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.

648 lines
16KB

  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[5];
  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. pipeRecv[100] = '\0';
  91. pipeSend[100] = '\0';
  92. std::snprintf(pipeRecv, 100, "%d", pipe1[0]); // [0] means reading end
  93. std::snprintf(pipeSend, 100, "%d", pipe2[1]); // [1] means writting end
  94. argv[3] = pipeRecv; // reading end
  95. argv[4] = pipeSend; // writting end
  96. //----------------------------------------------------------------
  97. // fork
  98. int ret = -1;
  99. if ((! fork_exec(argv, &ret)) || ret == -1)
  100. {
  101. try {
  102. ::close(pipe1[0]);
  103. ::close(pipe1[1]);
  104. } catch (...) {}
  105. try {
  106. ::close(pipe2[0]);
  107. ::close(pipe2[1]);
  108. } catch (...) {}
  109. fail("fork_exec() failed");
  110. return false;
  111. }
  112. fPid = ret;
  113. // fork duplicated the handles, close pipe ends that are used by the child process
  114. try {
  115. ::close(pipe1[0]);
  116. } catch(...) {}
  117. try {
  118. ::close(pipe2[1]);
  119. } catch(...) {}
  120. fPipeSend = pipe1[1]; // [1] means writting end
  121. fPipeRecv = pipe2[0]; // [0] means reading end
  122. // set non-block
  123. try {
  124. ret = ::fcntl(fPipeRecv, F_SETFL, ::fcntl(fPipeRecv, F_GETFL) | O_NONBLOCK);
  125. } catch (...) {
  126. ret = -1;
  127. fail("failed to set pipe as non-block");
  128. }
  129. //----------------------------------------------------------------
  130. // wait a while for child process to confirm it is alive
  131. if (ret != -1)
  132. {
  133. char ch;
  134. ssize_t ret2;
  135. for (int i=0; ;)
  136. {
  137. try {
  138. ret2 = ::read(fPipeRecv, &ch, 1);
  139. }
  140. catch (...) {
  141. fail("failed to read from pipe");
  142. break;
  143. }
  144. switch (ret2)
  145. {
  146. case -1:
  147. if (errno == EAGAIN)
  148. {
  149. if (i < WAIT_START_TIMEOUT / WAIT_STEP)
  150. {
  151. carla_msleep(WAIT_STEP);
  152. ++i;
  153. continue;
  154. }
  155. 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);
  156. }
  157. else
  158. carla_stderr("read() failed: %s", std::strerror(errno));
  159. break;
  160. case 1:
  161. if (ch == '\n') {
  162. // success
  163. return true;
  164. }
  165. carla_stderr("read() has wrong first char '%c'", ch);
  166. break;
  167. default:
  168. carla_stderr("read() returned %i", int(ret2));
  169. break;
  170. }
  171. break;
  172. }
  173. }
  174. carla_stderr("force killing misbehaved child %i (start)", int(fPid));
  175. if (kill(fPid, SIGKILL) == -1)
  176. {
  177. carla_stderr("kill() failed: %s (start)\n", std::strerror(errno));
  178. }
  179. // wait a while child to exit, we dont like zombie processes
  180. wait_child(fPid);
  181. // close pipes
  182. try {
  183. ::close(fPipeRecv);
  184. } catch (...) {}
  185. try {
  186. ::close(fPipeSend);
  187. } catch (...) {}
  188. fPipeRecv = -1;
  189. fPipeSend = -1;
  190. fPid = -1;
  191. return false;
  192. }
  193. void stop() noexcept
  194. {
  195. carla_debug("CarlaPipeServer::stop()");
  196. if (fPipeSend == -1 || fPipeRecv == -1 || fPid == -1)
  197. return;
  198. const CarlaMutexLocker cml(fWriteLock);
  199. try {
  200. ssize_t ignore = ::write(fPipeSend, "quit\n", 5);
  201. (void)ignore;
  202. } CARLA_SAFE_EXCEPTION("CarlaPipeServer::stop");
  203. waitChildClose();
  204. try {
  205. ::close(fPipeRecv);
  206. } catch (...) {}
  207. try {
  208. ::close(fPipeSend);
  209. } catch (...) {}
  210. fPipeRecv = -1;
  211. fPipeSend = -1;
  212. fPid = -1;
  213. }
  214. void idle()
  215. {
  216. const char* locale = nullptr;
  217. for (;;)
  218. {
  219. const char* const msg(readline());
  220. if (msg == nullptr)
  221. break;
  222. if (locale == nullptr)
  223. {
  224. locale = carla_strdup(setlocale(LC_NUMERIC, nullptr));
  225. setlocale(LC_NUMERIC, "POSIX");
  226. }
  227. fIsReading = true;
  228. msgReceived(msg);
  229. fIsReading = false;
  230. delete[] msg;
  231. }
  232. if (locale != nullptr)
  233. {
  234. setlocale(LC_NUMERIC, locale);
  235. delete[] locale;
  236. }
  237. }
  238. // -------------------------------------------------------------------
  239. bool readNextLineAsBool(bool& value) noexcept
  240. {
  241. CARLA_SAFE_ASSERT_RETURN(fIsReading, false);
  242. if (const char* const msg = readline())
  243. {
  244. value = (std::strcmp(msg, "true") == 0);
  245. delete[] msg;
  246. return true;
  247. }
  248. return false;
  249. }
  250. bool readNextLineAsInt(int32_t& value) noexcept
  251. {
  252. CARLA_SAFE_ASSERT_RETURN(fIsReading, false);
  253. if (const char* const msg = readline())
  254. {
  255. value = std::atoi(msg);
  256. delete[] msg;
  257. return true;
  258. }
  259. return false;
  260. }
  261. bool readNextLineAsUInt(uint32_t& value) noexcept
  262. {
  263. CARLA_SAFE_ASSERT_RETURN(fIsReading, false);
  264. if (const char* const msg = readline())
  265. {
  266. int32_t tmp = std::atoi(msg);
  267. delete[] msg;
  268. if (tmp >= 0)
  269. {
  270. value = static_cast<uint32_t>(tmp);
  271. return true;
  272. }
  273. }
  274. return false;
  275. }
  276. bool readNextLineAsLong(int64_t& value) noexcept
  277. {
  278. CARLA_SAFE_ASSERT_RETURN(fIsReading, false);
  279. if (const char* const msg = readline())
  280. {
  281. value = std::atol(msg);
  282. delete[] msg;
  283. return true;
  284. }
  285. return false;
  286. }
  287. bool readNextLineAsULong(uint64_t& value) noexcept
  288. {
  289. CARLA_SAFE_ASSERT_RETURN(fIsReading, false);
  290. if (const char* const msg = readline())
  291. {
  292. int64_t tmp = std::atol(msg);
  293. delete[] msg;
  294. if (tmp >= 0)
  295. {
  296. value = static_cast<uint64_t>(tmp);
  297. return true;
  298. }
  299. }
  300. return false;
  301. }
  302. bool readNextLineAsFloat(float& value) noexcept
  303. {
  304. CARLA_SAFE_ASSERT_RETURN(fIsReading, false);
  305. if (const char* const msg = readline())
  306. {
  307. const bool ret(std::sscanf(msg, "%f", &value) == 1);
  308. delete[] msg;
  309. return ret;
  310. }
  311. return false;
  312. }
  313. bool readNextLineAsString(const char*& value) noexcept
  314. {
  315. CARLA_SAFE_ASSERT_RETURN(fIsReading, false);
  316. if (const char* const msg = readline())
  317. {
  318. value = msg;
  319. return true;
  320. }
  321. return false;
  322. }
  323. // -------------------------------------------------------------------
  324. void writeMsg(const char* const msg) const noexcept
  325. {
  326. CARLA_SAFE_ASSERT_RETURN(fPipeSend != -1,);
  327. try {
  328. ssize_t ignore = ::write(fPipeSend, msg, std::strlen(msg));
  329. (void)ignore;
  330. } CARLA_SAFE_EXCEPTION("CarlaPipeServer::writeMsg");
  331. }
  332. void writeMsg(const char* const msg, size_t size) const noexcept
  333. {
  334. CARLA_SAFE_ASSERT_RETURN(fPipeSend != -1,);
  335. try {
  336. ssize_t ignore = ::write(fPipeSend, msg, size);
  337. (void)ignore;
  338. } CARLA_SAFE_EXCEPTION("CarlaPipeServer::writeMsg");
  339. }
  340. void writeAndFixMsg(const char* const msg) noexcept
  341. {
  342. CARLA_SAFE_ASSERT_RETURN(fPipeSend != -1,);
  343. const size_t size(msg != nullptr ? std::strlen(msg) : 0);
  344. char fixedMsg[size+2];
  345. if (size > 0)
  346. {
  347. std::strcpy(fixedMsg, msg);
  348. for (size_t i=0; i < size; ++i)
  349. {
  350. if (fixedMsg[i] == '\n')
  351. fixedMsg[i] = '\r';
  352. }
  353. if (fixedMsg[size-1] == '\r')
  354. {
  355. fixedMsg[size-1] = '\n';
  356. fixedMsg[size] = '\0';
  357. fixedMsg[size+1] = '\0';
  358. }
  359. else
  360. {
  361. fixedMsg[size] = '\n';
  362. fixedMsg[size+1] = '\0';
  363. }
  364. }
  365. else
  366. {
  367. fixedMsg[0] = '\n';
  368. fixedMsg[1] = '\0';
  369. }
  370. try {
  371. ssize_t ignore = ::write(fPipeSend, fixedMsg, size+1);
  372. (void)ignore;
  373. } CARLA_SAFE_EXCEPTION("CarlaPipeServer::writeAndFixMsg");
  374. }
  375. void waitChildClose() noexcept
  376. {
  377. if (! wait_child(fPid))
  378. {
  379. carla_stderr2("force killing misbehaved child %i (exit)", int(fPid));
  380. if (kill(fPid, SIGKILL) == -1)
  381. carla_stderr2("kill() failed: %s (exit)", std::strerror(errno));
  382. else
  383. wait_child(fPid);
  384. }
  385. }
  386. // -------------------------------------------------------------------
  387. protected:
  388. // common write lock
  389. CarlaMutex fWriteLock;
  390. // to possibly send errors somewhere
  391. virtual void fail(const char* const error)
  392. {
  393. carla_stderr2(error);
  394. }
  395. // returns true if msg handled
  396. virtual bool msgReceived(const char* const msg) noexcept = 0;
  397. // -------------------------------------------------------------------
  398. private:
  399. int fPipeRecv; // the pipe end that is used for receiving messages from UI
  400. int fPipeSend; // the pipe end that is used for sending messages to UI
  401. bool fIsReading;
  402. pid_t fPid;
  403. char fTmpBuf[0xff+1];
  404. CarlaString fTmpStr;
  405. // -------------------------------------------------------------------
  406. const char* readline() noexcept
  407. {
  408. char ch;
  409. char* ptr = fTmpBuf;
  410. ssize_t ret;
  411. fTmpStr.clear();
  412. for (int i=0; i < 0xff; ++i)
  413. {
  414. try {
  415. ret = ::read(fPipeRecv, &ch, 1);
  416. }
  417. catch (...) {
  418. break;
  419. }
  420. if (ret == 1 && ch != '\n')
  421. {
  422. if (ch == '\r')
  423. ch = '\n';
  424. *ptr++ = ch;
  425. if (i+1 == 0xff)
  426. {
  427. i = 0;
  428. ptr = fTmpBuf;
  429. fTmpStr += fTmpBuf;
  430. }
  431. continue;
  432. }
  433. if (fTmpStr.isNotEmpty() || ptr != fTmpBuf)
  434. {
  435. if (ptr != fTmpBuf)
  436. {
  437. *ptr = '\0';
  438. fTmpStr += fTmpBuf;
  439. }
  440. try {
  441. return fTmpStr.dup();
  442. }
  443. catch(...) {
  444. return nullptr;
  445. }
  446. }
  447. break;
  448. }
  449. return nullptr;
  450. }
  451. // -------------------------------------------------------------------
  452. static bool fork_exec(const char* const argv[5], int* const retp) noexcept
  453. {
  454. const pid_t ret = *retp = vfork();
  455. switch (ret)
  456. {
  457. case 0: // child process
  458. execlp(argv[0], argv[0], argv[1], argv[2], argv[3], argv[4],
  459. #ifdef CARLA_OS_MAC // fix warning
  460. NULL);
  461. #else
  462. nullptr);
  463. #endif
  464. carla_stderr2("exec failed: %s", std::strerror(errno));
  465. _exit(0); // this is not noexcept safe but doesn't matter anyway
  466. return false;
  467. case -1: // error
  468. carla_stderr2("fork() failed: %s", std::strerror(errno));
  469. _exit(0); // this is not noexcept safe but doesn't matter anyway
  470. return false;
  471. }
  472. return true;
  473. }
  474. static bool wait_child(const pid_t pid) noexcept
  475. {
  476. if (pid == -1)
  477. {
  478. carla_stderr2("Can't wait for pid -1");
  479. return false;
  480. }
  481. pid_t ret;
  482. for (int i=0, maxTime=WAIT_ZOMBIE_TIMEOUT/WAIT_STEP; i < maxTime; ++i)
  483. {
  484. try {
  485. ret = ::waitpid(pid, nullptr, WNOHANG);
  486. }
  487. catch(...) {
  488. break;
  489. }
  490. if (ret != 0)
  491. {
  492. if (ret == pid)
  493. return true;
  494. if (ret == -1)
  495. {
  496. if (errno == ECHILD)
  497. return true;
  498. carla_stderr2("waitpid(%i) failed: %s", int(pid), std::strerror(errno));
  499. return false;
  500. }
  501. carla_stderr2("we waited for child pid %i to exit but we got pid %i instead", int(pid), int(ret));
  502. return false;
  503. }
  504. carla_msleep(WAIT_STEP); /* wait 100 ms */
  505. }
  506. 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);
  507. return false;
  508. }
  509. };
  510. // -----------------------------------------------------------------------
  511. #endif // CARLA_PIPE_UTILS_HPP_INCLUDED