app.cpp 32 KB

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