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