app.cpp 28 KB

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