app.cpp 32 KB

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