app.cpp 23 KB

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