app.cpp 21 KB

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