app.cpp 32 KB

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