Audio plugin host https://kx.studio/carla
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.

659 lines
17KB

  1. /*
  2. * Carla Pipe utils based on lv2fil UI code
  3. * Copyright (C) 2009 Nedko Arnaudov <nedko@arnaudov.name>
  4. * Copyright (C) 2013-2014 Filipe Coelho <falktx@falktx.com>
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU General Public License as
  8. * published by the Free Software Foundation; either version 2 of
  9. * the License, or any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * For a full copy of the GNU General Public License see the doc/GPL.txt file.
  17. */
  18. #ifndef CARLA_PIPE_UTILS_HPP_INCLUDED
  19. #define CARLA_PIPE_UTILS_HPP_INCLUDED
  20. #include "CarlaMutex.hpp"
  21. #include "CarlaString.hpp"
  22. #include <cerrno>
  23. #include <clocale>
  24. #include <fcntl.h>
  25. #include <signal.h>
  26. #include <sys/wait.h>
  27. #define WAIT_START_TIMEOUT 3000 /* ms */
  28. #define WAIT_ZOMBIE_TIMEOUT 3000 /* ms */
  29. #define WAIT_STEP 100 /* ms */
  30. // -----------------------------------------------------------------------
  31. class CarlaPipeServer
  32. {
  33. protected:
  34. CarlaPipeServer()
  35. : fPipeRecv(-1),
  36. fPipeSend(-1),
  37. fIsReading(false),
  38. fPid(-1)
  39. {
  40. carla_debug("CarlaPipeServer::CarlaPipeServer()");
  41. carla_zeroChar(fTmpBuf, 0xff+1);
  42. }
  43. // -------------------------------------------------------------------
  44. public:
  45. virtual ~CarlaPipeServer()
  46. {
  47. carla_debug("CarlaPipeServer::~CarlaPipeServer()");
  48. stop();
  49. }
  50. bool isOk() const noexcept
  51. {
  52. return (fPipeRecv != -1 && fPipeSend != -1 && fPid != -1);
  53. }
  54. bool start(const char* const filename, const char* const arg1, const char* const arg2) noexcept
  55. {
  56. CARLA_SAFE_ASSERT_RETURN(filename != nullptr && filename[0] != '\0', false);
  57. CARLA_SAFE_ASSERT_RETURN(arg1 != nullptr, false);
  58. CARLA_SAFE_ASSERT_RETURN(arg2 != nullptr, false);
  59. carla_debug("CarlaPipeServer::start(\"%s\", \"%s\", \"%s\")", filename, arg1, arg2);
  60. const CarlaMutexLocker cml(fWriteLock);
  61. //----------------------------------------------------------------
  62. const char* argv[6];
  63. //----------------------------------------------------------------
  64. // argv[0] => filename
  65. argv[0] = filename;
  66. //----------------------------------------------------------------
  67. // argv[1-2] => args
  68. argv[1] = arg1;
  69. argv[2] = arg2;
  70. //----------------------------------------------------------------
  71. // argv[3-4] => pipes
  72. int pipe1[2]; // written by host process, read by plugin UI process
  73. int pipe2[2]; // written by plugin UI process, read by host process
  74. if (::pipe(pipe1) != 0)
  75. {
  76. fail("pipe1 creation failed");
  77. return false;
  78. }
  79. if (::pipe(pipe2) != 0)
  80. {
  81. try {
  82. ::close(pipe1[0]);
  83. ::close(pipe1[1]);
  84. } catch (...) {}
  85. fail("pipe2 creation failed");
  86. return false;
  87. }
  88. char pipeRecv[100+1];
  89. char pipeSend[100+1];
  90. std::snprintf(pipeRecv, 100, "%d", pipe1[0]); // [0] means reading end
  91. std::snprintf(pipeSend, 100, "%d", pipe2[1]); // [1] means writting end
  92. pipeRecv[100] = '\0';
  93. pipeSend[100] = '\0';
  94. argv[3] = pipeRecv; // reading end
  95. argv[4] = pipeSend; // writting end
  96. //----------------------------------------------------------------
  97. // argv[5] => null
  98. argv[5] = nullptr;
  99. //----------------------------------------------------------------
  100. // fork
  101. int ret = -1;
  102. if ((! fork_exec(argv, &ret)) || ret == -1)
  103. {
  104. try {
  105. ::close(pipe1[0]);
  106. ::close(pipe1[1]);
  107. } catch (...) {}
  108. try {
  109. ::close(pipe2[0]);
  110. ::close(pipe2[1]);
  111. } catch (...) {}
  112. fail("fork_exec() failed");
  113. return false;
  114. }
  115. fPid = ret;
  116. // fork duplicated the handles, close pipe ends that are used by the child process
  117. try {
  118. ::close(pipe1[0]);
  119. } catch(...) {}
  120. try {
  121. ::close(pipe2[1]);
  122. } catch(...) {}
  123. fPipeSend = pipe1[1]; // [1] means writting end
  124. fPipeRecv = pipe2[0]; // [0] means reading end
  125. // set non-block
  126. try {
  127. ret = ::fcntl(fPipeRecv, F_SETFL, ::fcntl(fPipeRecv, F_GETFL) | O_NONBLOCK);
  128. } catch (...) {
  129. ret = -1;
  130. fail("failed to set pipe as non-block");
  131. }
  132. //----------------------------------------------------------------
  133. // wait a while for child process to confirm it is alive
  134. if (ret != -1)
  135. {
  136. char ch;
  137. ssize_t ret2;
  138. for (int i=0; ;)
  139. {
  140. try {
  141. ret2 = ::read(fPipeRecv, &ch, 1);
  142. }
  143. catch (...) {
  144. fail("failed to read from pipe");
  145. break;
  146. }
  147. switch (ret2)
  148. {
  149. case -1:
  150. if (errno == EAGAIN)
  151. {
  152. if (i < WAIT_START_TIMEOUT / WAIT_STEP)
  153. {
  154. carla_msleep(WAIT_STEP);
  155. ++i;
  156. continue;
  157. }
  158. carla_stderr("we have waited for child with pid %d to appear for %.1f seconds and we are giving up", (int)fPid, (float)WAIT_START_TIMEOUT / 1000.0f);
  159. }
  160. else
  161. carla_stderr("read() failed: %s", std::strerror(errno));
  162. break;
  163. case 1:
  164. if (ch == '\n') {
  165. // success
  166. return true;
  167. }
  168. carla_stderr("read() has wrong first char '%c'", ch);
  169. break;
  170. default:
  171. carla_stderr("read() returned %i", int(ret2));
  172. break;
  173. }
  174. break;
  175. }
  176. }
  177. carla_stderr("force killing misbehaved child %i (start)", int(fPid));
  178. if (kill(fPid, SIGKILL) == -1)
  179. {
  180. carla_stderr("kill() failed: %s (start)\n", std::strerror(errno));
  181. }
  182. // wait a while child to exit, we dont like zombie processes
  183. wait_child(fPid);
  184. // close pipes
  185. try {
  186. ::close(fPipeRecv);
  187. } catch (...) {}
  188. try {
  189. ::close(fPipeSend);
  190. } catch (...) {}
  191. fPipeRecv = -1;
  192. fPipeSend = -1;
  193. fPid = -1;
  194. return false;
  195. }
  196. void stop() noexcept
  197. {
  198. carla_debug("CarlaPipeServer::stop()");
  199. if (fPipeSend == -1 || fPipeRecv == -1 || fPid == -1)
  200. return;
  201. const CarlaMutexLocker cml(fWriteLock);
  202. try {
  203. ssize_t ignore = ::write(fPipeSend, "quit\n", 5);
  204. (void)ignore;
  205. } CARLA_SAFE_EXCEPTION("CarlaPipeServer::stop");
  206. waitChildClose();
  207. try {
  208. ::close(fPipeRecv);
  209. } catch (...) {}
  210. try {
  211. ::close(fPipeSend);
  212. } catch (...) {}
  213. fPipeRecv = -1;
  214. fPipeSend = -1;
  215. fPid = -1;
  216. }
  217. void idle()
  218. {
  219. const char* locale = nullptr;
  220. for (;;)
  221. {
  222. const char* const msg(readline());
  223. if (msg == nullptr)
  224. break;
  225. if (locale == nullptr)
  226. {
  227. locale = carla_strdup(setlocale(LC_NUMERIC, nullptr));
  228. setlocale(LC_NUMERIC, "POSIX");
  229. }
  230. fIsReading = true;
  231. msgReceived(msg);
  232. fIsReading = false;
  233. delete[] msg;
  234. }
  235. if (locale != nullptr)
  236. {
  237. setlocale(LC_NUMERIC, locale);
  238. delete[] locale;
  239. }
  240. }
  241. // -------------------------------------------------------------------
  242. bool readNextLineAsBool(bool& value) noexcept
  243. {
  244. CARLA_SAFE_ASSERT_RETURN(fIsReading, false);
  245. if (const char* const msg = readline())
  246. {
  247. value = (std::strcmp(msg, "true") == 0);
  248. delete[] msg;
  249. return true;
  250. }
  251. return false;
  252. }
  253. bool readNextLineAsInt(int32_t& value) noexcept
  254. {
  255. CARLA_SAFE_ASSERT_RETURN(fIsReading, false);
  256. if (const char* const msg = readline())
  257. {
  258. value = std::atoi(msg);
  259. delete[] msg;
  260. return true;
  261. }
  262. return false;
  263. }
  264. bool readNextLineAsUInt(uint32_t& value) noexcept
  265. {
  266. CARLA_SAFE_ASSERT_RETURN(fIsReading, false);
  267. if (const char* const msg = readline())
  268. {
  269. int32_t tmp = std::atoi(msg);
  270. delete[] msg;
  271. if (tmp >= 0)
  272. {
  273. value = static_cast<uint32_t>(tmp);
  274. return true;
  275. }
  276. }
  277. return false;
  278. }
  279. bool readNextLineAsLong(int64_t& value) noexcept
  280. {
  281. CARLA_SAFE_ASSERT_RETURN(fIsReading, false);
  282. if (const char* const msg = readline())
  283. {
  284. value = std::atol(msg);
  285. delete[] msg;
  286. return true;
  287. }
  288. return false;
  289. }
  290. bool readNextLineAsULong(uint64_t& value) noexcept
  291. {
  292. CARLA_SAFE_ASSERT_RETURN(fIsReading, false);
  293. if (const char* const msg = readline())
  294. {
  295. int64_t tmp = std::atol(msg);
  296. delete[] msg;
  297. if (tmp >= 0)
  298. {
  299. value = static_cast<uint64_t>(tmp);
  300. return true;
  301. }
  302. }
  303. return false;
  304. }
  305. bool readNextLineAsFloat(float& value) noexcept
  306. {
  307. CARLA_SAFE_ASSERT_RETURN(fIsReading, false);
  308. if (const char* const msg = readline())
  309. {
  310. const bool ret(std::sscanf(msg, "%f", &value) == 1);
  311. delete[] msg;
  312. return ret;
  313. }
  314. return false;
  315. }
  316. bool readNextLineAsString(const char*& value) noexcept
  317. {
  318. CARLA_SAFE_ASSERT_RETURN(fIsReading, false);
  319. if (const char* const msg = readline())
  320. {
  321. value = msg;
  322. return true;
  323. }
  324. return false;
  325. }
  326. // -------------------------------------------------------------------
  327. // must be locked before calling
  328. void writeMsg(const char* const msg) const noexcept
  329. {
  330. CARLA_SAFE_ASSERT_RETURN(fPipeSend != -1,);
  331. const CarlaMutexTryLocker cmtl(fWriteLock);
  332. try {
  333. ssize_t ignore = ::write(fPipeSend, msg, std::strlen(msg));
  334. (void)ignore;
  335. } CARLA_SAFE_EXCEPTION("CarlaPipeServer::writeMsg");
  336. }
  337. void writeMsg(const char* const msg, size_t size) const noexcept
  338. {
  339. CARLA_SAFE_ASSERT_RETURN(fPipeSend != -1,);
  340. const CarlaMutexTryLocker cmtl(fWriteLock);
  341. try {
  342. ssize_t ignore = ::write(fPipeSend, msg, size);
  343. (void)ignore;
  344. } CARLA_SAFE_EXCEPTION("CarlaPipeServer::writeMsg");
  345. }
  346. void writeAndFixMsg(const char* const msg) noexcept
  347. {
  348. CARLA_SAFE_ASSERT_RETURN(fPipeSend != -1,);
  349. const CarlaMutexTryLocker cmtl(fWriteLock);
  350. const size_t size(msg != nullptr ? std::strlen(msg) : 0);
  351. char fixedMsg[size+2];
  352. if (size > 0)
  353. {
  354. std::strcpy(fixedMsg, msg);
  355. for (size_t i=0; i < size; ++i)
  356. {
  357. if (fixedMsg[i] == '\n')
  358. fixedMsg[i] = '\r';
  359. }
  360. if (fixedMsg[size-1] == '\r')
  361. {
  362. fixedMsg[size-1] = '\n';
  363. fixedMsg[size] = '\0';
  364. fixedMsg[size+1] = '\0';
  365. }
  366. else
  367. {
  368. fixedMsg[size] = '\n';
  369. fixedMsg[size+1] = '\0';
  370. }
  371. }
  372. else
  373. {
  374. fixedMsg[0] = '\n';
  375. fixedMsg[1] = '\0';
  376. }
  377. try {
  378. ssize_t ignore = ::write(fPipeSend, fixedMsg, size+1);
  379. (void)ignore;
  380. } CARLA_SAFE_EXCEPTION("CarlaPipeServer::writeAndFixMsg");
  381. }
  382. // -------------------------------------------------------------------
  383. void waitChildClose() noexcept
  384. {
  385. if (! wait_child(fPid))
  386. {
  387. carla_stderr2("force killing misbehaved child %i (exit)", int(fPid));
  388. if (kill(fPid, SIGKILL) == -1)
  389. carla_stderr2("kill() failed: %s (exit)", std::strerror(errno));
  390. else
  391. wait_child(fPid);
  392. }
  393. }
  394. // -------------------------------------------------------------------
  395. protected:
  396. // common write lock
  397. CarlaMutex fWriteLock;
  398. // to possibly send errors somewhere
  399. virtual void fail(const char* const error)
  400. {
  401. carla_stderr2(error);
  402. }
  403. // returns true if msg handled
  404. virtual bool msgReceived(const char* const msg) noexcept = 0;
  405. // -------------------------------------------------------------------
  406. private:
  407. int fPipeRecv; // the pipe end that is used for receiving messages from UI
  408. int fPipeSend; // the pipe end that is used for sending messages to UI
  409. bool fIsReading;
  410. pid_t fPid;
  411. char fTmpBuf[0xff+1];
  412. CarlaString fTmpStr;
  413. // -------------------------------------------------------------------
  414. const char* readline() noexcept
  415. {
  416. char ch;
  417. char* ptr = fTmpBuf;
  418. ssize_t ret;
  419. fTmpStr.clear();
  420. for (int i=0; i < 0xff; ++i)
  421. {
  422. try {
  423. ret = ::read(fPipeRecv, &ch, 1);
  424. }
  425. catch (...) {
  426. break;
  427. }
  428. if (ret == 1 && ch != '\n')
  429. {
  430. if (ch == '\r')
  431. ch = '\n';
  432. *ptr++ = ch;
  433. if (i+1 == 0xff)
  434. {
  435. i = 0;
  436. ptr = fTmpBuf;
  437. fTmpStr += fTmpBuf;
  438. }
  439. continue;
  440. }
  441. if (fTmpStr.isNotEmpty() || ptr != fTmpBuf)
  442. {
  443. if (ptr != fTmpBuf)
  444. {
  445. *ptr = '\0';
  446. fTmpStr += fTmpBuf;
  447. }
  448. try {
  449. return fTmpStr.dup();
  450. }
  451. catch(...) {
  452. return nullptr;
  453. }
  454. }
  455. break;
  456. }
  457. return nullptr;
  458. }
  459. // -------------------------------------------------------------------
  460. static bool fork_exec(const char* const argv[6], int* const retp) noexcept
  461. {
  462. const pid_t ret = *retp = vfork();
  463. switch (ret)
  464. {
  465. case 0: // child process
  466. execvp(argv[0], const_cast<char* const*>(argv));
  467. carla_stderr2("exec failed: %s", std::strerror(errno));
  468. _exit(0); // this is not noexcept safe but doesn't matter anyway
  469. return false;
  470. case -1: // error
  471. carla_stderr2("fork() failed: %s", std::strerror(errno));
  472. _exit(0); // this is not noexcept safe but doesn't matter anyway
  473. return false;
  474. }
  475. return true;
  476. }
  477. static bool wait_child(const pid_t pid) noexcept
  478. {
  479. if (pid == -1)
  480. {
  481. carla_stderr2("Can't wait for pid -1");
  482. return false;
  483. }
  484. pid_t ret;
  485. for (int i=0, maxTime=WAIT_ZOMBIE_TIMEOUT/WAIT_STEP; i < maxTime; ++i)
  486. {
  487. try {
  488. ret = ::waitpid(pid, nullptr, WNOHANG);
  489. }
  490. catch(...) {
  491. break;
  492. }
  493. if (ret != 0)
  494. {
  495. if (ret == pid)
  496. return true;
  497. if (ret == -1)
  498. {
  499. if (errno == ECHILD)
  500. return true;
  501. carla_stderr2("waitpid(%i) failed: %s", int(pid), std::strerror(errno));
  502. return false;
  503. }
  504. carla_stderr2("we waited for child pid %i to exit but we got pid %i instead", int(pid), int(ret));
  505. return false;
  506. }
  507. carla_msleep(WAIT_STEP); /* wait 100 ms */
  508. }
  509. carla_stderr2("we waited for child with pid %i to exit for %.1f seconds and we are giving up", int(pid), float(WAIT_START_TIMEOUT)/1000.0f);
  510. return false;
  511. }
  512. };
  513. // -----------------------------------------------------------------------
  514. #endif // CARLA_PIPE_UTILS_HPP_INCLUDED