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