app.cpp 21 KB

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