app.cpp 21 KB

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