summaryrefslogtreecommitdiff
path: root/pinentry-dmenu.c
blob: 8ed5fa040ce34ce97c58c993b1f1a12bd2303258 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
/* See LICENSE file for copyright and license details. */
#include <ctype.h>
#include <libconfig.h>
#include <locale.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <pwd.h>
#include <time.h>
#include <unistd.h>

#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/Xutil.h>
#ifdef XINERAMA
#include <X11/extensions/Xinerama.h>
#endif
#include <X11/Xft/Xft.h>

#include "drw.h"
#include "util.h"

#include "pinentry/pinentry.h"
#include "pinentry/memory.h"

#define CONFIG "/.gnupg/pinentry-dmenu.conf"
#define INTERSECT(x, y, w, h, r) \
		(MAX(0, MIN((x)+(w),(r).x_org+(r).width)  - MAX((x),(r).x_org)) \
		 && MAX(0, MIN((y)+(h),(r).y_org+(r).height) - MAX((y),(r).y_org)))
#define LENGTH(X) (sizeof X / sizeof X[0])
#define TEXTW(X) (drw_fontset_getwidth(drw, (X)) + lrpad)
#define MINDESCLEN 8


enum { SchemePrompt, SchemeNormal, SchemeSelect, SchemeDesc, SchemeLast };
enum { WinPin, WinConfirm };
enum { Ok, NotOk, Cancel };
enum { Nothing, Yes, No };

static int bh, mw, mh;
static int sel;
static int promptw, ppromptw, pdescw;
/* Sum of left and right padding */
static int lrpad;
static size_t cursor;
static int mon = -1, screen;

static char* pin;

static Atom clip, utf8;
static Display *dpy;
static Window root, parentwin, win;
static XIC xic;

static Drw *drw;
static Clr *scheme[SchemeLast];

static int timed_out;
static int winmode;
pinentry_t pinentry;

#include "config.h"

static int
drawitem(const char* text, Bool sel, int x, int y, int w) {
	unsigned int i = (sel) ? SchemeSelect : SchemeNormal;

	drw_setscheme(drw, scheme[i]);

	return drw_text(drw, x, y, w, bh, lrpad / 2, text, 0);
}

static void
grabfocus(void) {
	Window focuswin;
	int i, revertwin;

	for (i = 0; i < 100; ++i) {
		XGetInputFocus(dpy, &focuswin, &revertwin);
		if (focuswin == win) {
			return;
		}
		XSetInputFocus(dpy, win, RevertToParent, CurrentTime);
		usleep(1000);
	}

	die("cannot grab focus");
}

static void
grabkeyboard(void) {
	int i;

	if (embedded) {
		return;
	}

	/* Try to grab keyboard,
	 * we may have to wait for another process to ungrab */
	for (i = 0; i < 1000; i++) {
		if (XGrabKeyboard(dpy, DefaultRootWindow(dpy), True, GrabModeAsync,
		                  GrabModeAsync, CurrentTime) == GrabSuccess) {
			return;
		}
		usleep(1000);
	}

	die("cannot grab keyboard");
}

static size_t
nextrune(int cursor, int inc) {
	ssize_t n;

	/* Return location of next utf8 rune in the given direction (+1 or -1) */
	for (n = cursor + inc;
	     n + inc >= 0 && (pin[n] & 0xc0) == 0x80;
	     n += inc);
	
	return n;
}

static void
insert(const char *str, ssize_t n) {
	int repeat;

	if (strlen(pin) + n > pinentry->pin_len - 1) {
		repeat = (pin == pinentry->pin) ? 0 : 1;

		if (!pinentry_setbufferlen(pinentry, 2 * pinentry->pin_len)) {
			printf("Error: Couldn't allocate secure memory\n");
			return;
		}

		pin = (repeat) ? pinentry->pin : pinentry->repeat_passphrase;
	}

	if (n > 0) {
		memcpy(&pin[cursor], str, n);
	}

	cursor += n;
	pin[cursor] = '\0';
}

static void
drawwin(void) {
	unsigned int curpos;
	int x = 0, pb, pbw = 0, i;
	size_t asterlen = strlen(asterisk);
	size_t pdesclen;
	int leftinput;
	char* censort = ecalloc(1, asterlen * pinentry->pin_len);
	
	unsigned int censortl = minpwlen * TEXTW(asterisk) / strlen(asterisk);
	unsigned int confirml = TEXTW(" YesNo ") + 3 * lrpad;

	drw_setscheme(drw, scheme[SchemeNormal]);
	drw_rect(drw, 0, 0, mw, mh, 1, 1);

	if (prompt) {
		drw_setscheme(drw, scheme[SchemePrompt]);
		x = drw_text(drw, x, 0, promptw, bh, lrpad / 2, prompt, 0);
	}

	if (pinentry->prompt) {
		drw_setscheme(drw, scheme[SchemePrompt]);
		drw_text(drw, x, 0, ppromptw, bh, lrpad / 2, pinentry->prompt, 0);
		x += ppromptw;
	}

	if (pinentry->description) {
		pb = mw - x;
		pdesclen = strlen(pinentry->description);
		
		if (pb > 0) {
			pb -= (winmode == WinPin) ? censortl : confirml;
			pbw = MINDESCLEN * pdescw / pdesclen;
			pbw = MIN(pbw, pdescw);

			if (pb >= pbw) {
				pbw = MAX(pbw, pdescw);
				pbw = MIN(pbw, pb);
				pb = mw - pbw;

				for (i = 0; i < pdesclen; i++) {
					if (pinentry->description[i] == '\n') {
						pinentry->description[i] = ' ';
					}
				}

				drw_setscheme(drw, scheme[SchemeDesc]);
				drw_text(drw, pb, 0, pbw, bh, lrpad / 2, pinentry->description,
				         0);
			} else {
				pbw = 0;
			}
		}
	}

	/* Draw input field */
	drw_setscheme(drw, scheme[SchemeNormal]);

	if (winmode == WinPin) {
		for (i = 0; i < asterlen * strlen(pin); i += asterlen) {
			memcpy(&censort[i], asterisk, asterlen);
		}

		censort[i+1] = '\n';
		leftinput = mw - x - pbw;
		drw_text(drw, x, 0, leftinput, bh, lrpad / 2, censort, 0);
		drw_font_getexts(drw->fonts, censort, cursor * asterlen, &curpos, NULL);

		if ((curpos += lrpad / 2 - 1) < leftinput) {
			drw_setscheme(drw, scheme[SchemeNormal]);
			drw_rect(drw, x + curpos, 2, 2, bh - 4, 1, 0);
		}
	} else {
		x += TEXTW(" ");
		x = drawitem("No", (sel == No), x, 0, TEXTW("No"));
		x = drawitem("Yes", (sel == Yes), x, 0, TEXTW("Yes"));
	}

	free(censort);
	drw_map(drw, win, 0, 0, mw, mh);
}

static void
setup_pin(char* pinlink) {
	pin = pinlink;
	pin[0] = '\0';
	cursor = 0;
}

static void
setup(void) {
	int x, y, i = 0;
	unsigned int du;
	XSetWindowAttributes swa;
	XIM xim;
	Window w, dw, *dws;
	XWindowAttributes wa;
#ifdef XINERAMA
	XineramaScreenInfo *info;
	Window pw;
	int a, j, di, n, area = 0;
#endif

	/* Init appearance */
	scheme[SchemePrompt] = drw_scm_create(drw, colors[SchemePrompt], 2);
	scheme[SchemeNormal] = drw_scm_create(drw, colors[SchemeNormal], 2);
	scheme[SchemeSelect] = drw_scm_create(drw, colors[SchemeSelect], 2);
	scheme[SchemeDesc]   = drw_scm_create(drw, colors[SchemeDesc],   2);

	clip = XInternAtom(dpy, "CLIPBOARD",   False);
	utf8 = XInternAtom(dpy, "UTF8_STRING", False);

	/* Calculate menu geometry */
	bh = drw->fonts->h + 2;
	mh = bh;
#ifdef XINERAMA
	info = XineramaQueryScreens(dpy, &n);

	if (parentwin == root && info) {
		XGetInputFocus(dpy, &w, &di);
		if (mon >= 0 && mon < n) {
			i = mon;
		} else if (w != root && w != PointerRoot && w != None) {
			/* Find top-level window containing current input focus */
			do {
				if (XQueryTree(dpy, (pw = w), &dw, &w, &dws, &du) && dws) {
					XFree(dws);
				}
			} while (w != root && w != pw);
			/* Find xinerama screen with which the window intersects most */
			if (XGetWindowAttributes(dpy, pw, &wa)) {
				for (j = 0; j < n; j++) {
					a = INTERSECT(wa.x, wa.y, wa.width, wa.height, info[j]);
					if (a > area) { 
						area = a;
						i = j;
					}
				}
			}
		}
		/* No focused window is on screen, so use pointer location instead */
		if (mon < 0 && !area
		    && XQueryPointer(dpy, root, &dw, &dw, &x, &y, &di, &di, &du)) {
			for (i = 0; i < n; i++) {
				if (INTERSECT(x, y, 1, 1, info[i])) {
					break;
				}
			}
		}

		x = info[i].x_org;
		y = info[i].y_org + (topbar ? 0 : info[i].height - mh);
		mw = info[i].width;
		XFree(info);
	} else
#endif
	{
		if (!XGetWindowAttributes(dpy, parentwin, &wa)) {
			die("could not get embedding window attributes: 0x%lx", parentwin);
		}
		x = 0;
		y = topbar ? 0 : wa.height - mh;
		mw = wa.width;
	}

	promptw = (prompt) ? TEXTW(prompt) - lrpad / 4 : 0;
	ppromptw = (pinentry->prompt) ? TEXTW(pinentry->prompt) : 0;
	pdescw = (pinentry->description) ? TEXTW(pinentry->description) : 0;

	/* Create menu window */
	swa.override_redirect = True;
	swa.background_pixel = scheme[SchemePrompt][ColBg].pixel;
	swa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
	win = XCreateWindow(dpy, parentwin, x, y, mw, mh, 0,
	                    CopyFromParent, CopyFromParent, CopyFromParent,
	                    CWOverrideRedirect | CWBackPixel | CWEventMask, &swa);

	/* Open input methods */
	xim = XOpenIM(dpy, NULL, NULL, NULL);
	xic = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
	                XNClientWindow, win, XNFocusWindow, win, NULL);
	XMapRaised(dpy, win);

	if (embedded) {
		XSelectInput(dpy, parentwin, FocusChangeMask);

		if (XQueryTree(dpy, parentwin, &dw, &w, &dws, &du) && dws) {
			for (i = 0; i < du && dws[i] != win; ++i) {
				XSelectInput(dpy, dws[i], FocusChangeMask);
			}

			XFree(dws);
		}
		grabfocus();
	}

	drw_resize(drw, mw, mh);
}

static void
cleanup(void) {
	XUngrabKey(dpy, AnyKey, AnyModifier, root);
	free(scheme[SchemeDesc]);
	free(scheme[SchemeSelect]);
	free(scheme[SchemeNormal]);
	free(scheme[SchemePrompt]);
	drw_free(drw);
	XSync(dpy, False);
	XCloseDisplay(dpy);
}

static int
keypress(XKeyEvent *ev) {
	char buf[32];
	int len;

	KeySym ksym = NoSymbol;
	Status status;
	len = XmbLookupString(xic, ev, buf, sizeof buf, &ksym, &status);
	
	if (status == XBufferOverflow) {
		return 0;
	}

	if (winmode == WinConfirm) {
		switch(ksym) {
		case XK_KP_Enter:
		case XK_Return:
			if (sel != Nothing) {
				return 1;
			}
			break;
		case XK_y:
		case XK_Y:
			sel = Yes;
			return 1;
		case XK_n:
		case XK_N:
			sel = No;
			return 1;
		case XK_Escape:
			pinentry->canceled = 1;
			sel = No;
			return 1;
		case XK_Left:
			sel = No;
			break;
		case XK_Right:
			sel = Yes;
			break;
		}
	} else {
		switch(ksym) {
		case XK_Delete:
			if (pin[cursor] == '\0') {
				return 0;
			}
			cursor = nextrune(cursor, +1);
			/* Fallthrough */
		case XK_BackSpace:
			if (cursor == 0) {
				return 0;
			}
			insert(NULL, nextrune(cursor, -1) - cursor);
			break;
		case XK_Escape:
			pinentry->canceled = 1;
			return 1;
			//Cleanup();
			//exit(1);
			break;
		case XK_Left:
			if (cursor > 0) {
				cursor = nextrune(cursor, -1);
			}
			break;
		case XK_Right:
			if (pin[cursor] != '\0') {
				cursor = nextrune(cursor, +1);
			}
			break;
		case XK_Return:
		case XK_KP_Enter:
			return 1;
			break;
		default:
			if (!iscntrl(*buf)) {
				insert(buf, len);
			}
		}
	}

	drawwin();

	return 0;
}

static void
paste(void) {
	char *p, *q;
	int di;
	unsigned long dl;
	Atom da;

	/* We have been given the current selection, now insert it into input */
	XGetWindowProperty(dpy, win, utf8, 0, (sizeof pin / 4) + 1, False,
	                   utf8, &da, &di, &dl, &dl, (unsigned char **)&p);
	insert(p, (q = strchr(p, '\n')) ? q - p : (ssize_t) strlen(p));
	XFree(p);
	drawwin();
}

void
run(void) {
	XEvent ev;

	drawwin();

	while (!XNextEvent(dpy, &ev)) {
		if (XFilterEvent(&ev, win)) {
			/* What is this I don't even */
			continue;
		}
		switch(ev.type) {
		case Expose:
			if (ev.xexpose.count == 0) {
				drw_map(drw, win, 0, 0, mw, mh);
			}
			break;
		case KeyPress:
			if (keypress(&ev.xkey)) {
				return;
			}
			break;
		case SelectionNotify:
			if (ev.xselection.property == utf8) {
				paste();
			}
			break;
		case VisibilityNotify:
			if (ev.xvisibility.state != VisibilityUnobscured) {
				XRaiseWindow(dpy, win);
			}
			break;
		}
	}
}

static void
catchsig(int sig) {
	if (sig == SIGALRM) {
		timed_out = 1;
	}
}

static int
password(void) {
	winmode = WinPin;

	setup_pin(pinentry->pin);
	run();

	if (pinentry->repeat_passphrase) {
		setup_pin(pinentry->repeat_passphrase);
		// TODO: Add repeat text
		run();

		if (strcmp(pinentry->pin, pinentry->repeat_passphrase)) {
			pinentry->repeat_okay = 0;
			return 0;
		}

		pinentry->repeat_okay = 1;
	}

	return (pinentry->canceled) ? -1 : 1;
}

static int
confirm(void) {
	winmode = WinConfirm;
	sel = Nothing;

	run();
	
	return sel != No;
}

static int
cmdhandler(pinentry_t received_pinentry) {
	struct sigaction sa;
	XWindowAttributes wa;
	int ret;
	
	pinentry = received_pinentry;

	if (!setlocale(LC_CTYPE, "") || !XSupportsLocale()) {
		fputs("warning: no locale support\n", stderr);
	}
	if (!(dpy = XOpenDisplay(pinentry->display))) {
		die("cannot open display");
	}
	screen = DefaultScreen(dpy);
	root = RootWindow(dpy, screen);
	embedded = (pinentry->parent_wid) ? embedded : 0;
	parentwin = (embedded) ? pinentry->parent_wid : root;
	if (!XGetWindowAttributes(dpy, parentwin, &wa)) {
		die("could not get embedding window attributes: 0x%lx", parentwin);
	}
	drw = drw_create(dpy, screen, root, wa.width, wa.height);
	if (!drw_fontset_create(drw, fonts, LENGTH(fonts))) {
		die("no fonts could be loaded.");
	}
	lrpad = drw->fonts->h;
	drw_setscheme(drw, scheme[SchemePrompt]);

	if (pinentry->timeout) {
		memset(&sa, 0, sizeof(sa));
		sa.sa_handler = catchsig;
		sigaction(SIGALRM, &sa, NULL);
		alarm(pinentry->timeout);
	}

	grabkeyboard();
	setup();

	if (pinentry->pin) {
		ret = password();
	} else {
		ret = confirm();
	}

	cleanup();

	return ret;
}

pinentry_cmd_handler_t pinentry_cmd_handler = cmdhandler;

int
main(int argc, char *argv[]) {
	Bool bval;
	int i, val;
	const char *str;
	char path[PATH_MAX];
	struct passwd *pw = getpwuid(getuid());
	config_t cfg;

	config_init(&cfg);
	i = strlen(pw->pw_dir);
	strcpy(path, pw->pw_dir);
	strcpy(&path[i], CONFIG);

	/* Read the file. If there is an error, report it and exit. */
	if (config_read_file(&cfg, path)) {
		if (config_lookup_string(&cfg, "asterisk", &str)) {
			asterisk = str;
		}
		if (config_lookup_bool(&cfg, "buttom", &bval)) {
			topbar = !bval;
		}
		if (config_lookup_int(&cfg, "min_password_length", &val)) {
			minpwlen = val;
		}
		if (config_lookup_int(&cfg, "monitor", &val)) {
			mon = val;
		}
		if (config_lookup_string(&cfg, "prompt", &str)) {
			prompt = str;
		}
		if (config_lookup_string(&cfg, "font", &str)) {
			fonts[0] = str;
		}
		if (config_lookup_string(&cfg, "prompt_bg", &str)) {
			colors[SchemePrompt][ColBg] = str;
		}
		if (config_lookup_string(&cfg, "prompt_fg", &str)) {
			colors[SchemePrompt][ColFg] = str;
		}
		if (config_lookup_string(&cfg, "normal_bg", &str)) {
			colors[SchemeNormal][ColBg] = str;
		}
		if (config_lookup_string(&cfg, "normal_fg", &str)) {
			colors[SchemeNormal][ColFg] = str;
		}
		if (config_lookup_string(&cfg, "select_bg", &str)) {
			colors[SchemeSelect][ColBg] = str;
		}
		if (config_lookup_string(&cfg, "select_fg", &str)) {
			colors[SchemeSelect][ColFg] = str;
		}
		if (config_lookup_string(&cfg, "desc_bg", &str)) {
			colors[SchemeDesc][ColBg] = str;
		}
		if (config_lookup_string(&cfg, "desc_fg", &str)) {
			colors[SchemeDesc][ColFg] = str;
		}
		if (config_lookup_bool(&cfg, "embedded", &bval)) {
			embedded = bval;
		}
	} else if ((str = config_error_file(&cfg))) {
		fprintf(stderr, "%s:%d: %s\n", config_error_file(&cfg),
		        config_error_line(&cfg), config_error_text(&cfg));
		return(EXIT_FAILURE);
	} else {
		printf("No config file found. Use defaults.\n");
	}

	pinentry_init("pinentry-dmenu");
	pinentry_parse_opts(argc, argv);
	
	if (pinentry_loop()) {
		return 1;
	}

	config_destroy(&cfg);
	
	return 0;
}