app.cpp 22 KB

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