app.cpp 31 KB

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