app.cpp 28 KB

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