app.cpp 31 KB

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