app.cpp 19 KB

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