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.

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