app.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  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. StopServer();
  369. RemoveLock();
  370. }
  371. XCloseDisplay(Dpy);
  372. delete LoginPanel;
  373. delete cfg;
  374. exit(OK_EXIT);
  375. }
  376. int CatchErrors(Display *dpy, XErrorEvent *ev) {
  377. return 0;
  378. }
  379. void App::RestartServer() {
  380. StopServer();
  381. RemoveLock();
  382. Run();
  383. }
  384. void App::KillAllClients(Bool top) {
  385. Window dummywindow;
  386. Window *children;
  387. unsigned int nchildren;
  388. unsigned int i;
  389. XWindowAttributes attr;
  390. XSync(Dpy, 0);
  391. XSetErrorHandler(CatchErrors);
  392. nchildren = 0;
  393. XQueryTree(Dpy, Root, &dummywindow, &dummywindow, &children, &nchildren);
  394. if(!top) {
  395. for(i=0; i<nchildren; i++) {
  396. if(XGetWindowAttributes(Dpy, children[i], &attr) && (attr.map_state == IsViewable))
  397. children[i] = XmuClientWindow(Dpy, children[i]);
  398. else
  399. children[i] = 0;
  400. }
  401. }
  402. for(i=0; i<nchildren; i++) {
  403. if(children[i])
  404. XKillClient(Dpy, children[i]);
  405. }
  406. XFree((char *)children);
  407. XSync(Dpy, 0);
  408. XSetErrorHandler(NULL);
  409. }
  410. int App::ServerTimeout(int timeout, char* text) {
  411. int i = 0;
  412. int pidfound = -1;
  413. static char *lasttext;
  414. for(;;) {
  415. pidfound = waitpid(ServerPID, NULL, WNOHANG);
  416. if(pidfound == ServerPID)
  417. break;
  418. if(timeout) {
  419. if(i == 0 && text != lasttext)
  420. cerr << endl << APPNAME << ": waiting for " << text;
  421. else
  422. cerr << ".";
  423. }
  424. if(timeout)
  425. sleep(1);
  426. if(++i > timeout)
  427. break;
  428. }
  429. if(i > 0)
  430. cerr << endl;
  431. lasttext = text;
  432. return (ServerPID != pidfound);
  433. }
  434. int App::WaitForServer() {
  435. int ncycles = 120;
  436. int cycles;
  437. for(cycles = 0; cycles < ncycles; cycles++) {
  438. if((Dpy = XOpenDisplay(DisplayName))) {
  439. return 1;
  440. } else {
  441. if(!ServerTimeout(1, "X server to begin accepting connections"))
  442. break;
  443. }
  444. }
  445. cerr << "Giving up." << endl;
  446. return 0;
  447. }
  448. int App::StartServer() {
  449. ServerPID = vfork();
  450. static const int MAX_XSERVER_ARGS = 256;
  451. static char* server[MAX_XSERVER_ARGS+2] = { NULL };
  452. server[0] = (char *)cfg->getOption("default_xserver").c_str();
  453. string argOption = cfg->getOption("xserver_arguments");
  454. /* Add mandatory -xauth option */
  455. argOption = argOption + " -auth " + cfg->getOption("authfile");
  456. char* args = new char[argOption.length()+2]; // NULL plus vt
  457. strcpy(args, argOption.c_str());
  458. int argc = 1;
  459. int pos = 0;
  460. bool hasVtSet = false;
  461. while (args[pos] != '\0') {
  462. if (args[pos] == ' ' || args[pos] == '\t') {
  463. *(args+pos) = '\0';
  464. server[argc++] = args+pos+1;
  465. } else if (pos == 0) {
  466. server[argc++] = args+pos;
  467. }
  468. if (server[argc-1][0] == 'v' && server[argc-1][1] == 't') {
  469. bool ok = false;
  470. Cfg::string2int(server[argc-1]+2, &ok);
  471. if (ok) {
  472. hasVtSet = true;
  473. }
  474. }
  475. ++pos;
  476. if (argc+1 >= MAX_XSERVER_ARGS) {
  477. // ignore _all_ arguments to make sure the server starts at
  478. // all
  479. argc = 1;
  480. break;
  481. }
  482. }
  483. if (!hasVtSet && daemonmode) {
  484. server[argc++] = "vt07";
  485. }
  486. server[argc] = NULL;
  487. switch(ServerPID) {
  488. case 0:
  489. signal(SIGTTIN, SIG_IGN);
  490. signal(SIGTTOU, SIG_IGN);
  491. signal(SIGUSR1, SIG_IGN);
  492. setpgid(0,getpid());
  493. execvp(server[0], server);
  494. cerr << APPNAME << ": X server could not be started" << endl;
  495. exit(ERR_EXIT);
  496. break;
  497. case -1:
  498. break;
  499. default:
  500. errno = 0;
  501. if(!ServerTimeout(0, "")) {
  502. ServerPID = -1;
  503. break;
  504. }
  505. alarm(15);
  506. pause();
  507. alarm(0);
  508. // Wait for server to start up
  509. if(WaitForServer() == 0) {
  510. cerr << APPNAME << ": unable to connect to X server" << endl;
  511. StopServer();
  512. ServerPID = -1;
  513. exit(ERR_EXIT);
  514. }
  515. break;
  516. }
  517. string numlock = cfg->getOption("numlock");
  518. if (numlock == "on") {
  519. NumLock::setOn();
  520. } else if (numlock == "off") {
  521. NumLock::setOff();
  522. }
  523. delete args;
  524. return ServerPID;
  525. }
  526. jmp_buf CloseEnv;
  527. int IgnoreXIO(Display *d) {
  528. cerr << APPNAME << ": connection to X server lost." << endl;
  529. longjmp(CloseEnv, 1);
  530. }
  531. void App::StopServer() {
  532. // Stop alars clock and ignore signals
  533. alarm(0);
  534. signal(SIGQUIT, SIG_IGN);
  535. signal(SIGINT, SIG_IGN);
  536. signal(SIGHUP, SIG_IGN);
  537. signal(SIGPIPE, SIG_IGN);
  538. signal(SIGTERM, SIG_DFL);
  539. signal(SIGKILL, SIG_DFL);
  540. signal(SIGALRM, SIG_DFL);
  541. // Catch X error
  542. XSetIOErrorHandler(IgnoreXIO);
  543. if(!setjmp(CloseEnv))
  544. XCloseDisplay(Dpy);
  545. // Send HUP to process group
  546. errno = 0;
  547. if((killpg(getpid(), SIGHUP) != 0) && (errno != ESRCH))
  548. cerr << APPNAME << ": can't send HUP to process group " << getpid() << endl;
  549. // Send TERM to server
  550. if(ServerPID < 0)
  551. return;
  552. errno = 0;
  553. if(killpg(ServerPID, SIGTERM) < 0) {
  554. if(errno == EPERM) {
  555. cerr << APPNAME << ": can't kill X server" << endl;
  556. exit(ERR_EXIT);
  557. }
  558. if(errno == ESRCH)
  559. return;
  560. }
  561. // Wait for server to shut down
  562. if(!ServerTimeout(10, "X server to shut down")) {
  563. cerr << endl;
  564. return;
  565. }
  566. cerr << endl << APPNAME << ": X server slow to shut down, sending KILL signal." << endl;
  567. // Send KILL to server
  568. errno = 0;
  569. if(killpg(ServerPID, SIGKILL) < 0) {
  570. if(errno == ESRCH)
  571. return;
  572. }
  573. // Wait for server to die
  574. if(ServerTimeout(3, "server to die")) {
  575. cerr << endl << APPNAME << ": can't kill server" << endl;
  576. exit(ERR_EXIT);
  577. }
  578. cerr << endl;
  579. }
  580. void App::blankScreen()
  581. {
  582. GC gc = XCreateGC(Dpy, Root, 0, 0);
  583. XSetForeground(Dpy, gc, BlackPixel(Dpy, Scr));
  584. XFillRectangle(Dpy, Root, gc, 0, 0,
  585. XWidthOfScreen(ScreenOfDisplay(Dpy, Scr)),
  586. XHeightOfScreen(ScreenOfDisplay(Dpy, Scr)));
  587. XFlush(Dpy);
  588. XFreeGC(Dpy, gc);
  589. }
  590. void App::setBackground(const string& themedir) {
  591. string filename;
  592. filename = themedir + "/background.png";
  593. image = new Image;
  594. bool loaded = image->Read(filename.c_str());
  595. if (!loaded){ // try jpeg if png failed
  596. filename = "";
  597. filename = themedir + "/background.jpg";
  598. loaded = image->Read(filename.c_str());
  599. }
  600. if (loaded) {
  601. string bgstyle = cfg->getOption("background_style");
  602. if (bgstyle == "stretch") {
  603. image->Resize(XWidthOfScreen(ScreenOfDisplay(Dpy, Scr)), XHeightOfScreen(ScreenOfDisplay(Dpy, Scr)));
  604. } else if (bgstyle == "tile") {
  605. image->Tile(XWidthOfScreen(ScreenOfDisplay(Dpy, Scr)), XHeightOfScreen(ScreenOfDisplay(Dpy, Scr)));
  606. } else if (bgstyle == "center") {
  607. string hexvalue = cfg->getOption("background_color");
  608. hexvalue = hexvalue.substr(1,6);
  609. image->Center(XWidthOfScreen(ScreenOfDisplay(Dpy, Scr)), XHeightOfScreen(ScreenOfDisplay(Dpy, Scr)),
  610. hexvalue.c_str());
  611. } else { // plain color or error
  612. string hexvalue = cfg->getOption("background_color");
  613. hexvalue = hexvalue.substr(1,6);
  614. image->Center(XWidthOfScreen(ScreenOfDisplay(Dpy, Scr)), XHeightOfScreen(ScreenOfDisplay(Dpy, Scr)),
  615. hexvalue.c_str());
  616. }
  617. Pixmap p = image->createPixmap(Dpy, Scr, Root);
  618. XSetWindowBackgroundPixmap(Dpy, Root, p);
  619. }
  620. XClearWindow(Dpy, Root);
  621. XFlush(Dpy);
  622. delete image;
  623. }
  624. // Check if there is a lockfile and a corresponding process
  625. void App::GetLock() {
  626. std::ifstream lockfile(cfg->getOption("lockfile").c_str());
  627. if (!lockfile) {
  628. // no lockfile present, create one
  629. std::ofstream lockfile(cfg->getOption("lockfile").c_str(), ios_base::out);
  630. if (!lockfile) {
  631. cerr << APPNAME << ": Could not create lock file: " << cfg->getOption("lockfile").c_str() << std::endl;
  632. exit(ERR_EXIT);
  633. }
  634. lockfile << getpid() << std::endl;
  635. lockfile.close();
  636. } else {
  637. // lockfile present, read pid from it
  638. int pid = 0;
  639. lockfile >> pid;
  640. lockfile.close();
  641. if (pid > 0) {
  642. // see if process with this pid exists
  643. int ret = kill(pid, 0);
  644. if (ret == 0 || (ret == -1 && errno == EPERM) ) {
  645. cerr << APPNAME << ": Another instance of the program is already running with PID " << pid << std::endl;
  646. exit(0);
  647. } else {
  648. cerr << APPNAME << ": Stale lockfile found, removing it" << std::endl;
  649. std::ofstream lockfile(cfg->getOption("lockfile").c_str(), ios_base::out);
  650. if (!lockfile) {
  651. cerr << APPNAME << ": Could not create new lock file: " << cfg->getOption("lockfile") << std::endl;
  652. exit(ERR_EXIT);
  653. }
  654. lockfile << getpid() << std::endl;
  655. lockfile.close();
  656. }
  657. }
  658. }
  659. }
  660. // Remove lockfile and close logs
  661. void App::RemoveLock() {
  662. remove(cfg->getOption("lockfile").c_str());
  663. }
  664. // Redirect stdout and stderr to log file
  665. void App::OpenLog() {
  666. FILE *log = fopen (cfg->getOption("logfile").c_str(),"a");
  667. if (!log) {
  668. cerr << APPNAME << ": Could not accesss log file: " << cfg->getOption("logfile") << endl;
  669. RemoveLock();
  670. exit(ERR_EXIT);
  671. }
  672. fclose(log);
  673. freopen (cfg->getOption("logfile").c_str(),"a",stdout);
  674. setvbuf(stdout, NULL, _IOLBF, BUFSIZ);
  675. freopen (cfg->getOption("logfile").c_str(),"a",stderr);
  676. setvbuf(stderr, NULL, _IONBF, BUFSIZ);
  677. }
  678. // Relases stdout/err
  679. void App::CloseLog(){
  680. fclose(stderr);
  681. fclose(stdout);
  682. }
  683. string App::findValidRandomTheme(const string& set)
  684. {
  685. // extract random theme from theme set; return empty string on error
  686. string name = set;
  687. struct stat buf;
  688. if (name[name.length()-1] == ',') {
  689. name = name.substr(0, name.length() - 1);
  690. }
  691. srandom(getpid()+time(NULL));
  692. vector<string> themes;
  693. string themefile;
  694. Cfg::split(themes, name, ',');
  695. do {
  696. int sel = random() % themes.size();
  697. name = Cfg::Trim(themes[sel]);
  698. themefile = string(THEMESDIR) +"/" + name + THEMESFILE;
  699. if (stat(themefile.c_str(), &buf) != 0) {
  700. themes.erase(find(themes.begin(), themes.end(), name));
  701. cerr << APPNAME << ": Invalid theme in config: "
  702. << name << endl;
  703. name = "";
  704. }
  705. } while (name == "" && themes.size());
  706. return name;
  707. }
  708. void App::replaceVariables(string& input,
  709. const string& var,
  710. const string& value)
  711. {
  712. string::size_type pos = 0;
  713. int len = var.size();
  714. while ((pos = input.find(var, pos)) != string::npos) {
  715. input = input.substr(0, pos) + value + input.substr(pos+len);
  716. }
  717. }
  718. void App::CreateServerAuth() {
  719. /* create mit cookie */
  720. int i, r;
  721. int hexcount = 0;
  722. string authfile;
  723. string cmd;
  724. char *digits = "0123456789abcdef";
  725. srand( time(NULL) );
  726. for ( i = 0; i < 31; i++ ) {
  727. r = rand()%16;
  728. mcookie[i] = digits[r];
  729. if (r>9)
  730. hexcount++;
  731. }
  732. /* MIT-COOKIE: even occurrences of digits and hex digits */
  733. if ((hexcount%2) == 0) {
  734. r = rand()%10;
  735. } else {
  736. r = rand()%5+10;
  737. }
  738. mcookie[31] = digits[r];
  739. /* reinitialize auth file */
  740. authfile = cfg->getOption("authfile");
  741. remove(authfile.c_str());
  742. putenv(StrConcat("XAUTHORITY=", authfile.c_str()));
  743. cmd = cfg->getOption("xauth_path") + " -q -f " + authfile + " add :0 . " + mcookie;
  744. system(cmd.c_str());
  745. }
  746. char* App::StrConcat(const char* str1, const char* str2) {
  747. char* tmp = new char[strlen(str1) + strlen(str2) + 1];
  748. strcpy(tmp, str1);
  749. strcat(tmp, str2);
  750. return tmp;
  751. }
  752. void App::UpdatePid() {
  753. std::ofstream lockfile(cfg->getOption("lockfile").c_str(), ios_base::out);
  754. if (!lockfile) {
  755. cerr << APPNAME << ": Could not update lock file: " << cfg->getOption("lockfile").c_str() << std::endl;
  756. exit(ERR_EXIT);
  757. }
  758. lockfile << getpid() << std::endl;
  759. lockfile.close();
  760. }