app.cpp 20 KB

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