app.cpp 31 KB

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