app.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  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 <sstream>
  17. #include <vector>
  18. #include <algorithm>
  19. #include "app.h"
  20. #include "numlock.h"
  21. #include "image.h"
  22. extern App* LoginApp;
  23. void CatchSignal(int sig) {
  24. cerr << APPNAME << ": unexpected signal " << sig << endl;
  25. LoginApp->StopServer();
  26. LoginApp->RemoveLock();
  27. exit(ERR_EXIT);
  28. }
  29. void AlarmSignal(int sig) {
  30. int pid = LoginApp->GetServerPID();
  31. if(waitpid(pid, NULL, WNOHANG) == pid) {
  32. LoginApp->StopServer();
  33. LoginApp->RemoveLock();
  34. exit(OK_EXIT);
  35. }
  36. signal(sig, AlarmSignal);
  37. alarm(2);
  38. }
  39. void User1Signal(int sig) {
  40. signal(sig, User1Signal);
  41. }
  42. App::App(int argc, char** argv) {
  43. int tmp;
  44. ServerPID = -1;
  45. testing = false;
  46. // Parse command line
  47. while((tmp = getopt(argc, argv, "vhp:d?")) != EOF) {
  48. switch (tmp) {
  49. case 'p': // Test theme
  50. testtheme = optarg;
  51. testing = true;
  52. if (testtheme == NULL) {
  53. cerr << "The -p option requires an argument" << endl;
  54. exit(ERR_EXIT);
  55. }
  56. break;
  57. case 'd': // Daemon mode
  58. daemonmode = true;
  59. break;
  60. case 'v': // Version
  61. std::cout << APPNAME << " version " << VERSION << endl;
  62. exit(OK_EXIT);
  63. break;
  64. case '?': // Illegal
  65. cerr << endl;
  66. case 'h': // Help
  67. cerr << "usage: " << APPNAME << " [option ...]" << endl
  68. << "options:" << endl
  69. << " -d: daemon mode" << endl
  70. << " -v: show version" << endl
  71. << " -p /path/to/theme/dir: preview theme" << endl;
  72. exit(OK_EXIT);
  73. break;
  74. }
  75. }
  76. if (getuid() != 0 && !testing) {
  77. cerr << APPNAME << ": only root can run this program" << endl;
  78. exit(ERR_EXIT);
  79. }
  80. }
  81. void App::Run() {
  82. DisplayName = DISPLAY;
  83. #ifdef XNEST_DEBUG
  84. char* p = getenv("DISPLAY");
  85. if (p && p[0]) {
  86. DisplayName = p;
  87. cout << "Using display name " << DisplayName << endl;
  88. }
  89. #endif
  90. // Read configuration and theme
  91. cfg.readConf(CFGFILE);
  92. string themebase = "";
  93. string themefile = "";
  94. string themedir = "";
  95. themeName = "";
  96. if (testing) {
  97. themeName = testtheme;
  98. } else {
  99. themebase = string(THEMESDIR) + "/";
  100. themeName = cfg.getOption("current_theme");
  101. string::size_type pos;
  102. if ((pos = themeName.find(",")) != string::npos) {
  103. // input is a set
  104. themeName = findValidRandomTheme(themeName);
  105. if (themeName == "") {
  106. themeName = "default";
  107. }
  108. }
  109. }
  110. bool loaded = false;
  111. while (!loaded) {
  112. themedir = themebase + themeName;
  113. themefile = themedir + THEMESFILE;
  114. if (!cfg.readConf(themefile)) {
  115. if (themeName == "default") {
  116. cerr << APPNAME << ": Failed to open default theme file "
  117. << themefile << endl;
  118. exit(ERR_EXIT);
  119. } else {
  120. cerr << APPNAME << ": Invalid theme in config: "
  121. << themeName << endl;
  122. themeName = "default";
  123. }
  124. } else {
  125. loaded = true;
  126. }
  127. }
  128. if (!testing) {
  129. // Create lock file
  130. LoginApp->GetLock();
  131. // Start x-server
  132. setenv("DISPLAY", DisplayName, 1);
  133. signal(SIGQUIT, CatchSignal);
  134. signal(SIGTERM, CatchSignal);
  135. signal(SIGKILL, CatchSignal);
  136. signal(SIGINT, CatchSignal);
  137. signal(SIGHUP, CatchSignal);
  138. signal(SIGPIPE, CatchSignal);
  139. signal(SIGUSR1, User1Signal);
  140. signal(SIGALRM, AlarmSignal);
  141. #ifndef XNEST_DEBUG
  142. OpenLog();
  143. if (cfg.getOption("daemon") == "yes") {
  144. daemonmode = true;
  145. }
  146. // Daemonize
  147. if (daemonmode) {
  148. if (daemon(0, 1) == -1) {
  149. cerr << APPNAME << ": " << strerror(errno) << endl;
  150. exit(ERR_EXIT);
  151. }
  152. }
  153. StartServer();
  154. alarm(2);
  155. #endif
  156. }
  157. // Open display
  158. if((Dpy = XOpenDisplay(DisplayName)) == 0) {
  159. cerr << APPNAME << ": could not open display '"
  160. << DisplayName << "'" << endl;
  161. if (!testing) StopServer();
  162. exit(ERR_EXIT);
  163. }
  164. // Get screen and root window
  165. Scr = DefaultScreen(Dpy);
  166. Root = RootWindow(Dpy, Scr);
  167. // for tests we use a standard window
  168. if (testing) {
  169. Window RealRoot = RootWindow(Dpy, Scr);
  170. Root = XCreateSimpleWindow(Dpy, RealRoot, 0, 0, 640, 480, 0, 0, 0);
  171. XMapWindow(Dpy, Root);
  172. XFlush(Dpy);
  173. } else {
  174. blankScreen();
  175. }
  176. HideCursor();
  177. // Create panel
  178. LoginPanel = new Panel(Dpy, Scr, Root, &cfg, themedir);
  179. // Start looping
  180. XEvent event;
  181. int panelclosed = 1;
  182. int Action;
  183. bool firstloop = true; // 1st time panel is shown (for automatic username)
  184. while(1) {
  185. if(panelclosed) {
  186. // Init root
  187. setBackground(themedir);
  188. // Close all clients
  189. if (!testing) {
  190. KillAllClients(False);
  191. KillAllClients(True);
  192. }
  193. // Show panel
  194. LoginPanel->OpenPanel();
  195. }
  196. Action = WAIT;
  197. LoginPanel->GetInput()->Reset();
  198. if (firstloop && cfg.getOption("default_user") != "") {
  199. LoginPanel->GetInput()->SetName(cfg.getOption("default_user") );
  200. firstloop = false;
  201. }
  202. while(Action == WAIT) {
  203. XNextEvent(Dpy, &event);
  204. Action = LoginPanel->EventHandler(&event);
  205. }
  206. if(Action == FAIL) {
  207. panelclosed = 0;
  208. LoginPanel->ClearPanel();
  209. XBell(Dpy, 100);
  210. } else {
  211. // for themes test we just quit
  212. if (testing) {
  213. Action = EXIT;
  214. }
  215. panelclosed = 1;
  216. LoginPanel->ClosePanel();
  217. switch(Action) {
  218. case LOGIN:
  219. Login();
  220. break;
  221. case CONSOLE:
  222. Console();
  223. break;
  224. case REBOOT:
  225. Reboot();
  226. break;
  227. case HALT:
  228. Halt();
  229. break;
  230. case SUSPEND:
  231. Suspend();
  232. break;
  233. case EXIT:
  234. Exit();
  235. break;
  236. }
  237. }
  238. }
  239. }
  240. int App::GetServerPID() {
  241. return ServerPID;
  242. }
  243. // Hide the cursor
  244. void App::HideCursor() {
  245. XColor black;
  246. char cursordata[1];
  247. Pixmap cursorpixmap;
  248. Cursor cursor;
  249. cursordata[0]=0;
  250. cursorpixmap=XCreateBitmapFromData(Dpy,Root,cursordata,1,1);
  251. black.red=0;
  252. black.green=0;
  253. black.blue=0;
  254. cursor=XCreatePixmapCursor(Dpy,cursorpixmap,cursorpixmap,&black,&black,0,0);
  255. XDefineCursor(Dpy,Root,cursor);
  256. }
  257. void App::Login() {
  258. struct passwd *pw;
  259. pid_t pid;
  260. pw = LoginPanel->GetInput()->GetPasswdStruct();
  261. if(pw == 0)
  262. return;
  263. // Create new process
  264. pid = fork();
  265. if(pid == 0) {
  266. // Login process starts here
  267. SwitchUser Su(pw, &cfg, DisplayName);
  268. string session = LoginPanel->getSession();
  269. string loginCommand = cfg.getOption("login_cmd");
  270. replaceVariables(loginCommand, SESSION_VAR, session);
  271. replaceVariables(loginCommand, THEME_VAR, themeName);
  272. string sessStart = cfg.getOption("sessionstart_cmd");
  273. if (sessStart != "") {
  274. replaceVariables(sessStart, USER_VAR, pw->pw_name);
  275. system(sessStart.c_str());
  276. }
  277. Su.Login(loginCommand.c_str());
  278. exit(OK_EXIT);
  279. }
  280. #ifndef XNEST_DEBUG
  281. CloseLog();
  282. #endif
  283. // Wait until user is logging out (login process terminates)
  284. pid_t wpid = -1;
  285. int status;
  286. while (wpid != pid) {
  287. wpid = wait(&status);
  288. }
  289. if (WIFEXITED(status) && WEXITSTATUS(status)) {
  290. LoginPanel->Message("Failed to execute login command");
  291. } else {
  292. string sessStop = cfg.getOption("sessionstop_cmd");
  293. if (sessStop != "") {
  294. replaceVariables(sessStop, USER_VAR, pw->pw_name);
  295. system(sessStop.c_str());
  296. }
  297. }
  298. // Close all clients
  299. KillAllClients(False);
  300. KillAllClients(True);
  301. // Send HUP signal to clientgroup
  302. killpg(pid, SIGHUP);
  303. // Send TERM signal to clientgroup, if error send KILL
  304. if(killpg(pid, SIGTERM))
  305. killpg(pid, SIGKILL);
  306. HideCursor();
  307. #ifndef XNEST_DEBUG
  308. // Re-activate log file
  309. OpenLog();
  310. #endif
  311. }
  312. void App::Reboot() {
  313. // Stop alarm clock
  314. alarm(0);
  315. // Write message
  316. LoginPanel->Message((char*)cfg.getOption("reboot_msg").c_str());
  317. sleep(3);
  318. // Stop server and reboot
  319. StopServer();
  320. RemoveLock();
  321. system(cfg.getOption("reboot_cmd").c_str());
  322. exit(OK_EXIT);
  323. }
  324. void App::Halt() {
  325. // Stop alarm clock
  326. alarm(0);
  327. // Write message
  328. LoginPanel->Message((char*)cfg.getOption("shutdown_msg").c_str());
  329. sleep(3);
  330. // Stop server and halt
  331. StopServer();
  332. RemoveLock();
  333. system(cfg.getOption("halt_cmd").c_str());
  334. exit(OK_EXIT);
  335. }
  336. void App::Suspend() {
  337. sleep(1);
  338. system(cfg.getOption("suspend_cmd").c_str());
  339. }
  340. void App::Console() {
  341. int posx = 40;
  342. int posy = 40;
  343. int fontx = 9;
  344. int fonty = 15;
  345. int width = (XWidthOfScreen(ScreenOfDisplay(Dpy, Scr)) - (posx * 2)) / fontx;
  346. int height = (XHeightOfScreen(ScreenOfDisplay(Dpy, Scr)) - (posy * 2)) / fonty;
  347. // Execute console
  348. const char* cmd = cfg.getOption("console_cmd").c_str();
  349. char *tmp = new char[strlen(cmd) + 60];
  350. sprintf(tmp, cmd, width, height, posx, posy, fontx, fonty);
  351. system(tmp);
  352. delete [] tmp;
  353. }
  354. void App::Exit() {
  355. if (testing) {
  356. char* testmsg = "This is a test message :-)";
  357. LoginPanel->Message(testmsg);
  358. sleep(3);
  359. } else {
  360. delete LoginPanel;
  361. StopServer();
  362. RemoveLock();
  363. }
  364. exit(OK_EXIT);
  365. }
  366. int CatchErrors(Display *dpy, XErrorEvent *ev) {
  367. return 0;
  368. }
  369. void App::KillAllClients(Bool top) {
  370. Window dummywindow;
  371. Window *children;
  372. unsigned int nchildren;
  373. unsigned int i;
  374. XWindowAttributes attr;
  375. XSync(Dpy, 0);
  376. XSetErrorHandler(CatchErrors);
  377. nchildren = 0;
  378. XQueryTree(Dpy, Root, &dummywindow, &dummywindow, &children, &nchildren);
  379. if(!top) {
  380. for(i=0; i<nchildren; i++) {
  381. if(XGetWindowAttributes(Dpy, children[i], &attr) && (attr.map_state == IsViewable))
  382. children[i] = XmuClientWindow(Dpy, children[i]);
  383. else
  384. children[i] = 0;
  385. }
  386. }
  387. for(i=0; i<nchildren; i++) {
  388. if(children[i])
  389. XKillClient(Dpy, children[i]);
  390. }
  391. XFree((char *)children);
  392. XSync(Dpy, 0);
  393. XSetErrorHandler(NULL);
  394. }
  395. int App::ServerTimeout(int timeout, char* text) {
  396. int i = 0;
  397. int pidfound = -1;
  398. static char *lasttext;
  399. for(;;) {
  400. pidfound = waitpid(ServerPID, NULL, WNOHANG);
  401. if(pidfound == ServerPID)
  402. break;
  403. if(timeout) {
  404. if(i == 0 && text != lasttext)
  405. cerr << endl << APPNAME << ": waiting for " << text;
  406. else
  407. cerr << ".";
  408. }
  409. if(timeout)
  410. sleep(1);
  411. if(++i > timeout)
  412. break;
  413. }
  414. if(i > 0)
  415. cerr << endl;
  416. lasttext = text;
  417. return (ServerPID != pidfound);
  418. }
  419. int App::WaitForServer() {
  420. int ncycles = 120;
  421. int cycles;
  422. for(cycles = 0; cycles < ncycles; cycles++) {
  423. if((Dpy = XOpenDisplay(DisplayName))) {
  424. return 1;
  425. } else {
  426. if(!ServerTimeout(1, "X server to begin accepting connections"))
  427. break;
  428. }
  429. }
  430. cerr << "Giving up." << endl;
  431. return 0;
  432. }
  433. int App::StartServer() {
  434. ServerPID = vfork();
  435. static const int MAX_XSERVER_ARGS = 256;
  436. static char* server[MAX_XSERVER_ARGS+2] = { NULL };
  437. server[0] = (char *)cfg.getOption("default_xserver").c_str();
  438. string argOption = cfg.getOption("xserver_arguments");
  439. char* args = new char[argOption.length()+2]; // NULL plus vt
  440. strcpy(args, argOption.c_str());
  441. int argc = 1;
  442. int pos = 0;
  443. bool hasVtSet = false;
  444. while (args[pos] != '\0') {
  445. if (args[pos] == ' ' || args[pos] == '\t') {
  446. *(args+pos) = '\0';
  447. server[argc++] = args+pos+1;
  448. } else if (pos == 0) {
  449. server[argc++] = args+pos;
  450. }
  451. if (server[argc-1][0] == 'v' && server[argc-1][1] == 't') {
  452. bool ok = false;
  453. Cfg::string2int(server[argc-1]+2, &ok);
  454. if (ok) {
  455. hasVtSet = true;
  456. }
  457. }
  458. ++pos;
  459. if (argc+1 >= MAX_XSERVER_ARGS) {
  460. // ignore _all_ arguments to make sure the server starts at
  461. // all
  462. argc = 1;
  463. break;
  464. }
  465. }
  466. if (!hasVtSet && daemonmode) {
  467. server[argc++] = "vt07";
  468. }
  469. server[argc] = NULL;
  470. switch(ServerPID) {
  471. case 0:
  472. signal(SIGTTIN, SIG_IGN);
  473. signal(SIGTTOU, SIG_IGN);
  474. signal(SIGUSR1, SIG_IGN);
  475. setpgid(0,getpid());
  476. execvp(server[0], server);
  477. cerr << APPNAME << ": X server could not be started" << endl;
  478. exit(ERR_EXIT);
  479. break;
  480. case -1:
  481. break;
  482. default:
  483. errno = 0;
  484. if(!ServerTimeout(0, "")) {
  485. ServerPID = -1;
  486. break;
  487. }
  488. alarm(15);
  489. pause();
  490. alarm(0);
  491. // Wait for server to start up
  492. if(WaitForServer() == 0) {
  493. cerr << APPNAME << ": unable to connect to X server" << endl;
  494. StopServer();
  495. ServerPID = -1;
  496. exit(ERR_EXIT);
  497. }
  498. break;
  499. }
  500. string numlock = cfg.getOption("numlock");
  501. if (numlock == "on") {
  502. NumLock::setOn();
  503. } else if (numlock == "off") {
  504. NumLock::setOff();
  505. }
  506. delete args;
  507. return ServerPID;
  508. }
  509. jmp_buf CloseEnv;
  510. int IgnoreXIO(Display *d) {
  511. cerr << APPNAME << ": connection to X server lost." << endl;
  512. longjmp(CloseEnv, 1);
  513. }
  514. void App::StopServer() {
  515. // Stop alars clock and ignore signals
  516. alarm(0);
  517. signal(SIGQUIT, SIG_IGN);
  518. signal(SIGINT, SIG_IGN);
  519. signal(SIGHUP, SIG_IGN);
  520. signal(SIGPIPE, SIG_IGN);
  521. signal(SIGTERM, SIG_DFL);
  522. signal(SIGKILL, SIG_DFL);
  523. signal(SIGALRM, SIG_DFL);
  524. // Catch X error
  525. XSetIOErrorHandler(IgnoreXIO);
  526. if(!setjmp(CloseEnv))
  527. XCloseDisplay(Dpy);
  528. // Send HUP to process group
  529. errno = 0;
  530. if((killpg(getpid(), SIGHUP) != 0) && (errno != ESRCH))
  531. cerr << APPNAME << ": can't send HUP to process group " << getpid() << endl;
  532. // Send TERM to server
  533. if(ServerPID < 0)
  534. return;
  535. errno = 0;
  536. if(killpg(ServerPID, SIGTERM) < 0) {
  537. if(errno == EPERM) {
  538. cerr << APPNAME << ": can't kill X server" << endl;
  539. exit(ERR_EXIT);
  540. }
  541. if(errno == ESRCH)
  542. return;
  543. }
  544. // Wait for server to shut down
  545. if(!ServerTimeout(10, "X server to shut down")) {
  546. cerr << endl;
  547. return;
  548. }
  549. cerr << endl << APPNAME << ": X server slow to shut down, sending KILL signal." << endl;
  550. // Send KILL to server
  551. errno = 0;
  552. if(killpg(ServerPID, SIGKILL) < 0) {
  553. if(errno == ESRCH)
  554. return;
  555. }
  556. // Wait for server to die
  557. if(ServerTimeout(3, "server to die")) {
  558. cerr << endl << APPNAME << ": can't kill server" << endl;
  559. exit(ERR_EXIT);
  560. }
  561. cerr << endl;
  562. }
  563. void App::blankScreen()
  564. {
  565. GC gc = XCreateGC(Dpy, Root, 0, 0);
  566. XSetForeground(Dpy, gc, BlackPixel(Dpy, Scr));
  567. XFillRectangle(Dpy, Root, gc, 0, 0,
  568. XWidthOfScreen(ScreenOfDisplay(Dpy, Scr)),
  569. XHeightOfScreen(ScreenOfDisplay(Dpy, Scr)));
  570. XFlush(Dpy);
  571. XFreeGC(Dpy, gc);
  572. }
  573. void App::setBackground(const string& themedir) {
  574. string filename;
  575. filename = themedir + "/background.png";
  576. Image *image = new Image;
  577. bool loaded = image->Read(filename.c_str());
  578. if (!loaded){ // try jpeg if png failed
  579. filename = "";
  580. filename = themedir + "/background.jpg";
  581. loaded = image->Read(filename.c_str());
  582. }
  583. if (loaded) {
  584. string bgstyle = cfg.getOption("background_style");
  585. if (bgstyle == "stretch") {
  586. image->Resize(XWidthOfScreen(ScreenOfDisplay(Dpy, Scr)), XHeightOfScreen(ScreenOfDisplay(Dpy, Scr)));
  587. } else if (bgstyle == "tile") {
  588. image->Tile(XWidthOfScreen(ScreenOfDisplay(Dpy, Scr)), XHeightOfScreen(ScreenOfDisplay(Dpy, Scr)));
  589. } else if (bgstyle == "center") {
  590. string hexvalue = cfg.getOption("background_color");
  591. hexvalue = hexvalue.substr(1,6);
  592. image->Center(XWidthOfScreen(ScreenOfDisplay(Dpy, Scr)), XHeightOfScreen(ScreenOfDisplay(Dpy, Scr)),
  593. hexvalue.c_str());
  594. } else { // plain color or error
  595. string hexvalue = cfg.getOption("background_color");
  596. hexvalue = hexvalue.substr(1,6);
  597. image->Center(XWidthOfScreen(ScreenOfDisplay(Dpy, Scr)), XHeightOfScreen(ScreenOfDisplay(Dpy, Scr)),
  598. hexvalue.c_str());
  599. }
  600. Pixmap p = image->createPixmap(Dpy, Scr, Root);
  601. XSetWindowBackgroundPixmap(Dpy, Root, p);
  602. }
  603. XClearWindow(Dpy, Root);
  604. XFlush(Dpy);
  605. }
  606. // Lock or die!
  607. void App::GetLock() {
  608. int fd;
  609. fd=open(cfg.getOption("lockfile").c_str(),O_WRONLY | O_CREAT | O_EXCL);
  610. if (fd<0 && errno==EEXIST) {
  611. cerr << APPNAME << ": It appears there is another instance of the program already running" <<endl
  612. << "If not, try to remove the lockfile: " << cfg.getOption("lockfile") <<endl;
  613. exit(ERR_EXIT);
  614. } else if (fd < 0) {
  615. cerr << APPNAME << ": Could not accesss lock file: " << cfg.getOption("lockfile") << endl;
  616. exit(ERR_EXIT);
  617. }
  618. }
  619. // Remove lockfile and close logs
  620. void App::RemoveLock() {
  621. remove(cfg.getOption("lockfile").c_str());
  622. }
  623. // Redirect stdout and stderr to log file
  624. void App::OpenLog() {
  625. FILE *log = fopen (cfg.getOption("logfile").c_str(),"a");
  626. if (!log) {
  627. cerr << APPNAME << ": Could not accesss log file: " << cfg.getOption("logfile") << endl;
  628. RemoveLock();
  629. exit(ERR_EXIT);
  630. }
  631. fclose(log);
  632. freopen (cfg.getOption("logfile").c_str(),"a",stdout);
  633. setvbuf(stdout, NULL, _IOLBF, BUFSIZ);
  634. freopen (cfg.getOption("logfile").c_str(),"a",stderr);
  635. setvbuf(stderr, NULL, _IONBF, BUFSIZ);
  636. }
  637. // Relases stdout/err
  638. void App::CloseLog(){
  639. fclose(stderr);
  640. fclose(stdout);
  641. }
  642. string App::findValidRandomTheme(const string& set)
  643. {
  644. // extract random theme from theme set; return empty string on error
  645. string name = set;
  646. struct stat buf;
  647. if (name[name.length()-1] == ',') {
  648. name = name.substr(0, name.length() - 1);
  649. }
  650. srandom(getpid()+time(NULL));
  651. vector<string> themes;
  652. string themefile;
  653. Cfg::split(themes, name, ',');
  654. do {
  655. int sel = random() % themes.size();
  656. name = Cfg::Trim(themes[sel]);
  657. themefile = string(THEMESDIR) +"/" + name + THEMESFILE;
  658. if (stat(themefile.c_str(), &buf) != 0) {
  659. themes.erase(find(themes.begin(), themes.end(), name));
  660. cerr << APPNAME << ": Invalid theme in config: "
  661. << name << endl;
  662. name = "";
  663. }
  664. } while (name == "" && themes.size());
  665. return name;
  666. }
  667. void App::replaceVariables(string& input,
  668. const string& var,
  669. const string& value)
  670. {
  671. string::size_type pos = 0;
  672. int len = var.size();
  673. while ((pos = input.find(var, pos)) != string::npos) {
  674. input = input.substr(0, pos) + value + input.substr(pos+len);
  675. }
  676. }