app.cpp 32 KB

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