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