app.cpp 28 KB

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