You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

XserverDesktop.cc 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. /* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
  2. * Copyright 2009-2017 Pierre Ossman for Cendio AB
  3. * Copyright 2014 Brian P. Hinz
  4. *
  5. * This 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. * This software is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this software; if not, write to the Free Software
  17. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
  18. * USA.
  19. */
  20. //
  21. // XserverDesktop.cxx
  22. //
  23. #include <assert.h>
  24. #include <stdio.h>
  25. #include <stdlib.h>
  26. #include <strings.h>
  27. #include <unistd.h>
  28. #include <pwd.h>
  29. #include <sys/types.h>
  30. #include <sys/stat.h>
  31. #include <fcntl.h>
  32. #include <sys/utsname.h>
  33. #include <network/Socket.h>
  34. #include <rfb/Exception.h>
  35. #include <rfb/VNCServerST.h>
  36. #include <rfb/HTTPServer.h>
  37. #include <rfb/LogWriter.h>
  38. #include <rfb/Configuration.h>
  39. #include <rfb/ServerCore.h>
  40. #include "XserverDesktop.h"
  41. #include "vncBlockHandler.h"
  42. #include "vncExtInit.h"
  43. #include "vncHooks.h"
  44. #include "vncSelection.h"
  45. #include "XorgGlue.h"
  46. #include "Input.h"
  47. extern "C" {
  48. void vncSetGlueContext(int screenIndex);
  49. }
  50. using namespace rfb;
  51. using namespace network;
  52. static LogWriter vlog("XserverDesktop");
  53. BoolParameter rawKeyboard("RawKeyboard",
  54. "Send keyboard events straight through and "
  55. "avoid mapping them to the current keyboard "
  56. "layout", false);
  57. IntParameter queryConnectTimeout("QueryConnectTimeout",
  58. "Number of seconds to show the "
  59. "Accept Connection dialog before "
  60. "rejecting the connection",
  61. 10);
  62. class FileHTTPServer : public rfb::HTTPServer {
  63. public:
  64. FileHTTPServer(XserverDesktop* d) : desktop(d) {}
  65. virtual ~FileHTTPServer() {}
  66. virtual rdr::InStream* getFile(const char* name, const char** contentType,
  67. int* contentLength, time_t* lastModified)
  68. {
  69. if (name[0] != '/' || strstr(name, "..") != 0) {
  70. vlog.info("http request was for invalid file name");
  71. return 0;
  72. }
  73. if (strcmp(name, "/") == 0) name = "/index.vnc";
  74. CharArray httpDirStr(httpDir.getData());
  75. CharArray fname(strlen(httpDirStr.buf)+strlen(name)+1);
  76. sprintf(fname.buf, "%s%s", httpDirStr.buf, name);
  77. int fd = open(fname.buf, O_RDONLY);
  78. if (fd < 0) return 0;
  79. rdr::InStream* is = new rdr::FdInStream(fd, -1, 0, true);
  80. *contentType = guessContentType(name, *contentType);
  81. if (strlen(name) > 4 && strcasecmp(&name[strlen(name)-4], ".vnc") == 0) {
  82. is = new rdr::SubstitutingInStream(is, desktop, 20);
  83. *contentType = "text/html";
  84. } else {
  85. struct stat st;
  86. if (fstat(fd, &st) == 0) {
  87. *contentLength = st.st_size;
  88. *lastModified = st.st_mtime;
  89. }
  90. }
  91. return is;
  92. }
  93. XserverDesktop* desktop;
  94. };
  95. XserverDesktop::XserverDesktop(int screenIndex_,
  96. std::list<network::SocketListener*> listeners_,
  97. std::list<network::SocketListener*> httpListeners_,
  98. const char* name, const rfb::PixelFormat &pf,
  99. int width, int height,
  100. void* fbptr, int stride)
  101. : screenIndex(screenIndex_),
  102. server(0), httpServer(0),
  103. listeners(listeners_), httpListeners(httpListeners_),
  104. directFbptr(true),
  105. queryConnectId(0), queryConnectTimer(this)
  106. {
  107. format = pf;
  108. server = new VNCServerST(name, this);
  109. setFramebuffer(width, height, fbptr, stride);
  110. server->setQueryConnectionHandler(this);
  111. if (!httpListeners.empty ())
  112. httpServer = new FileHTTPServer(this);
  113. for (std::list<SocketListener*>::iterator i = listeners.begin();
  114. i != listeners.end();
  115. i++) {
  116. vncSetNotifyFd((*i)->getFd(), screenIndex, true, false);
  117. }
  118. for (std::list<SocketListener*>::iterator i = httpListeners.begin();
  119. i != httpListeners.end();
  120. i++) {
  121. vncSetNotifyFd((*i)->getFd(), screenIndex, true, false);
  122. }
  123. }
  124. XserverDesktop::~XserverDesktop()
  125. {
  126. while (!listeners.empty()) {
  127. vncRemoveNotifyFd(listeners.back()->getFd());
  128. delete listeners.back();
  129. listeners.pop_back();
  130. }
  131. while (!httpListeners.empty()) {
  132. vncRemoveNotifyFd(listeners.back()->getFd());
  133. delete httpListeners.back();
  134. httpListeners.pop_back();
  135. }
  136. if (!directFbptr)
  137. delete [] data;
  138. delete httpServer;
  139. delete server;
  140. }
  141. void XserverDesktop::blockUpdates()
  142. {
  143. server->blockUpdates();
  144. }
  145. void XserverDesktop::unblockUpdates()
  146. {
  147. server->unblockUpdates();
  148. }
  149. void XserverDesktop::setFramebuffer(int w, int h, void* fbptr, int stride_)
  150. {
  151. ScreenSet layout;
  152. width_ = w;
  153. height_ = h;
  154. if (!directFbptr) {
  155. delete [] data;
  156. directFbptr = true;
  157. }
  158. if (!fbptr) {
  159. fbptr = new rdr::U8[w * h * (format.bpp/8)];
  160. stride_ = w;
  161. directFbptr = false;
  162. }
  163. data = (rdr::U8*)fbptr;
  164. stride = stride_;
  165. vncSetGlueContext(screenIndex);
  166. layout = ::computeScreenLayout(&outputIdMap);
  167. server->setPixelBuffer(this, layout);
  168. }
  169. void XserverDesktop::refreshScreenLayout()
  170. {
  171. vncSetGlueContext(screenIndex);
  172. server->setScreenLayout(::computeScreenLayout(&outputIdMap));
  173. }
  174. char* XserverDesktop::substitute(const char* varName)
  175. {
  176. if (strcmp(varName, "$$") == 0) {
  177. return rfb::strDup("$");
  178. }
  179. if (strcmp(varName, "$PORT") == 0) {
  180. char* str = new char[10];
  181. sprintf(str, "%d", listeners.empty () ? 0 : (*listeners.begin ())->getMyPort());
  182. return str;
  183. }
  184. if (strcmp(varName, "$WIDTH") == 0) {
  185. char* str = new char[10];
  186. sprintf(str, "%d", width());
  187. return str;
  188. }
  189. if (strcmp(varName, "$HEIGHT") == 0) {
  190. char* str = new char[10];
  191. sprintf(str, "%d", height());
  192. return str;
  193. }
  194. if (strcmp(varName, "$APPLETWIDTH") == 0) {
  195. char* str = new char[10];
  196. sprintf(str, "%d", width());
  197. return str;
  198. }
  199. if (strcmp(varName, "$APPLETHEIGHT") == 0) {
  200. char* str = new char[10];
  201. sprintf(str, "%d", height());
  202. return str;
  203. }
  204. if (strcmp(varName, "$DESKTOP") == 0) {
  205. return rfb::strDup(server->getName());
  206. }
  207. if (strcmp(varName, "$DISPLAY") == 0) {
  208. struct utsname uts;
  209. uname(&uts);
  210. char* str = new char[256];
  211. strncpy(str, uts.nodename, 240);
  212. str[239] = '\0'; /* Ensure string is zero-terminated */
  213. strcat(str, ":");
  214. strncat(str, vncGetDisplay(), 10);
  215. return str;
  216. }
  217. if (strcmp(varName, "$USER") == 0) {
  218. struct passwd* user = getpwuid(getuid());
  219. return rfb::strDup(user ? user->pw_name : "?");
  220. }
  221. return 0;
  222. }
  223. rfb::VNCServerST::queryResult
  224. XserverDesktop::queryConnection(network::Socket* sock,
  225. const char* userName,
  226. char** reason)
  227. {
  228. int count;
  229. if (queryConnectTimer.isStarted()) {
  230. *reason = strDup("Another connection is currently being queried.");
  231. return rfb::VNCServerST::REJECT;
  232. }
  233. count = vncNotifyQueryConnect();
  234. if (count == 0) {
  235. *reason = strDup("Unable to query the local user to accept the connection.");
  236. return rfb::VNCServerST::REJECT;
  237. }
  238. queryConnectAddress.replaceBuf(sock->getPeerAddress());
  239. if (!userName)
  240. userName = "(anonymous)";
  241. queryConnectUsername.replaceBuf(strDup(userName));
  242. queryConnectId = (uint32_t)(intptr_t)sock;
  243. queryConnectSocket = sock;
  244. queryConnectTimer.start(queryConnectTimeout * 1000);
  245. return rfb::VNCServerST::PENDING;
  246. }
  247. void XserverDesktop::bell()
  248. {
  249. server->bell();
  250. }
  251. void XserverDesktop::setLEDState(unsigned int state)
  252. {
  253. server->setLEDState(state);
  254. }
  255. void XserverDesktop::serverCutText(const char* str, int len)
  256. {
  257. try {
  258. server->serverCutText(str, len);
  259. } catch (rdr::Exception& e) {
  260. vlog.error("XserverDesktop::serverCutText: %s",e.str());
  261. }
  262. }
  263. void XserverDesktop::setDesktopName(const char* name)
  264. {
  265. try {
  266. server->setName(name);
  267. } catch (rdr::Exception& e) {
  268. vlog.error("XserverDesktop::setDesktopName: %s",e.str());
  269. }
  270. }
  271. void XserverDesktop::setCursor(int width, int height, int hotX, int hotY,
  272. const unsigned char *rgbaData)
  273. {
  274. rdr::U8* cursorData;
  275. rdr::U8 *out;
  276. const unsigned char *in;
  277. cursorData = new rdr::U8[width * height * 4];
  278. // Un-premultiply alpha
  279. in = rgbaData;
  280. out = cursorData;
  281. for (int y = 0; y < height; y++) {
  282. for (int x = 0; x < width; x++) {
  283. rdr::U8 alpha;
  284. alpha = in[3];
  285. if (alpha == 0)
  286. alpha = 1; // Avoid division by zero
  287. *out++ = (unsigned)*in++ * 255/alpha;
  288. *out++ = (unsigned)*in++ * 255/alpha;
  289. *out++ = (unsigned)*in++ * 255/alpha;
  290. *out++ = *in++;
  291. }
  292. }
  293. try {
  294. server->setCursor(width, height, Point(hotX, hotY), cursorData);
  295. } catch (rdr::Exception& e) {
  296. vlog.error("XserverDesktop::setCursor: %s",e.str());
  297. }
  298. delete [] cursorData;
  299. }
  300. void XserverDesktop::add_changed(const rfb::Region &region)
  301. {
  302. try {
  303. server->add_changed(region);
  304. } catch (rdr::Exception& e) {
  305. vlog.error("XserverDesktop::add_changed: %s",e.str());
  306. }
  307. }
  308. void XserverDesktop::add_copied(const rfb::Region &dest, const rfb::Point &delta)
  309. {
  310. try {
  311. server->add_copied(dest, delta);
  312. } catch (rdr::Exception& e) {
  313. vlog.error("XserverDesktop::add_copied: %s",e.str());
  314. }
  315. }
  316. void XserverDesktop::handleSocketEvent(int fd, bool read, bool write)
  317. {
  318. try {
  319. if (read) {
  320. if (handleListenerEvent(fd, &listeners, server))
  321. return;
  322. if (handleListenerEvent(fd, &httpListeners, httpServer))
  323. return;
  324. }
  325. if (handleSocketEvent(fd, server, read, write))
  326. return;
  327. if (handleSocketEvent(fd, httpServer, read, write))
  328. return;
  329. vlog.error("Cannot find file descriptor for socket event");
  330. } catch (rdr::Exception& e) {
  331. vlog.error("XserverDesktop::handleSocketEvent: %s",e.str());
  332. }
  333. }
  334. bool XserverDesktop::handleListenerEvent(int fd,
  335. std::list<SocketListener*>* sockets,
  336. SocketServer* sockserv)
  337. {
  338. std::list<SocketListener*>::iterator i;
  339. for (i = sockets->begin(); i != sockets->end(); i++) {
  340. if ((*i)->getFd() == fd)
  341. break;
  342. }
  343. if (i == sockets->end())
  344. return false;
  345. Socket* sock = (*i)->accept();
  346. sock->outStream().setBlocking(false);
  347. vlog.debug("new client, sock %d", sock->getFd());
  348. sockserv->addSocket(sock);
  349. vncSetNotifyFd(sock->getFd(), screenIndex, true, false);
  350. return true;
  351. }
  352. bool XserverDesktop::handleSocketEvent(int fd,
  353. SocketServer* sockserv,
  354. bool read, bool write)
  355. {
  356. std::list<Socket*> sockets;
  357. std::list<Socket*>::iterator i;
  358. sockserv->getSockets(&sockets);
  359. for (i = sockets.begin(); i != sockets.end(); i++) {
  360. if ((*i)->getFd() == fd)
  361. break;
  362. }
  363. if (i == sockets.end())
  364. return false;
  365. if (read)
  366. sockserv->processSocketReadEvent(*i);
  367. if (write)
  368. sockserv->processSocketWriteEvent(*i);
  369. return true;
  370. }
  371. void XserverDesktop::blockHandler(int* timeout)
  372. {
  373. // We don't have a good callback for when we can init input devices[1],
  374. // so we abuse the fact that this routine will be called first thing
  375. // once the dix is done initialising.
  376. // [1] Technically Xvnc has InitInput(), but libvnc.so has nothing.
  377. vncInitInputDevice();
  378. try {
  379. std::list<Socket*> sockets;
  380. std::list<Socket*>::iterator i;
  381. server->getSockets(&sockets);
  382. for (i = sockets.begin(); i != sockets.end(); i++) {
  383. int fd = (*i)->getFd();
  384. if ((*i)->isShutdown()) {
  385. vlog.debug("client gone, sock %d",fd);
  386. vncRemoveNotifyFd(fd);
  387. server->removeSocket(*i);
  388. vncClientGone(fd);
  389. delete (*i);
  390. } else {
  391. /* Update existing NotifyFD to listen for write (or not) */
  392. vncSetNotifyFd(fd, screenIndex, true, (*i)->outStream().bufferUsage() > 0);
  393. }
  394. }
  395. if (httpServer) {
  396. httpServer->getSockets(&sockets);
  397. for (i = sockets.begin(); i != sockets.end(); i++) {
  398. int fd = (*i)->getFd();
  399. if ((*i)->isShutdown()) {
  400. vlog.debug("http client gone, sock %d",fd);
  401. vncRemoveNotifyFd(fd);
  402. httpServer->removeSocket(*i);
  403. delete (*i);
  404. } else {
  405. /* Update existing NotifyFD to listen for write (or not) */
  406. vncSetNotifyFd(fd, screenIndex, true, (*i)->outStream().bufferUsage() > 0);
  407. }
  408. }
  409. }
  410. // We are responsible for propagating mouse movement between clients
  411. int cursorX, cursorY;
  412. vncGetPointerPos(&cursorX, &cursorY);
  413. cursorX -= vncGetScreenX(screenIndex);
  414. cursorY -= vncGetScreenY(screenIndex);
  415. if (oldCursorPos.x != cursorX || oldCursorPos.y != cursorY) {
  416. oldCursorPos.x = cursorX;
  417. oldCursorPos.y = cursorY;
  418. server->setCursorPos(oldCursorPos);
  419. }
  420. // Trigger timers and check when the next will expire
  421. int nextTimeout = server->checkTimeouts();
  422. if (nextTimeout > 0 && (*timeout == -1 || nextTimeout < *timeout))
  423. *timeout = nextTimeout;
  424. } catch (rdr::Exception& e) {
  425. vlog.error("XserverDesktop::blockHandler: %s",e.str());
  426. }
  427. }
  428. void XserverDesktop::addClient(Socket* sock, bool reverse)
  429. {
  430. vlog.debug("new client, sock %d reverse %d",sock->getFd(),reverse);
  431. sock->outStream().setBlocking(false);
  432. server->addSocket(sock, reverse);
  433. vncSetNotifyFd(sock->getFd(), screenIndex, true, false);
  434. }
  435. void XserverDesktop::disconnectClients()
  436. {
  437. vlog.debug("disconnecting all clients");
  438. return server->closeClients("Disconnection from server end");
  439. }
  440. void XserverDesktop::getQueryConnect(uint32_t* opaqueId,
  441. const char** address,
  442. const char** username,
  443. int *timeout)
  444. {
  445. *opaqueId = queryConnectId;
  446. if (!queryConnectTimer.isStarted()) {
  447. *address = "";
  448. *username = "";
  449. *timeout = 0;
  450. } else {
  451. *address = queryConnectAddress.buf;
  452. *username = queryConnectUsername.buf;
  453. *timeout = queryConnectTimeout;
  454. }
  455. }
  456. void XserverDesktop::approveConnection(uint32_t opaqueId, bool accept,
  457. const char* rejectMsg)
  458. {
  459. if (queryConnectId == opaqueId) {
  460. server->approveConnection(queryConnectSocket, accept, rejectMsg);
  461. queryConnectId = 0;
  462. queryConnectTimer.stop();
  463. }
  464. }
  465. ///////////////////////////////////////////////////////////////////////////
  466. //
  467. // SDesktop callbacks
  468. void XserverDesktop::pointerEvent(const Point& pos, int buttonMask)
  469. {
  470. vncPointerMove(pos.x + vncGetScreenX(screenIndex),
  471. pos.y + vncGetScreenY(screenIndex));
  472. vncPointerButtonAction(buttonMask);
  473. }
  474. void XserverDesktop::clientCutText(const char* str, int len)
  475. {
  476. vncClientCutText(str, len);
  477. }
  478. unsigned int XserverDesktop::setScreenLayout(int fb_width, int fb_height,
  479. const rfb::ScreenSet& layout)
  480. {
  481. char buffer[2048];
  482. vlog.debug("Got request for framebuffer resize to %dx%d",
  483. fb_width, fb_height);
  484. layout.print(buffer, sizeof(buffer));
  485. vlog.debug("%s", buffer);
  486. vncSetGlueContext(screenIndex);
  487. return ::setScreenLayout(fb_width, fb_height, layout, &outputIdMap);
  488. }
  489. void XserverDesktop::grabRegion(const rfb::Region& region)
  490. {
  491. if (directFbptr)
  492. return;
  493. std::vector<rfb::Rect> rects;
  494. std::vector<rfb::Rect>::iterator i;
  495. region.get_rects(&rects);
  496. for (i = rects.begin(); i != rects.end(); i++) {
  497. rdr::U8 *buffer;
  498. int stride;
  499. buffer = getBufferRW(*i, &stride);
  500. vncGetScreenImage(screenIndex, i->tl.x, i->tl.y, i->width(), i->height(),
  501. (char*)buffer, stride * format.bpp/8);
  502. commitBufferRW(*i);
  503. }
  504. }
  505. void XserverDesktop::keyEvent(rdr::U32 keysym, rdr::U32 keycode, bool down)
  506. {
  507. if (!rawKeyboard)
  508. keycode = 0;
  509. vncKeyboardEvent(keysym, keycode, down);
  510. }
  511. bool XserverDesktop::handleTimeout(Timer* t)
  512. {
  513. if (t == &queryConnectTimer) {
  514. server->approveConnection(queryConnectSocket, false,
  515. "The attempt to prompt the user to "
  516. "accept the connection failed");
  517. }
  518. return false;
  519. }