app.cpp 31 KB

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