1 /* SLiM - Simple Login Manager
2 Copyright (C) 1997, 1998 Per Liden
3 Copyright (C) 2004-06 Simone Rota <sip@varlock.com>
4 Copyright (C) 2004-06 Johannes Winkelmann <jw@tks6.net>
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
10 */
11
12 #include <sys/types.h>
13 #include <sys/stat.h>
14 #include <unistd.h>
15 #include <fcntl.h>
16 #include <stdint.h>
17 #include <login_cap.h>
18 #include <cstring>
19 #include <cstdio>
20 #include <iostream>
21 #include <fstream>
22 #include <sstream>
23 #include <vector>
24 #include <algorithm>
25
26 #include "app.h"
27 #include "numlock.h"
28 #include "util.h"
29
30 #ifdef HAVE_SHADOW
31 #include <shadow.h>
32 #endif
33
34 using namespace std;
35
36 static const int LOGIN_CAP_VAR_COUNT = 4;
37 static const char* LOGIN_CAP_VARS[] = {
38 "lang",
39 "charset",
40 "timezone",
41 "manpath",
42 };
43 static const char* LOGIN_CAP_ENVS[] = {
44 "LANG",
45 "MM_CHARSET",
46 "TZ",
47 "MANPATH",
48 };
49
50 #ifdef USE_PAM
51 #include <string>
52
conv(int num_msg,const struct pam_message ** msg,struct pam_response ** resp,void * appdata_ptr)53 int conv(int num_msg, const struct pam_message **msg,
54 struct pam_response **resp, void *appdata_ptr){
55 *resp = (struct pam_response *) calloc(num_msg, sizeof(struct pam_response));
56 Panel* panel = *static_cast<Panel**>(appdata_ptr);
57 int result = PAM_SUCCESS;
58 for (int i=0; i<num_msg; i++){
59 (*resp)[i].resp=0;
60 (*resp)[i].resp_retcode=0;
61 switch(msg[i]->msg_style){
62 case PAM_PROMPT_ECHO_ON:
63 /* We assume PAM is asking for the username */
64 panel->EventHandler(Panel::Get_Name);
65 switch(panel->getAction()){
66 case Panel::Suspend:
67 case Panel::Halt:
68 case Panel::Reboot:
69 (*resp)[i].resp=strdup("root");
70 break;
71
72 case Panel::Console:
73 case Panel::Exit:
74 case Panel::Login:
75 (*resp)[i].resp=strdup(panel->GetName().c_str());
76 break;
77 default:
78 break;
79 }
80 break;
81
82 case PAM_PROMPT_ECHO_OFF:
83 /* We assume PAM is asking for the password */
84 switch(panel->getAction()){
85 case Panel::Console:
86 case Panel::Exit:
87 /* We should leave now! */
88 result=PAM_CONV_ERR;
89 break;
90
91 default:
92 panel->EventHandler(Panel::Get_Passwd);
93 (*resp)[i].resp=strdup(panel->GetPasswd().c_str());
94 break;
95 }
96 break;
97
98 case PAM_ERROR_MSG:
99 case PAM_TEXT_INFO:
100 /* We simply write these to the log
101 TODO: Maybe we should simply ignore them */
102 logStream << APPNAME << ": " << msg[i]->msg << endl;
103 break;
104 }
105 if (result!=PAM_SUCCESS) break;
106 }
107 if (result!=PAM_SUCCESS){
108 for (int i=0; i<num_msg; i++){
109 if ((*resp)[i].resp==0) continue;
110 free((*resp)[i].resp);
111 (*resp)[i].resp=0;
112 };
113 free(*resp);
114 *resp=0;
115 };
116 return result;
117 }
118 #endif
119
120 extern App* LoginApp;
121
xioerror(Display * disp)122 int xioerror(Display *disp) {
123 LoginApp->RestartServer();
124 return 0;
125 }
126
CatchSignal(int sig)127 void CatchSignal(int sig) {
128 logStream << APPNAME << ": unexpected signal " << sig << endl;
129
130 if (LoginApp->isServerStarted())
131 LoginApp->StopServer();
132
133 LoginApp->RemoveLock();
134 exit(ERR_EXIT);
135 }
136
User1Signal(int sig)137 void User1Signal(int sig) {
138 signal(sig, User1Signal);
139 }
140
AddToEnv(char *** curr_env,const char * name,const char * value)141 static void AddToEnv(char*** curr_env, const char *name, const char *value) {
142 int n;
143 for (n = 0; (*curr_env)[n] != NULL; n++) ;
144 n++;
145 char** new_env = static_cast<char**>(malloc(sizeof(char*) * (n + 1)));
146 memcpy(new_env, *curr_env, sizeof(char*) * n);
147 char* entry = static_cast<char*>(malloc(strlen(name) + strlen(value) + 2));
148 strcpy(entry, name);
149 strcat(entry, "=");
150 strcat(entry, value);
151 new_env[n-1] = entry;
152 new_env[n] = NULL;
153 free(*curr_env);
154 *curr_env = new_env;
155 }
156
157 #ifdef USE_PAM
App(int argc,char ** argv)158 App::App(int argc, char** argv)
159 : pam(conv, static_cast<void*>(&LoginPanel)),
160 #else
161 App::App(int argc, char** argv)
162 :
163 #endif
164 mcookiesize(32) /* Must be divisible by 4 */
165 {
166 int tmp;
167 ServerPID = -1;
168 testing = false;
169 serverStarted = false;
170 mcookie = string(App::mcookiesize, 'a');
171 daemonmode = false;
172 force_nodaemon = false;
173 firstlogin = true;
174 Dpy = NULL;
175
176 /* Parse command line
177 Note: we force a option for nodaemon switch to handle "-nodaemon" */
178 while((tmp = getopt(argc, argv, "vhp:n:d?")) != EOF) {
179 switch (tmp) {
180 case 'p': /* Test theme */
181 testtheme = optarg;
182 testing = true;
183 if (testtheme == NULL) {
184 logStream << "The -p option requires an argument" << endl;
185 exit(ERR_EXIT);
186 }
187 break;
188 case 'd': /* Daemon mode */
189 daemonmode = true;
190 break;
191 case 'n': /* Daemon mode */
192 daemonmode = false;
193 force_nodaemon = true;
194 break;
195 case 'v': /* Version */
196 std::cout << APPNAME << " version " << VERSION << endl;
197 exit(OK_EXIT);
198 break;
199 case '?': /* Illegal */
200 logStream << endl;
201 case 'h': /* Help */
202 logStream << "usage: " << APPNAME << " [option ...]" << endl
203 << "options:" << endl
204 << " -d: daemon mode" << endl
205 << " -nodaemon: no-daemon mode" << endl
206 << " -v: show version" << endl
207 << " -p /path/to/theme/dir: preview theme" << endl;
208 exit(OK_EXIT);
209 break;
210 }
211 }
212 #ifndef XNEST_DEBUG
213 if (getuid() != 0 && !testing) {
214 logStream << APPNAME << ": only root can run this program" << endl;
215 exit(ERR_EXIT);
216 }
217 #endif /* XNEST_DEBUG */
218
219 }
220
Run()221 void App::Run() {
222 DisplayName = DISPLAY;
223
224 #ifdef XNEST_DEBUG
225 char* p = getenv("DISPLAY");
226 if (p && p[0]) {
227 DisplayName = p;
228 cout << "Using display name " << DisplayName << endl;
229 }
230 #endif
231
232 /* Read configuration and theme */
233 cfg = new Cfg;
234 cfg->readConf(CFGFILE);
235 string themebase = "";
236 string themefile = "";
237 string themedir = "";
238 themeName = "";
239 if (testing) {
240 themeName = testtheme;
241 } else {
242 themebase = string(THEMESDIR) + "/";
243 themeName = cfg->getOption("current_theme");
244 string::size_type pos;
245 if ((pos = themeName.find(",")) != string::npos) {
246 /* input is a set */
247 themeName = findValidRandomTheme(themeName);
248 if (themeName == "") {
249 themeName = "default";
250 }
251 }
252 }
253
254 #ifdef USE_PAM
255 try{
256 pam.start("slim");
257 pam.set_item(PAM::Authenticator::TTY, DisplayName);
258 pam.set_item(PAM::Authenticator::Requestor, "root");
259 }
260 catch(PAM::Exception& e){
261 logStream << APPNAME << ": " << e << endl;
262 exit(ERR_EXIT);
263 };
264 #endif
265
266 bool loaded = false;
267 while (!loaded) {
268 themedir = themebase + themeName;
269 themefile = themedir + THEMESFILE;
270 if (!cfg->readConf(themefile)) {
271 if (themeName == "default") {
272 logStream << APPNAME << ": Failed to open default theme file "
273 << themefile << endl;
274 exit(ERR_EXIT);
275 } else {
276 logStream << APPNAME << ": Invalid theme in config: "
277 << themeName << endl;
278 themeName = "default";
279 }
280 } else {
281 loaded = true;
282 }
283 }
284
285 if (!testing) {
286 /* Create lock file */
287 LoginApp->GetLock();
288
289 /* Start x-server */
290 setenv("DISPLAY", DisplayName, 1);
291 signal(SIGQUIT, CatchSignal);
292 signal(SIGTERM, CatchSignal);
293 signal(SIGKILL, CatchSignal);
294 signal(SIGINT, CatchSignal);
295 signal(SIGHUP, CatchSignal);
296 signal(SIGPIPE, CatchSignal);
297 signal(SIGUSR1, User1Signal);
298
299 #ifndef XNEST_DEBUG
300 if (!force_nodaemon && cfg->getOption("daemon") == "yes") {
301 daemonmode = true;
302 }
303
304 /* Daemonize */
305 if (daemonmode) {
306 if (daemon(0, 0) == -1) {
307 logStream << APPNAME << ": " << strerror(errno) << endl;
308 exit(ERR_EXIT);
309 }
310 }
311
312 OpenLog();
313
314 if (daemonmode)
315 UpdatePid();
316
317 CreateServerAuth();
318 StartServer();
319 #endif
320
321 }
322
323 /* Open display */
324 if((Dpy = XOpenDisplay(DisplayName)) == 0) {
325 logStream << APPNAME << ": could not open display '"
326 << DisplayName << "'" << endl;
327 if (!testing) StopServer();
328 exit(ERR_EXIT);
329 }
330
331 /* Get screen and root window */
332 Scr = DefaultScreen(Dpy);
333 Root = RootWindow(Dpy, Scr);
334
335 // Intern _XROOTPMAP_ID property
336 BackgroundPixmapId = XInternAtom(Dpy, "_XROOTPMAP_ID", False);
337
338 /* for tests we use a standard window */
339 if (testing) {
340 Window RealRoot = RootWindow(Dpy, Scr);
341 Root = XCreateSimpleWindow(Dpy, RealRoot, 0, 0, 1280, 1024, 0, 0, 0);
342 XMapWindow(Dpy, Root);
343 XFlush(Dpy);
344 } else {
345 blankScreen();
346 }
347
348 HideCursor();
349
350 /* Create panel */
351 LoginPanel = new Panel(Dpy, Scr, Root, cfg, themedir, Panel::Mode_DM);
352 bool firstloop = true; /* 1st time panel is shown (for automatic username) */
353 bool focuspass = cfg->getOption("focus_password")=="yes";
354 bool autologin = cfg->getOption("auto_login")=="yes";
355
356 if (firstlogin && cfg->getOption("default_user") != "") {
357 LoginPanel->SetName(cfg->getOption("default_user") );
358 #ifdef USE_PAM
359 pam.set_item(PAM::Authenticator::User, cfg->getOption("default_user").c_str());
360 #endif
361 firstlogin = false;
362 if (autologin) {
363 Login();
364 }
365 }
366
367 /* Set NumLock */
368 string numlock = cfg->getOption("numlock");
369 if (numlock == "on") {
370 NumLock::setOn(Dpy);
371 } else if (numlock == "off") {
372 NumLock::setOff(Dpy);
373 }
374
375 /* Start looping */
376 int panelclosed = 1;
377 Panel::ActionType Action;
378
379 while(1) {
380 if(panelclosed) {
381 /* Init root */
382 setBackground(themedir);
383
384 /* Close all clients */
385 if (!testing) {
386 KillAllClients(False);
387 KillAllClients(True);
388 }
389
390 /* Show panel */
391 LoginPanel->OpenPanel();
392 }
393
394 LoginPanel->Reset();
395
396 if (firstloop && cfg->getOption("default_user") != "") {
397 LoginPanel->SetName(cfg->getOption("default_user") );
398 }
399
400 if (firstloop) {
401 LoginPanel->SwitchSession();
402 }
403
404 if (!AuthenticateUser(focuspass && firstloop)){
405 panelclosed = 0;
406 firstloop = false;
407 LoginPanel->ClearPanel();
408 XBell(Dpy, 100);
409 continue;
410 }
411
412 firstloop = false;
413
414 Action = LoginPanel->getAction();
415 /* for themes test we just quit */
416 if (testing) {
417 Action = Panel::Exit;
418 }
419 panelclosed = 1;
420 LoginPanel->ClosePanel();
421
422 switch(Action) {
423 case Panel::Login:
424 Login();
425 break;
426 case Panel::Console:
427 Console();
428 break;
429 case Panel::Reboot:
430 Reboot();
431 break;
432 case Panel::Halt:
433 Halt();
434 break;
435 case Panel::Suspend:
436 Suspend();
437 break;
438 case Panel::Exit:
439 Exit();
440 break;
441 default:
442 break;
443 }
444 }
445 }
446
447 #ifdef USE_PAM
AuthenticateUser(bool focuspass)448 bool App::AuthenticateUser(bool focuspass){
449 /* Reset the username */
450 try{
451 if (!focuspass)
452 pam.set_item(PAM::Authenticator::User, 0);
453 pam.authenticate();
454 }
455 catch(PAM::Auth_Exception& e){
456 switch(LoginPanel->getAction()){
457 case Panel::Exit:
458 case Panel::Console:
459 return true; /* <--- This is simply fake! */
460 default:
461 break;
462 };
463 logStream << APPNAME << ": " << e << endl;
464 return false;
465 }
466 catch(PAM::Exception& e){
467 logStream << APPNAME << ": " << e << endl;
468 exit(ERR_EXIT);
469 };
470 return true;
471 }
472 #else
AuthenticateUser(bool focuspass)473 bool App::AuthenticateUser(bool focuspass){
474 if (!focuspass){
475 LoginPanel->EventHandler(Panel::Get_Name);
476 switch(LoginPanel->getAction()){
477 case Panel::Exit:
478 case Panel::Console:
479 logStream << APPNAME << ": Got a special command (" << LoginPanel->GetName() << ")" << endl;
480 return true; /* <--- This is simply fake! */
481 default:
482 break;
483 }
484 }
485 LoginPanel->EventHandler(Panel::Get_Passwd);
486
487 char *encrypted, *correct;
488 struct passwd *pw;
489
490 switch(LoginPanel->getAction()){
491 case Panel::Suspend:
492 case Panel::Halt:
493 case Panel::Reboot:
494 pw = getpwnam("root");
495 break;
496 case Panel::Console:
497 case Panel::Exit:
498 case Panel::Login:
499 pw = getpwnam(LoginPanel->GetName().c_str());
500 break;
501 }
502 endpwent();
503 if(pw == 0)
504 return false;
505
506 #ifdef HAVE_SHADOW
507 struct spwd *sp = getspnam(pw->pw_name);
508 endspent();
509 if(sp)
510 correct = sp->sp_pwdp;
511 else
512 #endif /* HAVE_SHADOW */
513 correct = pw->pw_passwd;
514
515 if(correct == 0 || correct[0] == '\0')
516 return true;
517
518 encrypted = crypt(LoginPanel->GetPasswd().c_str(), correct);
519 return ((encrypted && strcmp(encrypted, correct) == 0) ? true : false);
520 }
521 #endif
522
GetServerPID()523 int App::GetServerPID() {
524 return ServerPID;
525 }
526
527 /* Hide the cursor */
HideCursor()528 void App::HideCursor() {
529 if (cfg->getOption("hidecursor") == "true") {
530 XColor black;
531 char cursordata[1];
532 Pixmap cursorpixmap;
533 Cursor cursor;
534 cursordata[0]=0;
535 cursorpixmap=XCreateBitmapFromData(Dpy,Root,cursordata,1,1);
536 black.red=0;
537 black.green=0;
538 black.blue=0;
539 cursor=XCreatePixmapCursor(Dpy,cursorpixmap,cursorpixmap,&black,&black,0,0);
540 XDefineCursor(Dpy,Root,cursor);
541 }
542 }
543
Login()544 void App::Login() {
545 struct passwd *pw;
546 pid_t pid;
547
548 #ifdef USE_PAM
549 try{
550 pam.open_session();
551 pw = getpwnam(static_cast<const char*>(pam.get_item(PAM::Authenticator::User)));
552 }
553 catch(PAM::Cred_Exception& e){
554 /* Credentials couldn't be established */
555 logStream << APPNAME << ": " << e << endl;
556 return;
557 }
558 catch(PAM::Exception& e){
559 logStream << APPNAME << ": " << e << endl;
560 exit(ERR_EXIT);
561 };
562 #else
563 pw = getpwnam(LoginPanel->GetName().c_str());
564 #endif
565 endpwent();
566 if(pw == 0)
567 return;
568 if (pw->pw_shell[0] == '\0') {
569 setusershell();
570 strcpy(pw->pw_shell, getusershell());
571 endusershell();
572 }
573
574 /* Setup the environment */
575 char* term = getenv("TERM");
576 string maildir = _PATH_MAILDIR;
577 maildir.append("/");
578 maildir.append(pw->pw_name);
579 string xauthority = pw->pw_dir;
580 xauthority.append("/.Xauthority");
581
582 #ifdef USE_PAM
583 /* Setup the PAM environment */
584 try{
585 if(term) pam.setenv("TERM", term);
586 pam.setenv("HOME", pw->pw_dir);
587 pam.setenv("PWD", pw->pw_dir);
588 pam.setenv("SHELL", pw->pw_shell);
589 pam.setenv("USER", pw->pw_name);
590 pam.setenv("LOGNAME", pw->pw_name);
591 pam.setenv("PATH", cfg->getOption("default_path").c_str());
592 pam.setenv("DISPLAY", DisplayName);
593 pam.setenv("MAIL", maildir.c_str());
594 pam.setenv("XAUTHORITY", xauthority.c_str());
595 }
596 catch(PAM::Exception& e){
597 logStream << APPNAME << ": " << e << endl;
598 exit(ERR_EXIT);
599 }
600 #endif
601
602 #ifdef USE_CONSOLEKIT
603 /* Setup the ConsoleKit session */
604 try {
605 ck.open_session(DisplayName, pw->pw_uid);
606 }
607 catch(Ck::Exception &e) {
608 logStream << APPNAME << ": " << e << endl;
609 exit(ERR_EXIT);
610 }
611 #endif
612
613 /* Create new process */
614 pid = fork();
615 if(pid == 0) {
616 #ifdef USE_PAM
617 /* Get a copy of the environment and close the child's copy */
618 /* of the PAM-handle. */
619 char** child_env = pam.getenvlist();
620
621 # ifdef USE_CONSOLEKIT
622 char** old_env = child_env;
623
624 /* Grow the copy of the environment for the session cookie */
625 int n;
626 for(n = 0; child_env[n] != NULL ; n++);
627
628 n++;
629
630 child_env = static_cast<char**>(malloc(sizeof(char*)*(n+1)));
631 memcpy(child_env, old_env, sizeof(char*)*n);
632 child_env[n - 1] = StrConcat("XDG_SESSION_COOKIE=", ck.get_xdg_session_cookie());
633 child_env[n] = NULL;
634 # endif /* USE_CONSOLEKIT */
635 #else
636
637 # ifdef USE_CONSOLEKIT
638 const int Num_Of_Variables = 12; /* Number of env. variables + 1 */
639 # else
640 const int Num_Of_Variables = 11; /* Number of env. variables + 1 */
641 # endif /* USE_CONSOLEKIT */
642 char** child_env = static_cast<char**>(malloc(sizeof(char*)*Num_Of_Variables));
643 int n = 0;
644 if(term) child_env[n++]=StrConcat("TERM=", term);
645 child_env[n++]=StrConcat("HOME=", pw->pw_dir);
646 child_env[n++]=StrConcat("PWD=", pw->pw_dir);
647 child_env[n++]=StrConcat("SHELL=", pw->pw_shell);
648 child_env[n++]=StrConcat("USER=", pw->pw_name);
649 child_env[n++]=StrConcat("LOGNAME=", pw->pw_name);
650 child_env[n++]=StrConcat("PATH=", cfg->getOption("default_path").c_str());
651 child_env[n++]=StrConcat("DISPLAY=", DisplayName);
652 child_env[n++]=StrConcat("MAIL=", maildir.c_str());
653 child_env[n++]=StrConcat("XAUTHORITY=", xauthority.c_str());
654 # ifdef USE_CONSOLEKIT
655 child_env[n++]=StrConcat("XDG_SESSION_COOKIE=", ck.get_xdg_session_cookie());
656 # endif /* USE_CONSOLEKIT */
657 child_env[n++]=0;
658
659 #endif
660
661 login_cap_t *lc = login_getpwclass(pw);
662 if (lc != NULL) {
663 for (int i = 0; i < LOGIN_CAP_VAR_COUNT; i++) {
664 const char *value = login_getcapstr(lc, LOGIN_CAP_VARS[i], NULL, NULL);
665 if (value != NULL) {
666 AddToEnv(&child_env, LOGIN_CAP_ENVS[i], value);
667 }
668 }
669 login_close(lc);
670 }
671
672 /* Login process starts here */
673 SwitchUser Su(pw, cfg, DisplayName, child_env);
674 string session = LoginPanel->getSession();
675 string loginCommand = cfg->getOption("login_cmd");
676 replaceVariables(loginCommand, SESSION_VAR, session);
677 replaceVariables(loginCommand, THEME_VAR, themeName);
678 string sessStart = cfg->getOption("sessionstart_cmd");
679 if (sessStart != "") {
680 replaceVariables(sessStart, USER_VAR, pw->pw_name);
681 system(sessStart.c_str());
682 }
683 Su.Login(loginCommand.c_str(), mcookie.c_str());
684 _exit(OK_EXIT);
685 }
686
687 #ifndef XNEST_DEBUG
688 CloseLog();
689 #endif
690
691 /* Wait until user is logging out (login process terminates) */
692 pid_t wpid = -1;
693 int status;
694 while (wpid != pid) {
695 wpid = wait(&status);
696 if (wpid == ServerPID)
697 xioerror(Dpy); /* Server died, simulate IO error */
698 }
699 if (WIFEXITED(status) && WEXITSTATUS(status)) {
700 LoginPanel->Message("Failed to execute login command");
701 sleep(3);
702 } else {
703 string sessStop = cfg->getOption("sessionstop_cmd");
704 if (sessStop != "") {
705 replaceVariables(sessStop, USER_VAR, pw->pw_name);
706 system(sessStop.c_str());
707 }
708 }
709
710 #ifdef USE_CONSOLEKIT
711 try {
712 ck.close_session();
713 }
714 catch(Ck::Exception &e) {
715 logStream << APPNAME << ": " << e << endl;
716 };
717 #endif
718
719 #ifdef USE_PAM
720 try{
721 pam.close_session();
722 }
723 catch(PAM::Exception& e){
724 logStream << APPNAME << ": " << e << endl;
725 };
726 #endif
727
728 /* Close all clients */
729 KillAllClients(False);
730 KillAllClients(True);
731
732 /* Send HUP signal to clientgroup */
733 killpg(pid, SIGHUP);
734
735 /* Send TERM signal to clientgroup, if error send KILL */
736 if(killpg(pid, SIGTERM))
737 killpg(pid, SIGKILL);
738
739 HideCursor();
740
741 #ifndef XNEST_DEBUG
742 /* Re-activate log file */
743 OpenLog();
744 RestartServer();
745 #endif
746
747 }
748
Reboot()749 void App::Reboot() {
750 #ifdef USE_PAM
751 try{
752 pam.end();
753 }
754 catch(PAM::Exception& e){
755 logStream << APPNAME << ": " << e << endl;
756 };
757 #endif
758
759 /* Write message */
760 LoginPanel->Message((char*)cfg->getOption("reboot_msg").c_str());
761 sleep(3);
762
763 /* Stop server and reboot */
764 StopServer();
765 RemoveLock();
766 system(cfg->getOption("reboot_cmd").c_str());
767 exit(OK_EXIT);
768 }
769
770
Halt()771 void App::Halt() {
772 #ifdef USE_PAM
773 try{
774 pam.end();
775 }
776 catch(PAM::Exception& e){
777 logStream << APPNAME << ": " << e << endl;
778 };
779 #endif
780
781 /* Write message */
782 LoginPanel->Message((char*)cfg->getOption("shutdown_msg").c_str());
783 sleep(3);
784
785 /* Stop server and halt */
786 StopServer();
787 RemoveLock();
788 system(cfg->getOption("halt_cmd").c_str());
789 exit(OK_EXIT);
790 }
791
Suspend()792 void App::Suspend() {
793 sleep(1);
794 system(cfg->getOption("suspend_cmd").c_str());
795 }
796
797
Console()798 void App::Console() {
799 int posx = 40;
800 int posy = 40;
801 int fontx = 9;
802 int fonty = 15;
803 int width = (XWidthOfScreen(ScreenOfDisplay(Dpy, Scr)) - (posx * 2)) / fontx;
804 int height = (XHeightOfScreen(ScreenOfDisplay(Dpy, Scr)) - (posy * 2)) / fonty;
805
806 /* Execute console */
807 const char* cmd = cfg->getOption("console_cmd").c_str();
808 char *tmp = new char[strlen(cmd) + 60];
809 sprintf(tmp, cmd, width, height, posx, posy, fontx, fonty);
810 system(tmp);
811 delete [] tmp;
812 }
813
814
Exit()815 void App::Exit() {
816 #ifdef USE_PAM
817 try{
818 pam.end();
819 }
820 catch(PAM::Exception& e){
821 logStream << APPNAME << ": " << e << endl;
822 };
823 #endif
824
825 if (testing) {
826 const char* testmsg = "This is a test message :-)";
827 LoginPanel->Message(testmsg);
828 sleep(3);
829 delete LoginPanel;
830 XCloseDisplay(Dpy);
831 } else {
832 delete LoginPanel;
833 StopServer();
834 RemoveLock();
835 }
836 delete cfg;
837 exit(OK_EXIT);
838 }
839
CatchErrors(Display * dpy,XErrorEvent * ev)840 int CatchErrors(Display *dpy, XErrorEvent *ev) {
841 return 0;
842 }
843
RestartServer()844 void App::RestartServer() {
845 #ifdef USE_PAM
846 try{
847 pam.end();
848 }
849 catch(PAM::Exception& e){
850 logStream << APPNAME << ": " << e << endl;
851 };
852 #endif
853
854 StopServer();
855 RemoveLock();
856 while (waitpid(-1, NULL, WNOHANG) > 0); /* Collects all dead childrens */
857 Run();
858 }
859
KillAllClients(Bool top)860 void App::KillAllClients(Bool top) {
861 Window dummywindow;
862 Window *children;
863 unsigned int nchildren;
864 unsigned int i;
865 XWindowAttributes attr;
866
867 XSync(Dpy, 0);
868 XSetErrorHandler(CatchErrors);
869
870 nchildren = 0;
871 XQueryTree(Dpy, Root, &dummywindow, &dummywindow, &children, &nchildren);
872 if(!top) {
873 for(i=0; i<nchildren; i++) {
874 if(XGetWindowAttributes(Dpy, children[i], &attr) && (attr.map_state == IsViewable))
875 children[i] = XmuClientWindow(Dpy, children[i]);
876 else
877 children[i] = 0;
878 }
879 }
880
881 for(i=0; i<nchildren; i++) {
882 if(children[i])
883 XKillClient(Dpy, children[i]);
884 }
885 XFree((char *)children);
886
887 XSync(Dpy, 0);
888 XSetErrorHandler(NULL);
889 }
890
891
ServerTimeout(int timeout,char * text)892 int App::ServerTimeout(int timeout, char* text) {
893 int i = 0;
894 int pidfound = -1;
895 static char *lasttext;
896
897 for(;;) {
898 pidfound = waitpid(ServerPID, NULL, WNOHANG);
899 if(pidfound == ServerPID)
900 break;
901 if(timeout) {
902 if(i == 0 && text != lasttext)
903 logStream << endl << APPNAME << ": waiting for " << text;
904 else
905 logStream << ".";
906 }
907 if(timeout)
908 sleep(1);
909 if(++i > timeout)
910 break;
911 }
912
913 if(i > 0)
914 logStream << endl;
915 lasttext = text;
916
917 return (ServerPID != pidfound);
918 }
919
920
WaitForServer()921 int App::WaitForServer() {
922 int ncycles = 120;
923 int cycles;
924
925 for(cycles = 0; cycles < ncycles; cycles++) {
926 if((Dpy = XOpenDisplay(DisplayName))) {
927 XSetIOErrorHandler(xioerror);
928 return 1;
929 } else {
930 if(!ServerTimeout(1, (char *) "X server to begin accepting connections"))
931 break;
932 }
933 }
934
935 logStream << "Giving up." << endl;
936
937 return 0;
938 }
939
940
StartServer()941 int App::StartServer() {
942 ServerPID = fork();
943
944 static const int MAX_XSERVER_ARGS = 256;
945 static char* server[MAX_XSERVER_ARGS+2] = { NULL };
946 server[0] = (char *)cfg->getOption("default_xserver").c_str();
947 string argOption = cfg->getOption("xserver_arguments");
948 /* Add mandatory -xauth option */
949 argOption = argOption + " -auth " + cfg->getOption("authfile");
950 char* args = new char[argOption.length()+2]; /* NULL plus vt */
951 strcpy(args, argOption.c_str());
952
953 serverStarted = false;
954
955 int argc = 1;
956 int pos = 0;
957 bool hasVtSet = false;
958 while (args[pos] != '\0') {
959 if (args[pos] == ' ' || args[pos] == '\t') {
960 *(args+pos) = '\0';
961 server[argc++] = args+pos+1;
962 } else if (pos == 0) {
963 server[argc++] = args+pos;
964 }
965 ++pos;
966
967 if (argc+1 >= MAX_XSERVER_ARGS) {
968 /* ignore _all_ arguments to make sure the server starts at */
969 /* all */
970 argc = 1;
971 break;
972 }
973 }
974
975 for (int i=0; i<argc; i++) {
976 if (server[i][0] == 'v' && server[i][1] == 't') {
977 bool ok = false;
978 Cfg::string2int(server[i]+2, &ok);
979 if (ok) {
980 hasVtSet = true;
981 }
982 }
983 }
984
985 if (!hasVtSet && daemonmode) {
986 server[argc++] = (char*)"vt09";
987 }
988 server[argc] = NULL;
989
990 switch(ServerPID) {
991 case 0:
992 signal(SIGTTIN, SIG_IGN);
993 signal(SIGTTOU, SIG_IGN);
994 signal(SIGUSR1, SIG_IGN);
995 setpgid(0,getpid());
996
997 execvp(server[0], server);
998 logStream << APPNAME << ": X server could not be started" << endl;
999 exit(ERR_EXIT);
1000 break;
1001
1002 case -1:
1003 break;
1004
1005 default:
1006 errno = 0;
1007 if(!ServerTimeout(0, (char *)"")) {
1008 ServerPID = -1;
1009 break;
1010 }
1011
1012 /* Wait for server to start up */
1013 if(WaitForServer() == 0) {
1014 logStream << APPNAME << ": unable to connect to X server" << endl;
1015 StopServer();
1016 ServerPID = -1;
1017 exit(ERR_EXIT);
1018 }
1019 break;
1020 }
1021
1022 delete [] args;
1023
1024 serverStarted = true;
1025
1026 return ServerPID;
1027 }
1028
1029 jmp_buf CloseEnv;
IgnoreXIO(Display * d)1030 int IgnoreXIO(Display *d) {
1031 logStream << APPNAME << ": connection to X server lost." << endl;
1032 longjmp(CloseEnv, 1);
1033 }
1034
StopServer()1035 void App::StopServer() {
1036 signal(SIGQUIT, SIG_IGN);
1037 signal(SIGINT, SIG_IGN);
1038 signal(SIGHUP, SIG_IGN);
1039 signal(SIGPIPE, SIG_IGN);
1040 signal(SIGTERM, SIG_DFL);
1041 signal(SIGKILL, SIG_DFL);
1042
1043 /* Catch X error */
1044 XSetIOErrorHandler(IgnoreXIO);
1045 if(!setjmp(CloseEnv) && Dpy)
1046 XCloseDisplay(Dpy);
1047
1048 /* Send HUP to process group */
1049 errno = 0;
1050 if((killpg(getpid(), SIGHUP) != 0) && (errno != ESRCH))
1051 logStream << APPNAME << ": can't send HUP to process group " << getpid() << endl;
1052
1053 /* Send TERM to server */
1054 if(ServerPID < 0)
1055 return;
1056 errno = 0;
1057 if(killpg(ServerPID, SIGTERM) < 0) {
1058 if(errno == EPERM) {
1059 logStream << APPNAME << ": can't kill X server" << endl;
1060 exit(ERR_EXIT);
1061 }
1062 if(errno == ESRCH)
1063 return;
1064 }
1065
1066 /* Wait for server to shut down */
1067 if(!ServerTimeout(10, (char *)"X server to shut down")) {
1068 logStream << endl;
1069 return;
1070 }
1071
1072 logStream << endl << APPNAME << ": X server slow to shut down, sending KILL signal." << endl;
1073
1074 /* Send KILL to server */
1075 errno = 0;
1076 if(killpg(ServerPID, SIGKILL) < 0) {
1077 if(errno == ESRCH)
1078 return;
1079 }
1080
1081 /* Wait for server to die */
1082 if(ServerTimeout(3, (char*)"server to die")) {
1083 logStream << endl << APPNAME << ": can't kill server" << endl;
1084 exit(ERR_EXIT);
1085 }
1086 logStream << endl;
1087 }
1088
blankScreen()1089 void App::blankScreen()
1090 {
1091 GC gc = XCreateGC(Dpy, Root, 0, 0);
1092 XSetForeground(Dpy, gc, BlackPixel(Dpy, Scr));
1093 XFillRectangle(Dpy, Root, gc, 0, 0,
1094 XWidthOfScreen(ScreenOfDisplay(Dpy, Scr)),
1095 XHeightOfScreen(ScreenOfDisplay(Dpy, Scr)));
1096 XFlush(Dpy);
1097 XFreeGC(Dpy, gc);
1098
1099 }
1100
setBackground(const string & themedir)1101 void App::setBackground(const string& themedir) {
1102 string filename;
1103 filename = themedir + "/background.png";
1104 image = new Image;
1105 bool loaded = image->Read(filename.c_str());
1106 if (!loaded){ /* try jpeg if png failed */
1107 filename = themedir + "/background.jpg";
1108 loaded = image->Read(filename.c_str());
1109 }
1110 if (loaded) {
1111 string bgstyle = cfg->getOption("background_style");
1112 if (bgstyle == "stretch") {
1113 image->Resize(XWidthOfScreen(ScreenOfDisplay(Dpy, Scr)), XHeightOfScreen(ScreenOfDisplay(Dpy, Scr)));
1114 } else if (bgstyle == "tile") {
1115 image->Tile(XWidthOfScreen(ScreenOfDisplay(Dpy, Scr)), XHeightOfScreen(ScreenOfDisplay(Dpy, Scr)));
1116 } else if (bgstyle == "center") {
1117 string hexvalue = cfg->getOption("background_color");
1118 hexvalue = hexvalue.substr(1,6);
1119 image->Center(XWidthOfScreen(ScreenOfDisplay(Dpy, Scr)), XHeightOfScreen(ScreenOfDisplay(Dpy, Scr)),
1120 hexvalue.c_str());
1121 } else { /* plain color or error */
1122 string hexvalue = cfg->getOption("background_color");
1123 hexvalue = hexvalue.substr(1,6);
1124 image->Center(XWidthOfScreen(ScreenOfDisplay(Dpy, Scr)), XHeightOfScreen(ScreenOfDisplay(Dpy, Scr)),
1125 hexvalue.c_str());
1126 }
1127 Pixmap p = image->createPixmap(Dpy, Scr, Root);
1128 XSetWindowBackgroundPixmap(Dpy, Root, p);
1129 XChangeProperty(Dpy, Root, BackgroundPixmapId, XA_PIXMAP, 32,
1130 PropModeReplace, (unsigned char *)&p, 1);
1131 }
1132 XClearWindow(Dpy, Root);
1133
1134 XFlush(Dpy);
1135 delete image;
1136 }
1137
1138 /* Check if there is a lockfile and a corresponding process */
GetLock()1139 void App::GetLock() {
1140 std::ifstream lockfile(cfg->getOption("lockfile").c_str());
1141 if (!lockfile) {
1142 /* no lockfile present, create one */
1143 std::ofstream lockfile(cfg->getOption("lockfile").c_str(), ios_base::out);
1144 if (!lockfile) {
1145 logStream << APPNAME << ": Could not create lock file: " << cfg->getOption("lockfile").c_str() << std::endl;
1146 exit(ERR_EXIT);
1147 }
1148 lockfile << getpid() << std::endl;
1149 lockfile.close();
1150 } else {
1151 /* lockfile present, read pid from it */
1152 int pid = 0;
1153 lockfile >> pid;
1154 lockfile.close();
1155 if (pid > 0) {
1156 /* see if process with this pid exists */
1157 int ret = kill(pid, 0);
1158 if (ret == 0 || (ret == -1 && errno == EPERM) ) {
1159 logStream << APPNAME << ": Another instance of the program is already running with PID " << pid << std::endl;
1160 exit(0);
1161 } else {
1162 logStream << APPNAME << ": Stale lockfile found, removing it" << std::endl;
1163 std::ofstream lockfile(cfg->getOption("lockfile").c_str(), ios_base::out);
1164 if (!lockfile) {
1165 logStream << APPNAME << ": Could not create new lock file: " << cfg->getOption("lockfile") << std::endl;
1166 exit(ERR_EXIT);
1167 }
1168 lockfile << getpid() << std::endl;
1169 lockfile.close();
1170 }
1171 }
1172 }
1173 }
1174
1175 /* Remove lockfile and close logs */
RemoveLock()1176 void App::RemoveLock() {
1177 remove(cfg->getOption("lockfile").c_str());
1178 }
1179
1180 /* Get server start check flag. */
isServerStarted()1181 bool App::isServerStarted() {
1182 return serverStarted;
1183 }
1184
1185 /* Redirect stdout and stderr to log file */
OpenLog()1186 void App::OpenLog() {
1187
1188 if ( !logStream.openLog( cfg->getOption("logfile").c_str() ) ) {
1189 logStream << APPNAME << ": Could not accesss log file: " << cfg->getOption("logfile") << endl;
1190 RemoveLock();
1191 exit(ERR_EXIT);
1192 }
1193 /* I should set the buffers to imediate write, but I just flush on every << operation. */
1194 }
1195
1196 /* Relases stdout/err */
CloseLog()1197 void App::CloseLog(){
1198 /* Simply closing the log */
1199 logStream.closeLog();
1200 }
1201
findValidRandomTheme(const string & set)1202 string App::findValidRandomTheme(const string& set)
1203 {
1204 /* extract random theme from theme set; return empty string on error */
1205 string name = set;
1206 struct stat buf;
1207
1208 if (name[name.length()-1] == ',') {
1209 name = name.substr(0, name.length() - 1);
1210 }
1211
1212 Util::srandom(Util::makeseed());
1213
1214 vector<string> themes;
1215 string themefile;
1216 Cfg::split(themes, name, ',');
1217 do {
1218 int sel = Util::random() % themes.size();
1219
1220 name = Cfg::Trim(themes[sel]);
1221 themefile = string(THEMESDIR) +"/" + name + THEMESFILE;
1222 if (stat(themefile.c_str(), &buf) != 0) {
1223 themes.erase(find(themes.begin(), themes.end(), name));
1224 logStream << APPNAME << ": Invalid theme in config: "
1225 << name << endl;
1226 name = "";
1227 }
1228 } while (name == "" && themes.size());
1229 return name;
1230 }
1231
1232
replaceVariables(string & input,const string & var,const string & value)1233 void App::replaceVariables(string& input,
1234 const string& var,
1235 const string& value)
1236 {
1237 string::size_type pos = 0;
1238 int len = var.size();
1239 while ((pos = input.find(var, pos)) != string::npos) {
1240 input = input.substr(0, pos) + value + input.substr(pos+len);
1241 }
1242 }
1243
1244 /*
1245 * We rely on the fact that all bits generated by Util::random()
1246 * are usable, so we are taking full words from its output.
1247 */
CreateServerAuth()1248 void App::CreateServerAuth() {
1249 /* create mit cookie */
1250 uint16_t word;
1251 uint8_t hi, lo;
1252 int i;
1253 string authfile;
1254 const char *digits = "0123456789abcdef";
1255 Util::srandom(Util::makeseed());
1256 for (i = 0; i < App::mcookiesize; i+=4) {
1257 word = Util::random() & 0xffff;
1258 lo = word & 0xff;
1259 hi = word >> 8;
1260 mcookie[i] = digits[lo & 0x0f];
1261 mcookie[i+1] = digits[lo >> 4];
1262 mcookie[i+2] = digits[hi & 0x0f];
1263 mcookie[i+3] = digits[hi >> 4];
1264 }
1265 /* reinitialize auth file */
1266 authfile = cfg->getOption("authfile");
1267 remove(authfile.c_str());
1268 putenv(StrConcat("XAUTHORITY=", authfile.c_str()));
1269 Util::add_mcookie(mcookie, ":0", cfg->getOption("xauth_path"),
1270 authfile);
1271 }
1272
StrConcat(const char * str1,const char * str2)1273 char* App::StrConcat(const char* str1, const char* str2) {
1274 char* tmp = new char[strlen(str1) + strlen(str2) + 1];
1275 strcpy(tmp, str1);
1276 strcat(tmp, str2);
1277 return tmp;
1278 }
1279
UpdatePid()1280 void App::UpdatePid() {
1281 std::ofstream lockfile(cfg->getOption("lockfile").c_str(), ios_base::out);
1282 if (!lockfile) {
1283 logStream << APPNAME << ": Could not update lock file: " << cfg->getOption("lockfile").c_str() << std::endl;
1284 exit(ERR_EXIT);
1285 }
1286 lockfile << getpid() << std::endl;
1287 lockfile.close();
1288 }
1289