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.

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