app.cpp 28 KB

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