app.cpp 32 KB

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