app.cpp 33 KB

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