app.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  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. string sessStart = cfg.getOption("sessionstart_cmd");
  269. if (sessStart != "") {
  270. replaceVariables(sessStart, USER_VAR, pw->pw_name);
  271. system(sessStart.c_str());
  272. }
  273. Su.Login(loginCommand.c_str());
  274. exit(OK_EXIT);
  275. }
  276. #ifndef XNEST_DEBUG
  277. CloseLog();
  278. #endif
  279. // Wait until user is logging out (login process terminates)
  280. pid_t wpid = -1;
  281. int status;
  282. while (wpid != pid) {
  283. wpid = wait(&status);
  284. }
  285. if (WIFEXITED(status) && WEXITSTATUS(status)) {
  286. LoginPanel->Message("Failed to execute login command");
  287. } else {
  288. string sessStop = cfg.getOption("sessionstop_cmd");
  289. if (sessStop != "") {
  290. replaceVariables(sessStop, USER_VAR, pw->pw_name);
  291. system(sessStop.c_str());
  292. }
  293. }
  294. // Close all clients
  295. KillAllClients(False);
  296. KillAllClients(True);
  297. // Send HUP signal to clientgroup
  298. killpg(pid, SIGHUP);
  299. // Send TERM signal to clientgroup, if error send KILL
  300. if(killpg(pid, SIGTERM))
  301. killpg(pid, SIGKILL);
  302. HideCursor();
  303. #ifndef XNEST_DEBUG
  304. // Re-activate log file
  305. OpenLog();
  306. #endif
  307. }
  308. void App::Reboot() {
  309. // Stop alarm clock
  310. alarm(0);
  311. // Write message
  312. LoginPanel->Message((char*)cfg.getOption("reboot_msg").c_str());
  313. sleep(3);
  314. // Stop server and reboot
  315. StopServer();
  316. RemoveLock();
  317. system(cfg.getOption("reboot_cmd").c_str());
  318. exit(OK_EXIT);
  319. }
  320. void App::Halt() {
  321. // Stop alarm clock
  322. alarm(0);
  323. // Write message
  324. LoginPanel->Message((char*)cfg.getOption("shutdown_msg").c_str());
  325. sleep(3);
  326. // Stop server and halt
  327. StopServer();
  328. RemoveLock();
  329. system(cfg.getOption("halt_cmd").c_str());
  330. exit(OK_EXIT);
  331. }
  332. void App::Suspend() {
  333. sleep(1);
  334. system(cfg.getOption("suspend_cmd").c_str());
  335. }
  336. void App::Console() {
  337. int posx = 40;
  338. int posy = 40;
  339. int fontx = 9;
  340. int fonty = 15;
  341. int width = (XWidthOfScreen(ScreenOfDisplay(Dpy, Scr)) - (posx * 2)) / fontx;
  342. int height = (XHeightOfScreen(ScreenOfDisplay(Dpy, Scr)) - (posy * 2)) / fonty;
  343. // Execute console
  344. const char* cmd = cfg.getOption("console_cmd").c_str();
  345. char *tmp = new char[strlen(cmd) + 60];
  346. sprintf(tmp, cmd, width, height, posx, posy, fontx, fonty);
  347. system(tmp);
  348. delete [] tmp;
  349. }
  350. void App::Exit() {
  351. if (testing) {
  352. char* testmsg = "This is a test message :-)";
  353. LoginPanel->Message(testmsg);
  354. sleep(3);
  355. } else {
  356. delete LoginPanel;
  357. StopServer();
  358. RemoveLock();
  359. }
  360. exit(OK_EXIT);
  361. }
  362. int CatchErrors(Display *dpy, XErrorEvent *ev) {
  363. return 0;
  364. }
  365. void App::KillAllClients(Bool top) {
  366. Window dummywindow;
  367. Window *children;
  368. unsigned int nchildren;
  369. unsigned int i;
  370. XWindowAttributes attr;
  371. XSync(Dpy, 0);
  372. XSetErrorHandler(CatchErrors);
  373. nchildren = 0;
  374. XQueryTree(Dpy, Root, &dummywindow, &dummywindow, &children, &nchildren);
  375. if(!top) {
  376. for(i=0; i<nchildren; i++) {
  377. if(XGetWindowAttributes(Dpy, children[i], &attr) && (attr.map_state == IsViewable))
  378. children[i] = XmuClientWindow(Dpy, children[i]);
  379. else
  380. children[i] = 0;
  381. }
  382. }
  383. for(i=0; i<nchildren; i++) {
  384. if(children[i])
  385. XKillClient(Dpy, children[i]);
  386. }
  387. XFree((char *)children);
  388. XSync(Dpy, 0);
  389. XSetErrorHandler(NULL);
  390. }
  391. int App::ServerTimeout(int timeout, char* text) {
  392. int i = 0;
  393. int pidfound = -1;
  394. static char *lasttext;
  395. for(;;) {
  396. pidfound = waitpid(ServerPID, NULL, WNOHANG);
  397. if(pidfound == ServerPID)
  398. break;
  399. if(timeout) {
  400. if(i == 0 && text != lasttext)
  401. cerr << endl << APPNAME << ": waiting for " << text;
  402. else
  403. cerr << ".";
  404. }
  405. if(timeout)
  406. sleep(1);
  407. if(++i > timeout)
  408. break;
  409. }
  410. if(i > 0)
  411. cerr << endl;
  412. lasttext = text;
  413. return (ServerPID != pidfound);
  414. }
  415. int App::WaitForServer() {
  416. int ncycles = 120;
  417. int cycles;
  418. for(cycles = 0; cycles < ncycles; cycles++) {
  419. if((Dpy = XOpenDisplay(DisplayName))) {
  420. return 1;
  421. } else {
  422. if(!ServerTimeout(1, "X server to begin accepting connections"))
  423. break;
  424. }
  425. }
  426. cerr << "Giving up." << endl;
  427. return 0;
  428. }
  429. int App::StartServer() {
  430. ServerPID = vfork();
  431. static const int MAX_XSERVER_ARGS = 256;
  432. static char* server[MAX_XSERVER_ARGS+2] = { NULL };
  433. server[0] = (char *)cfg.getOption("default_xserver").c_str();
  434. string argOption = cfg.getOption("xserver_arguments");
  435. char* args = new char[argOption.length()+2]; // NULL plus vt
  436. strcpy(args, argOption.c_str());
  437. int argc = 1;
  438. int pos = 0;
  439. bool hasVtSet = false;
  440. while (args[pos] != '\0') {
  441. if (args[pos] == ' ' || args[pos] == '\t') {
  442. *(args+pos) = '\0';
  443. server[argc++] = args+pos+1;
  444. } else if (pos == 0) {
  445. server[argc++] = args+pos;
  446. }
  447. if (server[argc-1][0] == 'v' && server[argc-1][1] == 't') {
  448. bool ok = false;
  449. Cfg::string2int(server[argc-1]+2, &ok);
  450. if (ok) {
  451. hasVtSet = true;
  452. }
  453. }
  454. ++pos;
  455. if (argc+1 >= MAX_XSERVER_ARGS) {
  456. // ignore _all_ arguments to make sure the server starts at
  457. // all
  458. argc = 1;
  459. break;
  460. }
  461. }
  462. if (!hasVtSet && daemonmode) {
  463. server[argc++] = "vt07";
  464. }
  465. server[argc] = NULL;
  466. switch(ServerPID) {
  467. case 0:
  468. signal(SIGTTIN, SIG_IGN);
  469. signal(SIGTTOU, SIG_IGN);
  470. signal(SIGUSR1, SIG_IGN);
  471. setpgid(0,getpid());
  472. execvp(server[0], server);
  473. cerr << APPNAME << ": X server could not be started" << endl;
  474. exit(ERR_EXIT);
  475. break;
  476. case -1:
  477. break;
  478. default:
  479. errno = 0;
  480. if(!ServerTimeout(0, "")) {
  481. ServerPID = -1;
  482. break;
  483. }
  484. alarm(15);
  485. pause();
  486. alarm(0);
  487. // Wait for server to start up
  488. if(WaitForServer() == 0) {
  489. cerr << APPNAME << ": unable to connect to X server" << endl;
  490. StopServer();
  491. ServerPID = -1;
  492. exit(ERR_EXIT);
  493. }
  494. break;
  495. }
  496. delete args;
  497. return ServerPID;
  498. }
  499. jmp_buf CloseEnv;
  500. int IgnoreXIO(Display *d) {
  501. cerr << APPNAME << ": connection to X server lost." << endl;
  502. longjmp(CloseEnv, 1);
  503. }
  504. void App::StopServer() {
  505. // Stop alars clock and ignore signals
  506. alarm(0);
  507. signal(SIGQUIT, SIG_IGN);
  508. signal(SIGINT, SIG_IGN);
  509. signal(SIGHUP, SIG_IGN);
  510. signal(SIGPIPE, SIG_IGN);
  511. signal(SIGTERM, SIG_DFL);
  512. signal(SIGKILL, SIG_DFL);
  513. signal(SIGALRM, SIG_DFL);
  514. // Catch X error
  515. XSetIOErrorHandler(IgnoreXIO);
  516. if(!setjmp(CloseEnv))
  517. XCloseDisplay(Dpy);
  518. // Send HUP to process group
  519. errno = 0;
  520. if((killpg(getpid(), SIGHUP) != 0) && (errno != ESRCH))
  521. cerr << APPNAME << ": can't send HUP to process group " << getpid() << endl;
  522. // Send TERM to server
  523. if(ServerPID < 0)
  524. return;
  525. errno = 0;
  526. if(killpg(ServerPID, SIGTERM) < 0) {
  527. if(errno == EPERM) {
  528. cerr << APPNAME << ": can't kill X server" << endl;
  529. exit(ERR_EXIT);
  530. }
  531. if(errno == ESRCH)
  532. return;
  533. }
  534. // Wait for server to shut down
  535. if(!ServerTimeout(10, "X server to shut down")) {
  536. cerr << endl;
  537. return;
  538. }
  539. cerr << endl << APPNAME << ": X server slow to shut down, sending KILL signal." << endl;
  540. // Send KILL to server
  541. errno = 0;
  542. if(killpg(ServerPID, SIGKILL) < 0) {
  543. if(errno == ESRCH)
  544. return;
  545. }
  546. // Wait for server to die
  547. if(ServerTimeout(3, "server to die")) {
  548. cerr << endl << APPNAME << ": can't kill server" << endl;
  549. exit(ERR_EXIT);
  550. }
  551. cerr << endl;
  552. }
  553. void App::blankScreen()
  554. {
  555. GC gc = XCreateGC(Dpy, Root, 0, 0);
  556. XSetForeground(Dpy, gc, BlackPixel(Dpy, Scr));
  557. XFillRectangle(Dpy, Root, gc, 0, 0,
  558. XWidthOfScreen(ScreenOfDisplay(Dpy, Scr)),
  559. XHeightOfScreen(ScreenOfDisplay(Dpy, Scr)));
  560. XFlush(Dpy);
  561. XFreeGC(Dpy, gc);
  562. }
  563. void App::setBackground(const string& themedir) {
  564. string filename;
  565. filename = themedir + "/background.png";
  566. Image *image = new Image;
  567. bool loaded = image->Read(filename.c_str());
  568. if (!loaded){ // try jpeg if png failed
  569. filename = "";
  570. filename = themedir + "/background.jpg";
  571. loaded = image->Read(filename.c_str());
  572. }
  573. if (loaded) {
  574. string bgstyle = cfg.getOption("background_style");
  575. if (bgstyle == "stretch") {
  576. image->Resize(XWidthOfScreen(ScreenOfDisplay(Dpy, Scr)), XHeightOfScreen(ScreenOfDisplay(Dpy, Scr)));
  577. } else if (bgstyle == "tile") {
  578. image->Tile(XWidthOfScreen(ScreenOfDisplay(Dpy, Scr)), XHeightOfScreen(ScreenOfDisplay(Dpy, Scr)));
  579. } else if (bgstyle == "center") {
  580. string hexvalue = cfg.getOption("background_color");
  581. hexvalue = hexvalue.substr(1,6);
  582. image->Center(XWidthOfScreen(ScreenOfDisplay(Dpy, Scr)), XHeightOfScreen(ScreenOfDisplay(Dpy, Scr)),
  583. hexvalue.c_str());
  584. } else { // plain color or error
  585. string hexvalue = cfg.getOption("background_color");
  586. hexvalue = hexvalue.substr(1,6);
  587. image->Center(XWidthOfScreen(ScreenOfDisplay(Dpy, Scr)), XHeightOfScreen(ScreenOfDisplay(Dpy, Scr)),
  588. hexvalue.c_str());
  589. }
  590. Pixmap p = image->createPixmap(Dpy, Scr, Root);
  591. XSetWindowBackgroundPixmap(Dpy, Root, p);
  592. }
  593. XClearWindow(Dpy, Root);
  594. XFlush(Dpy);
  595. }
  596. // Lock or die!
  597. void App::GetLock() {
  598. int fd;
  599. fd=open(cfg.getOption("lockfile").c_str(),O_WRONLY | O_CREAT | O_EXCL);
  600. if (fd<0 && errno==EEXIST) {
  601. cerr << APPNAME << ": It appears there is another instance of the program already running" <<endl
  602. << "If not, try to remove the lockfile: " << cfg.getOption("lockfile") <<endl;
  603. exit(ERR_EXIT);
  604. } else if (fd < 0) {
  605. cerr << APPNAME << ": Could not accesss lock file: " << cfg.getOption("lockfile") << endl;
  606. exit(ERR_EXIT);
  607. }
  608. }
  609. // Remove lockfile and close logs
  610. void App::RemoveLock() {
  611. remove(cfg.getOption("lockfile").c_str());
  612. }
  613. // Redirect stdout and stderr to log file
  614. void App::OpenLog() {
  615. FILE *log = fopen (cfg.getOption("logfile").c_str(),"a");
  616. if (!log) {
  617. cerr << APPNAME << ": Could not accesss log file: " << cfg.getOption("logfile") << endl;
  618. RemoveLock();
  619. exit(ERR_EXIT);
  620. }
  621. fclose(log);
  622. freopen (cfg.getOption("logfile").c_str(),"a",stdout);
  623. setvbuf(stdout, NULL, _IOLBF, BUFSIZ);
  624. freopen (cfg.getOption("logfile").c_str(),"a",stderr);
  625. setvbuf(stderr, NULL, _IONBF, BUFSIZ);
  626. }
  627. // Relases stdout/err
  628. void App::CloseLog(){
  629. fclose(stderr);
  630. fclose(stdout);
  631. }
  632. string App::findValidRandomTheme(const string& set)
  633. {
  634. // extract random theme from theme set; return empty string on error
  635. string name = set;
  636. struct stat buf;
  637. if (name[name.length()-1] == ',') {
  638. name = name.substr(0, name.length() - 1);
  639. }
  640. srandom(getpid()+time(NULL));
  641. vector<string> themes;
  642. string themefile;
  643. Cfg::split(themes, name, ',');
  644. do {
  645. int sel = random() % themes.size();
  646. name = Cfg::Trim(themes[sel]);
  647. themefile = string(THEMESDIR) +"/" + name + THEMESFILE;
  648. if (stat(themefile.c_str(), &buf) != 0) {
  649. themes.erase(find(themes.begin(), themes.end(), name));
  650. cerr << APPNAME << ": Invalid theme in config: "
  651. << name << endl;
  652. name = "";
  653. }
  654. } while (name == "" && themes.size());
  655. return name;
  656. }
  657. void App::replaceVariables(string& input,
  658. const string& var,
  659. const string& value)
  660. {
  661. string::size_type pos = 0;
  662. int len = var.size();
  663. while ((pos = input.find(var, pos)) != string::npos) {
  664. input = input.substr(0, pos) + value + input.substr(pos+len);
  665. }
  666. }