app.cpp 32 KB

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