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