app.cpp 23 KB

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