app.cpp 32 KB

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