Add config option for cross requests from file URLs
[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                 if (a->b)
786                         setstyle(c, getstyle(geturi(c)));
787                 else
788                         webkit_user_content_manager_remove_all_style_sheets(
789                             webkit_web_view_get_user_content_manager(c->view));
790                 refresh = 0;
791                 break;
792         case ZoomLevel:
793                 webkit_web_view_set_zoom_level(c->view, a->f);
794                 return; /* do not update */
795         default:
796                 return; /* do nothing */
797         }
798
799         updatetitle(c);
800         if (refresh)
801                 reload(c, a);
802 }
803
804 const char *
805 getcert(const char *uri)
806 {
807         int i;
808
809         for (i = 0; i < LENGTH(certs); ++i) {
810                 if (certs[i].regex &&
811                     !regexec(&(certs[i].re), uri, 0, NULL, 0))
812                         return certs[i].file;
813         }
814
815         return NULL;
816 }
817
818 void
819 setcert(Client *c, const char *uri)
820 {
821         const char *file = getcert(uri);
822         char *host;
823         GTlsCertificate *cert;
824
825         if (!file)
826                 return;
827
828         if (!(cert = g_tls_certificate_new_from_file(file, NULL))) {
829                 fprintf(stderr, "Could not read certificate file: %s\n", file);
830                 return;
831         }
832
833         if ((uri = strstr(uri, "https://"))) {
834                 uri += sizeof("https://") - 1;
835                 host = g_strndup(uri, strchr(uri, '/') - uri);
836                 webkit_web_context_allow_tls_certificate_for_host(
837                     webkit_web_view_get_context(c->view), cert, host);
838                 g_free(host);
839         }
840
841         g_object_unref(cert);
842
843 }
844
845 const char *
846 getstyle(const char *uri)
847 {
848         int i;
849
850         if (stylefile)
851                 return stylefile;
852
853         for (i = 0; i < LENGTH(styles); ++i) {
854                 if (styles[i].regex &&
855                     !regexec(&(styles[i].re), uri, 0, NULL, 0))
856                         return styles[i].file;
857         }
858
859         return "";
860 }
861
862 void
863 setstyle(Client *c, const char *file)
864 {
865         gchar *style;
866
867         if (!g_file_get_contents(file, &style, NULL, NULL)) {
868                 fprintf(stderr, "Could not read style file: %s\n", file);
869                 return;
870         }
871
872         webkit_user_content_manager_add_style_sheet(
873             webkit_web_view_get_user_content_manager(c->view),
874             webkit_user_style_sheet_new(style,
875             WEBKIT_USER_CONTENT_INJECT_ALL_FRAMES,
876             WEBKIT_USER_STYLE_LEVEL_USER,
877             NULL, NULL));
878
879         g_free(style);
880 }
881
882 void
883 runscript(Client *c)
884 {
885         gchar *script;
886         gsize l;
887
888         if (g_file_get_contents(scriptfile, &script, &l, NULL) && l)
889                 evalscript(c, script);
890         g_free(script);
891 }
892
893 void
894 evalscript(Client *c, const char *jsstr, ...)
895 {
896         va_list ap;
897         gchar *script;
898
899         va_start(ap, jsstr);
900         script = g_strdup_vprintf(jsstr, ap);
901         va_end(ap);
902
903         webkit_web_view_run_javascript(c->view, script, NULL, NULL, NULL);
904         g_free(script);
905 }
906
907 void
908 updatewinid(Client *c)
909 {
910         snprintf(winid, LENGTH(winid), "%lu", c->xid);
911 }
912
913 void
914 handleplumb(Client *c, const char *uri)
915 {
916         Arg a = (Arg)PLUMB(uri);
917         spawn(c, &a);
918 }
919
920 void
921 newwindow(Client *c, const Arg *a, int noembed)
922 {
923         int i = 0;
924         char tmp[64];
925         const char *cmd[29], *uri;
926         const Arg arg = { .v = cmd };
927
928         cmd[i++] = argv0;
929         cmd[i++] = "-a";
930         cmd[i++] = curconfig[CookiePolicies].val.v;
931         cmd[i++] = curconfig[ScrollBars].val.b ? "-B" : "-b";
932         if (cookiefile && g_strcmp0(cookiefile, "")) {
933                 cmd[i++] = "-c";
934                 cmd[i++] = cookiefile;
935         }
936         if (stylefile && g_strcmp0(stylefile, "")) {
937                 cmd[i++] = "-C";
938                 cmd[i++] = stylefile;
939         }
940         cmd[i++] = curconfig[DiskCache].val.b ? "-D" : "-d";
941         if (embed && !noembed) {
942                 cmd[i++] = "-e";
943                 snprintf(tmp, LENGTH(tmp), "%lu", embed);
944                 cmd[i++] = tmp;
945         }
946         cmd[i++] = curconfig[RunInFullscreen].val.b ? "-F" : "-f" ;
947         cmd[i++] = curconfig[Geolocation].val.b ?     "-G" : "-g" ;
948         cmd[i++] = curconfig[LoadImages].val.b ?      "-I" : "-i" ;
949         cmd[i++] = curconfig[KioskMode].val.b ?       "-K" : "-k" ;
950         cmd[i++] = curconfig[Style].val.b ?           "-M" : "-m" ;
951         cmd[i++] = curconfig[Inspector].val.b ?       "-N" : "-n" ;
952         cmd[i++] = curconfig[Plugins].val.b ?         "-P" : "-p" ;
953         if (scriptfile && g_strcmp0(scriptfile, "")) {
954                 cmd[i++] = "-r";
955                 cmd[i++] = scriptfile;
956         }
957         cmd[i++] = curconfig[JavaScript].val.b ? "-S" : "-s";
958         cmd[i++] = curconfig[StrictTLS].val.b ? "-T" : "-t";
959         if (fulluseragent && g_strcmp0(fulluseragent, "")) {
960                 cmd[i++] = "-u";
961                 cmd[i++] = fulluseragent;
962         }
963         if (showxid)
964                 cmd[i++] = "-w";
965         cmd[i++] = curconfig[Certificate].val.b ? "-X" : "-x" ;
966         /* do not keep zoom level */
967         cmd[i++] = "--";
968         if ((uri = a->v))
969                 cmd[i++] = uri;
970         cmd[i] = NULL;
971
972         spawn(c, &arg);
973 }
974
975 void
976 spawn(Client *c, const Arg *a)
977 {
978         if (fork() == 0) {
979                 if (dpy)
980                         close(ConnectionNumber(dpy));
981                 setsid();
982                 execvp(((char **)a->v)[0], (char **)a->v);
983                 fprintf(stderr, "%s: execvp %s", argv0, ((char **)a->v)[0]);
984                 perror(" failed");
985                 exit(1);
986         }
987 }
988
989 void
990 destroyclient(Client *c)
991 {
992         Client *p;
993
994         webkit_web_view_stop_loading(c->view);
995         /* Not needed, has already been called
996         gtk_widget_destroy(c->win);
997          */
998
999         for (p = clients; p && p->next != c; p = p->next)
1000                 ;
1001         if (p)
1002                 p->next = c->next;
1003         else
1004                 clients = c->next;
1005         free(c);
1006 }
1007
1008 void
1009 cleanup(void)
1010 {
1011         while (clients)
1012                 destroyclient(clients);
1013         g_free(cookiefile);
1014         g_free(scriptfile);
1015         g_free(stylefile);
1016         g_free(cachedir);
1017         XCloseDisplay(dpy);
1018 }
1019
1020 WebKitWebView *
1021 newview(Client *c, WebKitWebView *rv)
1022 {
1023         WebKitWebView *v;
1024         WebKitSettings *settings;
1025         WebKitUserContentManager *contentmanager;
1026         WebKitWebContext *context;
1027
1028         /* Webview */
1029         if (rv) {
1030                 v = WEBKIT_WEB_VIEW(
1031                     webkit_web_view_new_with_related_view(rv));
1032         } else {
1033                 settings = webkit_settings_new_with_settings(
1034                    "allow-file-access-from-file-urls", curconfig[FileURLsCrossAccess].val.b,
1035                    "allow-universal-access-from-file-urls", curconfig[FileURLsCrossAccess].val.b,
1036                    "auto-load-images", curconfig[LoadImages].val.b,
1037                    "default-charset", curconfig[DefaultCharset].val.v,
1038                    "default-font-size", curconfig[FontSize].val.i,
1039                    "enable-caret-browsing", curconfig[CaretBrowsing].val.b,
1040                    "enable-developer-extras", curconfig[Inspector].val.b,
1041                    "enable-dns-prefetching", curconfig[DNSPrefetch].val.b,
1042                    "enable-frame-flattening", curconfig[FrameFlattening].val.b,
1043                    "enable-html5-database", curconfig[DiskCache].val.b,
1044                    "enable-html5-local-storage", curconfig[DiskCache].val.b,
1045                    "enable-java", curconfig[Java].val.b,
1046                    "enable-javascript", curconfig[JavaScript].val.b,
1047                    "enable-plugins", curconfig[Plugins].val.b,
1048                    "enable-accelerated-2d-canvas", curconfig[AcceleratedCanvas].val.b,
1049                    "enable-site-specific-quirks", curconfig[SiteQuirks].val.b,
1050                    "enable-smooth-scrolling", curconfig[SmoothScrolling].val.b,
1051                    "media-playback-requires-user-gesture", curconfig[MediaManualPlay].val.b,
1052                    NULL);
1053 /* For more interesting settings, have a look at
1054  * http://webkitgtk.org/reference/webkit2gtk/stable/WebKitSettings.html */
1055
1056                 if (strcmp(fulluseragent, "")) {
1057                         webkit_settings_set_user_agent(settings, fulluseragent);
1058                 } else if (surfuseragent) {
1059                         webkit_settings_set_user_agent_with_application_details(
1060                             settings, "Surf", VERSION);
1061                 }
1062                 useragent = webkit_settings_get_user_agent(settings);
1063
1064                 contentmanager = webkit_user_content_manager_new();
1065
1066                 context = webkit_web_context_new_with_website_data_manager(
1067                           webkit_website_data_manager_new(
1068                           "base-cache-directory", cachedir,
1069                           "base-data-directory", cachedir,
1070                           NULL));
1071
1072                 /* rendering process model, can be a shared unique one
1073                  * or one for each view */
1074                 webkit_web_context_set_process_model(context,
1075                     WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
1076                 /* TLS */
1077                 webkit_web_context_set_tls_errors_policy(context,
1078                     curconfig[StrictTLS].val.b ? WEBKIT_TLS_ERRORS_POLICY_FAIL :
1079                     WEBKIT_TLS_ERRORS_POLICY_IGNORE);
1080                 /* disk cache */
1081                 webkit_web_context_set_cache_model(context,
1082                     curconfig[DiskCache].val.b ? WEBKIT_CACHE_MODEL_WEB_BROWSER :
1083                     WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
1084
1085                 /* Currently only works with text file to be compatible with curl */
1086                 webkit_cookie_manager_set_persistent_storage(
1087                     webkit_web_context_get_cookie_manager(context), cookiefile,
1088                     WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT);
1089                 /* cookie policy */
1090                 webkit_cookie_manager_set_accept_policy(
1091                     webkit_web_context_get_cookie_manager(context),
1092                     cookiepolicy_get());
1093                 /* languages */
1094                 webkit_web_context_set_preferred_languages(context,
1095                     curconfig[PreferredLanguages].val.v);
1096                 webkit_web_context_set_spell_checking_languages(context,
1097                     curconfig[SpellLanguages].val.v);
1098                 webkit_web_context_set_spell_checking_enabled(context,
1099                     curconfig[SpellChecking].val.b);
1100
1101                 g_signal_connect(G_OBJECT(context), "download-started",
1102                                  G_CALLBACK(downloadstarted), c);
1103                 g_signal_connect(G_OBJECT(context), "initialize-web-extensions",
1104                                  G_CALLBACK(initwebextensions), c);
1105
1106                 v = g_object_new(WEBKIT_TYPE_WEB_VIEW,
1107                     "settings", settings,
1108                     "user-content-manager", contentmanager,
1109                     "web-context", context,
1110                     NULL);
1111         }
1112
1113         g_signal_connect(G_OBJECT(v), "notify::estimated-load-progress",
1114                          G_CALLBACK(progresschanged), c);
1115         g_signal_connect(G_OBJECT(v), "notify::title",
1116                          G_CALLBACK(titlechanged), c);
1117         g_signal_connect(G_OBJECT(v), "button-release-event",
1118                          G_CALLBACK(buttonreleased), c);
1119         g_signal_connect(G_OBJECT(v), "close",
1120                         G_CALLBACK(closeview), c);
1121         g_signal_connect(G_OBJECT(v), "create",
1122                          G_CALLBACK(createview), c);
1123         g_signal_connect(G_OBJECT(v), "decide-policy",
1124                          G_CALLBACK(decidepolicy), c);
1125         g_signal_connect(G_OBJECT(v), "insecure-content-detected",
1126                          G_CALLBACK(insecurecontent), c);
1127         g_signal_connect(G_OBJECT(v), "load-failed-with-tls-errors",
1128                          G_CALLBACK(loadfailedtls), c);
1129         g_signal_connect(G_OBJECT(v), "load-changed",
1130                          G_CALLBACK(loadchanged), c);
1131         g_signal_connect(G_OBJECT(v), "mouse-target-changed",
1132                          G_CALLBACK(mousetargetchanged), c);
1133         g_signal_connect(G_OBJECT(v), "permission-request",
1134                          G_CALLBACK(permissionrequested), c);
1135         g_signal_connect(G_OBJECT(v), "ready-to-show",
1136                          G_CALLBACK(showview), c);
1137
1138         return v;
1139 }
1140
1141 void
1142 initwebextensions(WebKitWebContext *wc, Client *c)
1143 {
1144         webkit_web_context_set_web_extensions_directory(wc, WEBEXTDIR);
1145 }
1146
1147 GtkWidget *
1148 createview(WebKitWebView *v, WebKitNavigationAction *a, Client *c)
1149 {
1150         Client *n;
1151
1152         switch (webkit_navigation_action_get_navigation_type(a)) {
1153         case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1154                 /*
1155                  * popup windows of type “other” are almost always triggered
1156                  * by user gesture, so inverse the logic here
1157                  */
1158 /* instead of this, compare destination uri to mouse-over uri for validating window */
1159                 if (webkit_navigation_action_is_user_gesture(a))
1160                         return NULL;
1161         case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1162         case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1163         case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1164         case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1165         case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1166                 n = newclient(c);
1167                 break;
1168         default:
1169                 return NULL;
1170         }
1171
1172         return GTK_WIDGET(n->view);
1173 }
1174
1175 gboolean
1176 buttonreleased(GtkWidget *w, GdkEvent *e, Client *c)
1177 {
1178         WebKitHitTestResultContext element;
1179         int i;
1180
1181         element = webkit_hit_test_result_get_context(c->mousepos);
1182
1183         for (i = 0; i < LENGTH(buttons); ++i) {
1184                 if (element & buttons[i].target &&
1185                     e->button.button == buttons[i].button &&
1186                     CLEANMASK(e->button.state) == CLEANMASK(buttons[i].mask) &&
1187                     buttons[i].func) {
1188                         buttons[i].func(c, &buttons[i].arg, c->mousepos);
1189                         return buttons[i].stopevent;
1190                 }
1191         }
1192
1193         return FALSE;
1194 }
1195
1196 GdkFilterReturn
1197 processx(GdkXEvent *e, GdkEvent *event, gpointer d)
1198 {
1199         Client *c = (Client *)d;
1200         XPropertyEvent *ev;
1201         Arg a;
1202
1203         if (((XEvent *)e)->type == PropertyNotify) {
1204                 ev = &((XEvent *)e)->xproperty;
1205                 if (ev->state == PropertyNewValue) {
1206                         if (ev->atom == atoms[AtomFind]) {
1207                                 find(c, NULL);
1208
1209                                 return GDK_FILTER_REMOVE;
1210                         } else if (ev->atom == atoms[AtomGo]) {
1211                                 a.v = getatom(c, AtomGo);
1212                                 loaduri(c, &a);
1213
1214                                 return GDK_FILTER_REMOVE;
1215                         }
1216                 }
1217         }
1218         return GDK_FILTER_CONTINUE;
1219 }
1220
1221 gboolean
1222 winevent(GtkWidget *w, GdkEvent *e, Client *c)
1223 {
1224         int i;
1225
1226         switch (e->type) {
1227         case GDK_ENTER_NOTIFY:
1228                 c->overtitle = c->targeturi;
1229                 updatetitle(c);
1230                 break;
1231         case GDK_KEY_PRESS:
1232                 if (!curconfig[KioskMode].val.b) {
1233                         for (i = 0; i < LENGTH(keys); ++i) {
1234                                 if (gdk_keyval_to_lower(e->key.keyval) ==
1235                                     keys[i].keyval &&
1236                                     CLEANMASK(e->key.state) == keys[i].mod &&
1237                                     keys[i].func) {
1238                                         updatewinid(c);
1239                                         keys[i].func(c, &(keys[i].arg));
1240                                         return TRUE;
1241                                 }
1242                         }
1243                 }
1244         case GDK_LEAVE_NOTIFY:
1245                 c->overtitle = NULL;
1246                 updatetitle(c);
1247                 break;
1248         case GDK_WINDOW_STATE:
1249                 if (e->window_state.changed_mask ==
1250                     GDK_WINDOW_STATE_FULLSCREEN)
1251                         c->fullscreen = e->window_state.new_window_state &
1252                                         GDK_WINDOW_STATE_FULLSCREEN;
1253                 break;
1254         default:
1255                 break;
1256         }
1257
1258         return FALSE;
1259 }
1260
1261 void
1262 showview(WebKitWebView *v, Client *c)
1263 {
1264         GdkRGBA bgcolor = { 0 };
1265         GdkWindow *gwin;
1266
1267         c->finder = webkit_web_view_get_find_controller(c->view);
1268         c->inspector = webkit_web_view_get_inspector(c->view);
1269
1270         c->win = createwindow(c);
1271
1272         gtk_container_add(GTK_CONTAINER(c->win), GTK_WIDGET(c->view));
1273         gtk_widget_show_all(c->win);
1274         gtk_widget_grab_focus(GTK_WIDGET(c->view));
1275
1276         gwin = gtk_widget_get_window(GTK_WIDGET(c->win));
1277         c->xid = gdk_x11_window_get_xid(gwin);
1278         updatewinid(c);
1279         if (showxid) {
1280                 gdk_display_sync(gtk_widget_get_display(c->win));
1281                 puts(winid);
1282         }
1283
1284         if (curconfig[HideBackground].val.b)
1285                 webkit_web_view_set_background_color(c->view, &bgcolor);
1286
1287         if (!curconfig[KioskMode].val.b) {
1288                 gdk_window_set_events(gwin, GDK_ALL_EVENTS_MASK);
1289                 gdk_window_add_filter(gwin, processx, c);
1290         }
1291
1292         if (curconfig[RunInFullscreen].val.b)
1293                 togglefullscreen(c, NULL);
1294
1295         if (curconfig[ZoomLevel].val.f != 1.0)
1296                 webkit_web_view_set_zoom_level(c->view,
1297                                                curconfig[ZoomLevel].val.f);
1298
1299         setatom(c, AtomFind, "");
1300         setatom(c, AtomUri, "about:blank");
1301 }
1302
1303 GtkWidget *
1304 createwindow(Client *c)
1305 {
1306         char *wmstr;
1307         GtkWidget *w;
1308
1309         if (embed) {
1310                 w = gtk_plug_new(embed);
1311         } else {
1312                 w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1313
1314                 wmstr = g_path_get_basename(argv0);
1315                 gtk_window_set_wmclass(GTK_WINDOW(w), wmstr, "Surf");
1316                 g_free(wmstr);
1317
1318                 wmstr = g_strdup_printf("%s[%lu]", "Surf",
1319                         webkit_web_view_get_page_id(c->view));
1320                 gtk_window_set_role(GTK_WINDOW(w), wmstr);
1321                 g_free(wmstr);
1322
1323                 gtk_window_set_default_size(GTK_WINDOW(w), winsize[0], winsize[1]);
1324         }
1325
1326         g_signal_connect(G_OBJECT(w), "destroy",
1327                          G_CALLBACK(destroywin), c);
1328         g_signal_connect(G_OBJECT(w), "enter-notify-event",
1329                          G_CALLBACK(winevent), c);
1330         g_signal_connect(G_OBJECT(w), "key-press-event",
1331                          G_CALLBACK(winevent), c);
1332         g_signal_connect(G_OBJECT(w), "leave-notify-event",
1333                          G_CALLBACK(winevent), c);
1334         g_signal_connect(G_OBJECT(w), "window-state-event",
1335                          G_CALLBACK(winevent), c);
1336
1337         return w;
1338 }
1339
1340 gboolean
1341 loadfailedtls(WebKitWebView *v, gchar *uri, GTlsCertificate *cert,
1342               GTlsCertificateFlags err, Client *c)
1343 {
1344         GString *errmsg = g_string_new(NULL);
1345         gchar *html, *pem;
1346
1347         c->failedcert = g_object_ref(cert);
1348         c->tlserr = err;
1349         c->errorpage = 1;
1350
1351         if (err & G_TLS_CERTIFICATE_UNKNOWN_CA)
1352                 g_string_append(errmsg,
1353                     "The signing certificate authority is not known.<br>");
1354         if (err & G_TLS_CERTIFICATE_BAD_IDENTITY)
1355                 g_string_append(errmsg,
1356                     "The certificate does not match the expected identity "
1357                     "of the site that it was retrieved from.<br>");
1358         if (err & G_TLS_CERTIFICATE_NOT_ACTIVATED)
1359                 g_string_append(errmsg,
1360                     "The certificate's activation time "
1361                     "is still in the future.<br>");
1362         if (err & G_TLS_CERTIFICATE_EXPIRED)
1363                 g_string_append(errmsg, "The certificate has expired.<br>");
1364         if (err & G_TLS_CERTIFICATE_REVOKED)
1365                 g_string_append(errmsg,
1366                     "The certificate has been revoked according to "
1367                     "the GTlsConnection's certificate revocation list.<br>");
1368         if (err & G_TLS_CERTIFICATE_INSECURE)
1369                 g_string_append(errmsg,
1370                     "The certificate's algorithm is considered insecure.<br>");
1371         if (err & G_TLS_CERTIFICATE_GENERIC_ERROR)
1372                 g_string_append(errmsg,
1373                     "Some error occurred validating the certificate.<br>");
1374
1375         g_object_get(cert, "certificate-pem", &pem, NULL);
1376         html = g_strdup_printf("<p>Could not validate TLS for “%s”<br>%s</p>"
1377                                "<p>You can inspect the following certificate "
1378                                "with Ctrl-t (default keybinding).</p>"
1379                                "<p><pre>%s</pre></p>", uri, errmsg->str, pem);
1380         g_free(pem);
1381         g_string_free(errmsg, TRUE);
1382
1383         webkit_web_view_load_alternate_html(c->view, html, uri, NULL);
1384         g_free(html);
1385
1386         return TRUE;
1387 }
1388
1389 void
1390 loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c)
1391 {
1392         const char *uri = geturi(c);
1393
1394         switch (e) {
1395         case WEBKIT_LOAD_STARTED:
1396                 setatom(c, AtomUri, uri);
1397                 c->title = uri;
1398                 c->https = c->insecure = 0;
1399                 seturiparameters(c, uri);
1400                 if (c->errorpage)
1401                         c->errorpage = 0;
1402                 else
1403                         g_clear_object(&c->failedcert);
1404                 break;
1405         case WEBKIT_LOAD_REDIRECTED:
1406                 setatom(c, AtomUri, uri);
1407                 c->title = uri;
1408                 seturiparameters(c, uri);
1409                 break;
1410         case WEBKIT_LOAD_COMMITTED:
1411                 c->https = webkit_web_view_get_tls_info(c->view, &c->cert,
1412                                                         &c->tlserr);
1413                 break;
1414         case WEBKIT_LOAD_FINISHED:
1415                 /* Disabled until we write some WebKitWebExtension for
1416                  * manipulating the DOM directly.
1417                 evalscript(c, "document.documentElement.style.overflow = '%s'",
1418                     enablescrollbars ? "auto" : "hidden");
1419                 */
1420                 runscript(c);
1421                 break;
1422         }
1423         updatetitle(c);
1424 }
1425
1426 void
1427 progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c)
1428 {
1429         c->progress = webkit_web_view_get_estimated_load_progress(c->view) *
1430                       100;
1431         updatetitle(c);
1432 }
1433
1434 void
1435 titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c)
1436 {
1437         c->title = webkit_web_view_get_title(c->view);
1438         updatetitle(c);
1439 }
1440
1441 void
1442 mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h, guint modifiers,
1443     Client *c)
1444 {
1445         WebKitHitTestResultContext hc = webkit_hit_test_result_get_context(h);
1446
1447         /* Keep the hit test to know where is the pointer on the next click */
1448         c->mousepos = h;
1449
1450         if (hc & OnLink)
1451                 c->targeturi = webkit_hit_test_result_get_link_uri(h);
1452         else if (hc & OnImg)
1453                 c->targeturi = webkit_hit_test_result_get_image_uri(h);
1454         else if (hc & OnMedia)
1455                 c->targeturi = webkit_hit_test_result_get_media_uri(h);
1456         else
1457                 c->targeturi = NULL;
1458
1459         c->overtitle = c->targeturi;
1460         updatetitle(c);
1461 }
1462
1463 gboolean
1464 permissionrequested(WebKitWebView *v, WebKitPermissionRequest *r, Client *c)
1465 {
1466         ParamName param = ParameterLast;
1467
1468         if (WEBKIT_IS_GEOLOCATION_PERMISSION_REQUEST(r)) {
1469                 param = Geolocation;
1470         } else if (WEBKIT_IS_USER_MEDIA_PERMISSION_REQUEST(r)) {
1471                 if (webkit_user_media_permission_is_for_audio_device(
1472                     WEBKIT_USER_MEDIA_PERMISSION_REQUEST(r)))
1473                         param = AccessMicrophone;
1474                 else if (webkit_user_media_permission_is_for_video_device(
1475                          WEBKIT_USER_MEDIA_PERMISSION_REQUEST(r)))
1476                         param = AccessWebcam;
1477         } else {
1478                 return FALSE;
1479         }
1480
1481         if (curconfig[param].val.b)
1482                 webkit_permission_request_allow(r);
1483         else
1484                 webkit_permission_request_deny(r);
1485
1486         return TRUE;
1487 }
1488
1489 gboolean
1490 decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
1491     WebKitPolicyDecisionType dt, Client *c)
1492 {
1493         switch (dt) {
1494         case WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION:
1495                 decidenavigation(d, c);
1496                 break;
1497         case WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION:
1498                 decidenewwindow(d, c);
1499                 break;
1500         case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
1501                 decideresource(d, c);
1502                 break;
1503         default:
1504                 webkit_policy_decision_ignore(d);
1505                 break;
1506         }
1507         return TRUE;
1508 }
1509
1510 void
1511 decidenavigation(WebKitPolicyDecision *d, Client *c)
1512 {
1513         WebKitNavigationAction *a =
1514             webkit_navigation_policy_decision_get_navigation_action(
1515             WEBKIT_NAVIGATION_POLICY_DECISION(d));
1516
1517         switch (webkit_navigation_action_get_navigation_type(a)) {
1518         case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1519         case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1520         case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1521         case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1522         case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED: /* fallthrough */
1523         case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1524         default:
1525                 /* Do not navigate to links with a "_blank" target (popup) */
1526                 if (webkit_navigation_policy_decision_get_frame_name(
1527                     WEBKIT_NAVIGATION_POLICY_DECISION(d))) {
1528                         webkit_policy_decision_ignore(d);
1529                 } else {
1530                         /* Filter out navigation to different domain ? */
1531                         /* get action→urirequest, copy and load in new window+view
1532                          * on Ctrl+Click ? */
1533                         webkit_policy_decision_use(d);
1534                 }
1535                 break;
1536         }
1537 }
1538
1539 void
1540 decidenewwindow(WebKitPolicyDecision *d, Client *c)
1541 {
1542         Arg arg;
1543         WebKitNavigationAction *a =
1544             webkit_navigation_policy_decision_get_navigation_action(
1545             WEBKIT_NAVIGATION_POLICY_DECISION(d));
1546
1547
1548         switch (webkit_navigation_action_get_navigation_type(a)) {
1549         case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1550         case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1551         case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1552         case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1553         case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1554                 /* Filter domains here */
1555 /* If the value of “mouse-button” is not 0, then the navigation was triggered by a mouse event.
1556  * test for link clicked but no button ? */
1557                 arg.v = webkit_uri_request_get_uri(
1558                         webkit_navigation_action_get_request(a));
1559                 newwindow(c, &arg, 0);
1560                 break;
1561         case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1562         default:
1563                 break;
1564         }
1565
1566         webkit_policy_decision_ignore(d);
1567 }
1568
1569 void
1570 decideresource(WebKitPolicyDecision *d, Client *c)
1571 {
1572         int i, isascii = 1;
1573         WebKitResponsePolicyDecision *r = WEBKIT_RESPONSE_POLICY_DECISION(d);
1574         WebKitURIResponse *res =
1575             webkit_response_policy_decision_get_response(r);
1576         const gchar *uri = webkit_uri_response_get_uri(res);
1577
1578         if (g_str_has_suffix(uri, "/favicon.ico")) {
1579                 webkit_policy_decision_ignore(d);
1580                 return;
1581         }
1582
1583         if (!g_str_has_prefix(uri, "http://")
1584             && !g_str_has_prefix(uri, "https://")
1585             && !g_str_has_prefix(uri, "about:")
1586             && !g_str_has_prefix(uri, "file://")
1587             && !g_str_has_prefix(uri, "data:")
1588             && !g_str_has_prefix(uri, "blob:")
1589             && strlen(uri) > 0) {
1590                 for (i = 0; i < strlen(uri); i++) {
1591                         if (!g_ascii_isprint(uri[i])) {
1592                                 isascii = 0;
1593                                 break;
1594                         }
1595                 }
1596                 if (isascii) {
1597                         handleplumb(c, uri);
1598                         webkit_policy_decision_ignore(d);
1599                         return;
1600                 }
1601         }
1602
1603         if (webkit_response_policy_decision_is_mime_type_supported(r)) {
1604                 webkit_policy_decision_use(d);
1605         } else {
1606                 webkit_policy_decision_ignore(d);
1607                 download(c, res);
1608         }
1609 }
1610
1611 void
1612 insecurecontent(WebKitWebView *v, WebKitInsecureContentEvent e, Client *c)
1613 {
1614         c->insecure = 1;
1615 }
1616
1617 void
1618 downloadstarted(WebKitWebContext *wc, WebKitDownload *d, Client *c)
1619 {
1620         g_signal_connect(G_OBJECT(d), "notify::response",
1621                          G_CALLBACK(responsereceived), c);
1622 }
1623
1624 void
1625 responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c)
1626 {
1627         download(c, webkit_download_get_response(d));
1628         webkit_download_cancel(d);
1629 }
1630
1631 void
1632 download(Client *c, WebKitURIResponse *r)
1633 {
1634         Arg a = (Arg)DOWNLOAD(webkit_uri_response_get_uri(r), geturi(c));
1635         spawn(c, &a);
1636 }
1637
1638 void
1639 closeview(WebKitWebView *v, Client *c)
1640 {
1641         gtk_widget_destroy(c->win);
1642 }
1643
1644 void
1645 destroywin(GtkWidget* w, Client *c)
1646 {
1647         destroyclient(c);
1648         if (!clients)
1649                 gtk_main_quit();
1650 }
1651
1652 void
1653 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d)
1654 {
1655         Arg a = {.v = text };
1656         if (text)
1657                 loaduri((Client *) d, &a);
1658 }
1659
1660 void
1661 reload(Client *c, const Arg *a)
1662 {
1663         if (a->b)
1664                 webkit_web_view_reload_bypass_cache(c->view);
1665         else
1666                 webkit_web_view_reload(c->view);
1667 }
1668
1669 void
1670 print(Client *c, const Arg *a)
1671 {
1672         webkit_print_operation_run_dialog(webkit_print_operation_new(c->view),
1673                                           GTK_WINDOW(c->win));
1674 }
1675
1676 void
1677 showcert(Client *c, const Arg *a)
1678 {
1679         GTlsCertificate *cert = c->failedcert ? c->failedcert : c->cert;
1680         GcrCertificate *gcrt;
1681         GByteArray *crt;
1682         GtkWidget *win;
1683         GcrCertificateWidget *wcert;
1684
1685         if (!cert)
1686                 return;
1687
1688         g_object_get(cert, "certificate", &crt, NULL);
1689         gcrt = gcr_simple_certificate_new(crt->data, crt->len);
1690         g_byte_array_unref(crt);
1691
1692         win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1693         wcert = gcr_certificate_widget_new(gcrt);
1694         g_object_unref(gcrt);
1695
1696         gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(wcert));
1697         gtk_widget_show_all(win);
1698 }
1699
1700 void
1701 clipboard(Client *c, const Arg *a)
1702 {
1703         if (a->b) { /* load clipboard uri */
1704                 gtk_clipboard_request_text(gtk_clipboard_get(
1705                                            GDK_SELECTION_PRIMARY),
1706                                            pasteuri, c);
1707         } else { /* copy uri */
1708                 gtk_clipboard_set_text(gtk_clipboard_get(
1709                                        GDK_SELECTION_PRIMARY), c->targeturi
1710                                        ? c->targeturi : geturi(c), -1);
1711         }
1712 }
1713
1714 void
1715 zoom(Client *c, const Arg *a)
1716 {
1717         if (a->i > 0)
1718                 webkit_web_view_set_zoom_level(c->view,
1719                                                curconfig[ZoomLevel].val.f + 0.1);
1720         else if (a->i < 0)
1721                 webkit_web_view_set_zoom_level(c->view,
1722                                                curconfig[ZoomLevel].val.f - 0.1);
1723         else
1724                 webkit_web_view_set_zoom_level(c->view, 1.0);
1725
1726         curconfig[ZoomLevel].val.f = webkit_web_view_get_zoom_level(c->view);
1727 }
1728
1729 void
1730 scroll(Client *c, const Arg *a)
1731 {
1732         GdkEvent *ev = gdk_event_new(GDK_KEY_PRESS);
1733
1734         gdk_event_set_device(ev, gdkkb);
1735         ev->key.window = gtk_widget_get_window(GTK_WIDGET(c->win));
1736         ev->key.state = GDK_CONTROL_MASK;
1737         ev->key.time = GDK_CURRENT_TIME;
1738
1739         switch (a->i) {
1740         case 'd':
1741                 ev->key.keyval = GDK_KEY_Down;
1742                 break;
1743         case 'D':
1744                 ev->key.keyval = GDK_KEY_Page_Down;
1745                 break;
1746         case 'l':
1747                 ev->key.keyval = GDK_KEY_Left;
1748                 break;
1749         case 'r':
1750                 ev->key.keyval = GDK_KEY_Right;
1751                 break;
1752         case 'U':
1753                 ev->key.keyval = GDK_KEY_Page_Up;
1754                 break;
1755         case 'u':
1756                 ev->key.keyval = GDK_KEY_Up;
1757                 break;
1758         }
1759
1760         gdk_event_put(ev);
1761 }
1762
1763 void
1764 navigate(Client *c, const Arg *a)
1765 {
1766         if (a->i < 0)
1767                 webkit_web_view_go_back(c->view);
1768         else if (a->i > 0)
1769                 webkit_web_view_go_forward(c->view);
1770 }
1771
1772 void
1773 stop(Client *c, const Arg *a)
1774 {
1775         webkit_web_view_stop_loading(c->view);
1776 }
1777
1778 void
1779 toggle(Client *c, const Arg *a)
1780 {
1781         curconfig[a->i].val.b ^= 1;
1782         setparameter(c, 1, (ParamName)a->i, &curconfig[a->i].val);
1783 }
1784
1785 void
1786 togglefullscreen(Client *c, const Arg *a)
1787 {
1788         /* toggling value is handled in winevent() */
1789         if (c->fullscreen)
1790                 gtk_window_unfullscreen(GTK_WINDOW(c->win));
1791         else
1792                 gtk_window_fullscreen(GTK_WINDOW(c->win));
1793 }
1794
1795 void
1796 togglecookiepolicy(Client *c, const Arg *a)
1797 {
1798         ++cookiepolicy;
1799         cookiepolicy %= strlen(curconfig[CookiePolicies].val.v);
1800
1801         setparameter(c, 0, CookiePolicies, NULL);
1802 }
1803
1804 void
1805 toggleinspector(Client *c, const Arg *a)
1806 {
1807         if (webkit_web_inspector_is_attached(c->inspector))
1808                 webkit_web_inspector_close(c->inspector);
1809         else if (curconfig[Inspector].val.b)
1810                 webkit_web_inspector_show(c->inspector);
1811 }
1812
1813 void
1814 find(Client *c, const Arg *a)
1815 {
1816         const char *s, *f;
1817
1818         if (a && a->i) {
1819                 if (a->i > 0)
1820                         webkit_find_controller_search_next(c->finder);
1821                 else
1822                         webkit_find_controller_search_previous(c->finder);
1823         } else {
1824                 s = getatom(c, AtomFind);
1825                 f = webkit_find_controller_get_search_text(c->finder);
1826
1827                 if (g_strcmp0(f, s) == 0) /* reset search */
1828                         webkit_find_controller_search(c->finder, "", findopts,
1829                                                       G_MAXUINT);
1830
1831                 webkit_find_controller_search(c->finder, s, findopts,
1832                                               G_MAXUINT);
1833
1834                 if (strcmp(s, "") == 0)
1835                         webkit_find_controller_search_finish(c->finder);
1836         }
1837 }
1838
1839 void
1840 clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h)
1841 {
1842         navigate(c, a);
1843 }
1844
1845 void
1846 clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h)
1847 {
1848         Arg arg;
1849
1850         arg.v = webkit_hit_test_result_get_link_uri(h);
1851         newwindow(c, &arg, a->b);
1852 }
1853
1854 void
1855 clickexternplayer(Client *c, const Arg *a, WebKitHitTestResult *h)
1856 {
1857         Arg arg;
1858
1859         arg = (Arg)VIDEOPLAY(webkit_hit_test_result_get_media_uri(h));
1860         spawn(c, &arg);
1861 }
1862
1863 int
1864 main(int argc, char *argv[])
1865 {
1866         Arg arg;
1867         Client *c;
1868
1869         memset(&arg, 0, sizeof(arg));
1870
1871         /* command line args */
1872         ARGBEGIN {
1873         case 'a':
1874                 defconfig CSETV(CookiePolicies, EARGF(usage()));
1875                 break;
1876         case 'b':
1877                 defconfig CSETB(ScrollBars, 0);
1878                 break;
1879         case 'B':
1880                 defconfig CSETB(ScrollBars, 1);
1881                 break;
1882         case 'c':
1883                 cookiefile = EARGF(usage());
1884                 break;
1885         case 'C':
1886                 stylefile = EARGF(usage());
1887                 break;
1888         case 'd':
1889                 defconfig CSETB(DiskCache, 0);
1890                 break;
1891         case 'D':
1892                 defconfig CSETB(DiskCache, 1);
1893                 break;
1894         case 'e':
1895                 embed = strtol(EARGF(usage()), NULL, 0);
1896                 break;
1897         case 'f':
1898                 defconfig CSETB(RunInFullscreen, 0);
1899                 break;
1900         case 'F':
1901                 defconfig CSETB(RunInFullscreen, 1);
1902                 break;
1903         case 'g':
1904                 defconfig CSETB(Geolocation, 0);
1905                 break;
1906         case 'G':
1907                 defconfig CSETB(Geolocation, 1);
1908                 break;
1909         case 'i':
1910                 defconfig CSETB(LoadImages, 0);
1911                 break;
1912         case 'I':
1913                 defconfig CSETB(LoadImages, 1);
1914                 break;
1915         case 'k':
1916                 defconfig CSETB(KioskMode, 0);
1917                 break;
1918         case 'K':
1919                 defconfig CSETB(KioskMode, 1);
1920                 break;
1921         case 'm':
1922                 defconfig CSETB(Style, 0);
1923                 break;
1924         case 'M':
1925                 defconfig CSETB(Style, 1);
1926                 break;
1927         case 'n':
1928                 defconfig CSETB(Inspector, 0);
1929                 break;
1930         case 'N':
1931                 defconfig CSETB(Inspector, 1);
1932                 break;
1933         case 'p':
1934                 defconfig CSETB(Plugins, 0);
1935                 break;
1936         case 'P':
1937                 defconfig CSETB(Plugins, 1);
1938                 break;
1939         case 'r':
1940                 scriptfile = EARGF(usage());
1941                 break;
1942         case 's':
1943                 defconfig CSETB(JavaScript, 0);
1944                 break;
1945         case 'S':
1946                 defconfig CSETB(JavaScript, 1);
1947                 break;
1948         case 't':
1949                 defconfig CSETB(StrictTLS, 0);
1950                 break;
1951         case 'T':
1952                 defconfig CSETB(StrictTLS, 1);
1953                 break;
1954         case 'u':
1955                 fulluseragent = EARGF(usage());
1956                 break;
1957         case 'v':
1958                 die("surf-"VERSION", see LICENSE for © details\n");
1959         case 'w':
1960                 showxid = 1;
1961                 break;
1962         case 'x':
1963                 defconfig CSETB(Certificate, 0);
1964                 break;
1965         case 'X':
1966                 defconfig CSETB(Certificate, 1);
1967                 break;
1968         case 'z':
1969                 defconfig CSETF(ZoomLevel, strtof(EARGF(usage()), NULL));
1970                 break;
1971         default:
1972                 usage();
1973         } ARGEND;
1974         if (argc > 0)
1975                 arg.v = argv[0];
1976         else
1977                 arg.v = "about:blank";
1978
1979         setup();
1980         c = newclient(NULL);
1981         showview(NULL, c);
1982
1983         loaduri(c, &arg);
1984         updatetitle(c);
1985
1986         gtk_main();
1987         cleanup();
1988
1989         return 0;
1990 }