399386bd31fc3f16bb39bc59e556e72d72c9ee28
[slock.git] / slock.c
1
2 /* See LICENSE file for license details. */
3 #define _XOPEN_SOURCE 500
4 #if HAVE_SHADOW_H
5 #include <shadow.h>
6 #endif
7
8 #include <ctype.h>
9 #include <errno.h>
10 #include <pwd.h>
11 #include <stdarg.h>
12 #include <stdlib.h>
13 #include <stdio.h>
14 #include <string.h>
15 #include <unistd.h>
16 #include <sys/types.h>
17 #include <X11/keysym.h>
18 #include <X11/Xlib.h>
19 #include <X11/Xutil.h>
20
21 #if HAVE_BSD_AUTH
22 #include <login_cap.h>
23 #include <bsd_auth.h>
24 #endif
25
26 typedef struct {
27         int screen;
28         Window root, win;
29         Pixmap pmap;
30         unsigned long colors[2];
31 } Lock;
32
33 static Lock **locks;
34 static int nscreens;
35 static Bool running = True;
36
37 static void
38 die(const char *errstr, ...) {
39         va_list ap;
40
41         va_start(ap, errstr);
42         vfprintf(stderr, errstr, ap);
43         va_end(ap);
44         exit(EXIT_FAILURE);
45 }
46
47 #ifdef __linux__
48 #include <fcntl.h>
49
50 static void
51 dontkillme(void) {
52         int fd;
53
54         fd = open("/proc/self/oom_score_adj", O_WRONLY);
55         if (fd < 0 && errno == ENOENT)
56                 return;
57         if (fd < 0 || write(fd, "-1000\n", 6) != 6 || close(fd) != 0)
58                 die("cannot disable the out-of-memory killer for this process\n");
59 }
60 #endif
61
62 #ifndef HAVE_BSD_AUTH
63 static const char *
64 getpw(void) { /* only run as root */
65         const char *rval;
66         struct passwd *pw;
67
68         errno = 0;
69         pw = getpwuid(getuid());
70         if (!pw) {
71                 if (errno)
72                         die("slock: getpwuid: %s\n", strerror(errno));
73                 else
74                         die("slock: cannot retrieve password entry (make sure to suid or sgid slock)\n");
75         }
76         endpwent();
77         rval =  pw->pw_passwd;
78
79 #if HAVE_SHADOW_H
80         if (rval[0] == 'x' && rval[1] == '\0') {
81                 struct spwd *sp;
82                 sp = getspnam(getenv("USER"));
83                 if(!sp)
84                         die("slock: cannot retrieve shadow entry (make sure to suid or sgid slock)\n");
85                 endspent();
86                 rval = sp->sp_pwdp;
87         }
88 #endif
89
90         /* drop privileges */
91         if (geteuid() == 0
92            && ((getegid() != pw->pw_gid && setgid(pw->pw_gid) < 0) || setuid(pw->pw_uid) < 0))
93                 die("slock: cannot drop privileges\n");
94         return rval;
95 }
96 #endif
97
98 static void
99 #ifdef HAVE_BSD_AUTH
100 readpw(Display *dpy)
101 #else
102 readpw(Display *dpy, const char *pws)
103 #endif
104 {
105         char buf[32], passwd[256];
106         int num, screen;
107         unsigned int len, llen;
108         KeySym ksym;
109         XEvent ev;
110
111         len = llen = 0;
112         running = True;
113
114         /* As "slock" stands for "Simple X display locker", the DPMS settings
115          * had been removed and you can set it with "xset" or some other
116          * utility. This way the user can easily set a customized DPMS
117          * timeout. */
118         while(running && !XNextEvent(dpy, &ev)) {
119                 if(ev.type == KeyPress) {
120                         buf[0] = 0;
121                         num = XLookupString(&ev.xkey, buf, sizeof buf, &ksym, 0);
122                         if(IsKeypadKey(ksym)) {
123                                 if(ksym == XK_KP_Enter)
124                                         ksym = XK_Return;
125                                 else if(ksym >= XK_KP_0 && ksym <= XK_KP_9)
126                                         ksym = (ksym - XK_KP_0) + XK_0;
127                         }
128                         if(IsFunctionKey(ksym) || IsKeypadKey(ksym)
129                                         || IsMiscFunctionKey(ksym) || IsPFKey(ksym)
130                                         || IsPrivateKeypadKey(ksym))
131                                 continue;
132                         switch(ksym) {
133                         case XK_Return:
134                                 passwd[len] = 0;
135 #ifdef HAVE_BSD_AUTH
136                                 running = !auth_userokay(getlogin(), NULL, "auth-xlock", passwd);
137 #else
138                                 running = !!strcmp(crypt(passwd, pws), pws);
139 #endif
140                                 if(running)
141                                         XBell(dpy, 100);
142                                 len = 0;
143                                 break;
144                         case XK_Escape:
145                                 len = 0;
146                                 break;
147                         case XK_BackSpace:
148                                 if(len)
149                                         --len;
150                                 break;
151                         default:
152                                 if(num && !iscntrl((int) buf[0]) && (len + num < sizeof passwd)) {
153                                         memcpy(passwd + len, buf, num);
154                                         len += num;
155                                 }
156                                 break;
157                         }
158                         if(llen == 0 && len != 0) {
159                                 for(screen = 0; screen < nscreens; screen++) {
160                                         XSetWindowBackground(dpy, locks[screen]->win, locks[screen]->colors[1]);
161                                         XClearWindow(dpy, locks[screen]->win);
162                                 }
163                         } else if(llen != 0 && len == 0) {
164                                 for(screen = 0; screen < nscreens; screen++) {
165                                         XSetWindowBackground(dpy, locks[screen]->win, locks[screen]->colors[0]);
166                                         XClearWindow(dpy, locks[screen]->win);
167                                 }
168                         }
169                         llen = len;
170                 }
171                 else for(screen = 0; screen < nscreens; screen++)
172                         XRaiseWindow(dpy, locks[screen]->win);
173         }
174 }
175
176 static void
177 unlockscreen(Display *dpy, Lock *lock) {
178         if(dpy == NULL || lock == NULL)
179                 return;
180
181         XUngrabPointer(dpy, CurrentTime);
182         XFreeColors(dpy, DefaultColormap(dpy, lock->screen), lock->colors, 2, 0);
183         XFreePixmap(dpy, lock->pmap);
184         XDestroyWindow(dpy, lock->win);
185
186         free(lock);
187 }
188
189 static Lock *
190 lockscreen(Display *dpy, int screen) {
191         char curs[] = {0, 0, 0, 0, 0, 0, 0, 0};
192         unsigned int len;
193         Lock *lock;
194         XColor color, dummy;
195         XSetWindowAttributes wa;
196         Cursor invisible;
197
198         if(dpy == NULL || screen < 0)
199                 return NULL;
200
201         lock = malloc(sizeof(Lock));
202         if(lock == NULL)
203                 return NULL;
204
205         lock->screen = screen;
206
207         lock->root = RootWindow(dpy, lock->screen);
208
209         /* init */
210         wa.override_redirect = 1;
211         wa.background_pixel = BlackPixel(dpy, lock->screen);
212         lock->win = XCreateWindow(dpy, lock->root, 0, 0, DisplayWidth(dpy, lock->screen), DisplayHeight(dpy, lock->screen),
213                         0, DefaultDepth(dpy, lock->screen), CopyFromParent,
214                         DefaultVisual(dpy, lock->screen), CWOverrideRedirect | CWBackPixel, &wa);
215         XAllocNamedColor(dpy, DefaultColormap(dpy, lock->screen), COLOR2, &color, &dummy);
216         lock->colors[1] = color.pixel;
217         XAllocNamedColor(dpy, DefaultColormap(dpy, lock->screen), COLOR1, &color, &dummy);
218         lock->colors[0] = color.pixel;
219         lock->pmap = XCreateBitmapFromData(dpy, lock->win, curs, 8, 8);
220         invisible = XCreatePixmapCursor(dpy, lock->pmap, lock->pmap, &color, &color, 0, 0);
221         XDefineCursor(dpy, lock->win, invisible);
222         XMapRaised(dpy, lock->win);
223         for(len = 1000; len; len--) {
224                 if(XGrabPointer(dpy, lock->root, False, ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
225                         GrabModeAsync, GrabModeAsync, None, invisible, CurrentTime) == GrabSuccess)
226                         break;
227                 usleep(1000);
228         }
229         if(running && (len > 0)) {
230                 for(len = 1000; len; len--) {
231                         if(XGrabKeyboard(dpy, lock->root, True, GrabModeAsync, GrabModeAsync, CurrentTime)
232                                 == GrabSuccess)
233                                 break;
234                         usleep(1000);
235                 }
236         }
237
238         running &= (len > 0);
239         if(!running) {
240                 unlockscreen(dpy, lock);
241                 lock = NULL;
242         }
243         else 
244                 XSelectInput(dpy, lock->root, SubstructureNotifyMask);
245
246         return lock;
247 }
248
249 static void
250 usage(void) {
251         fprintf(stderr, "usage: slock [-v]\n");
252         exit(EXIT_FAILURE);
253 }
254
255 int
256 main(int argc, char **argv) {
257 #ifndef HAVE_BSD_AUTH
258         const char *pws;
259 #endif
260         Display *dpy;
261         int screen;
262
263         if((argc == 2) && !strcmp("-v", argv[1]))
264                 die("slock-%s, © 2006-2012 Anselm R Garbe\n", VERSION);
265         else if(argc != 1)
266                 usage();
267
268 #ifdef __linux__
269         dontkillme();
270 #endif
271
272         if(!getpwuid(getuid()))
273                 die("slock: no passwd entry for you\n");
274
275 #ifndef HAVE_BSD_AUTH
276         pws = getpw();
277 #endif
278
279         if(!(dpy = XOpenDisplay(0)))
280                 die("slock: cannot open display\n");
281         /* Get the number of screens in display "dpy" and blank them all. */
282         nscreens = ScreenCount(dpy);
283         locks = malloc(sizeof(Lock *) * nscreens);
284         if(locks == NULL)
285                 die("slock: malloc: %s\n", strerror(errno));
286         int nlocks = 0;
287         for(screen = 0; screen < nscreens; screen++) {
288                 if ( (locks[screen] = lockscreen(dpy, screen)) != NULL)
289                         nlocks++;
290         }
291         XSync(dpy, False);
292
293         /* Did we actually manage to lock something? */
294         if (nlocks == 0) { // nothing to protect
295                 free(locks);
296                 XCloseDisplay(dpy);
297                 return 1;
298         }
299
300         /* Everything is now blank. Now wait for the correct password. */
301 #ifdef HAVE_BSD_AUTH
302         readpw(dpy);
303 #else
304         readpw(dpy, pws);
305 #endif
306
307         /* Password ok, unlock everything and quit. */
308         for(screen = 0; screen < nscreens; screen++)
309                 unlockscreen(dpy, locks[screen]);
310
311         free(locks);
312         XCloseDisplay(dpy);
313
314         return 0;
315 }