app.cpp 31 KB

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