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.

619 lines
15KB

  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(int& 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(uint& value)
  249. {
  250. CARLA_SAFE_ASSERT_RETURN(fIsReading, false);
  251. if (const char* const msg = readline())
  252. {
  253. int tmp = std::atoi(msg);
  254. delete[] msg;
  255. if (tmp >= 0)
  256. {
  257. value = static_cast<uint>(tmp);
  258. return true;
  259. }
  260. }
  261. return false;
  262. }
  263. bool readNextLineAsLong(long& 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 readNextLineAsFloat(float& value)
  275. {
  276. CARLA_SAFE_ASSERT_RETURN(fIsReading, false);
  277. if (const char* const msg = readline())
  278. {
  279. const bool ret(std::sscanf(msg, "%f", &value) == 1);
  280. delete[] msg;
  281. return ret;
  282. }
  283. return false;
  284. }
  285. bool readNextLineAsString(const char*& value)
  286. {
  287. CARLA_SAFE_ASSERT_RETURN(fIsReading, false);
  288. if (const char* const msg = readline())
  289. {
  290. value = msg;
  291. return true;
  292. }
  293. return false;
  294. }
  295. // -------------------------------------------------------------------
  296. void writeMsg(const char* const msg) const noexcept
  297. {
  298. CARLA_SAFE_ASSERT_RETURN(fPipeSend != -1,);
  299. try {
  300. ssize_t ignore = ::write(fPipeSend, msg, std::strlen(msg));
  301. (void)ignore;
  302. } catch (...) {}
  303. }
  304. void writeMsg(const char* const msg, size_t size) const noexcept
  305. {
  306. CARLA_SAFE_ASSERT_RETURN(fPipeSend != -1,);
  307. try {
  308. ssize_t ignore = ::write(fPipeSend, msg, size);
  309. (void)ignore;
  310. } catch (...) {}
  311. }
  312. void writeAndFixMsg(const char* const msg)
  313. {
  314. CARLA_SAFE_ASSERT_RETURN(fPipeSend != -1,);
  315. const size_t size(msg != nullptr ? std::strlen(msg) : 0);
  316. char fixedMsg[size+2];
  317. if (size > 0)
  318. {
  319. std::strcpy(fixedMsg, msg);
  320. for (size_t i=0; i < size; ++i)
  321. {
  322. if (fixedMsg[i] == '\n')
  323. fixedMsg[i] = '\r';
  324. }
  325. if (fixedMsg[size+1] == '\r')
  326. {
  327. fixedMsg[size-1] = '\n';
  328. fixedMsg[size] = '\0';
  329. fixedMsg[size+1] = '\0';
  330. }
  331. else
  332. {
  333. fixedMsg[size] = '\n';
  334. fixedMsg[size+1] = '\0';
  335. }
  336. }
  337. else
  338. {
  339. fixedMsg[0] = '\n';
  340. fixedMsg[1] = '\0';
  341. }
  342. try {
  343. ssize_t ignore = ::write(fPipeSend, fixedMsg, size+1);
  344. (void)ignore;
  345. } catch (...) {}
  346. }
  347. void waitChildClose()
  348. {
  349. if (! wait_child(fPid))
  350. {
  351. carla_stderr2("force killing misbehaved child %i (exit)", int(fPid));
  352. if (kill(fPid, SIGKILL) == -1)
  353. carla_stderr2("kill() failed: %s (exit)", strerror(errno));
  354. else
  355. wait_child(fPid);
  356. }
  357. }
  358. // -------------------------------------------------------------------
  359. protected:
  360. virtual void fail(const char* const error)
  361. {
  362. carla_stderr2(error);
  363. }
  364. virtual void msgReceived(const char* const msg) = 0;
  365. // -------------------------------------------------------------------
  366. private:
  367. int fPipeRecv; // the pipe end that is used for receiving messages from UI
  368. int fPipeSend; // the pipe end that is used for sending messages to UI
  369. bool fIsReading;
  370. pid_t fPid;
  371. char fTmpBuf[0xff+1];
  372. CarlaString fTmpStr;
  373. // -------------------------------------------------------------------
  374. const char* readline()
  375. {
  376. char ch;
  377. char* ptr = fTmpBuf;
  378. ssize_t ret;
  379. fTmpStr.clear();
  380. for (int i=0; i < 0xff; ++i)
  381. {
  382. try {
  383. ret = read(fPipeRecv, &ch, 1);
  384. }
  385. catch (...) {
  386. break;
  387. }
  388. if (ret == 1 && ch != '\n')
  389. {
  390. if (ch == '\r')
  391. ch = '\n';
  392. *ptr++ = ch;
  393. if (i+1 == 0xff)
  394. {
  395. i = 0;
  396. ptr = fTmpBuf;
  397. fTmpStr += fTmpBuf;
  398. }
  399. continue;
  400. }
  401. if (fTmpStr.isNotEmpty() || ptr != fTmpBuf)
  402. {
  403. if (ptr != fTmpBuf)
  404. {
  405. *ptr = '\0';
  406. fTmpStr += fTmpBuf;
  407. }
  408. return fTmpStr.dup();
  409. }
  410. break;
  411. }
  412. return nullptr;
  413. }
  414. static bool fork_exec(const char* const argv[5], int* const retp)
  415. {
  416. const pid_t ret = *retp = vfork();
  417. switch (ret)
  418. {
  419. case 0: /* child process */
  420. execlp(argv[0], argv[0], argv[1], argv[2], argv[3], argv[4], nullptr);
  421. carla_stderr2("exec failed: %s", std::strerror(errno));
  422. _exit(0);
  423. return false;
  424. case -1: /* error */
  425. carla_stderr2("fork() failed: %s", std::strerror(errno));
  426. _exit(0);
  427. return false;
  428. }
  429. return true;
  430. }
  431. static bool wait_child(const pid_t pid)
  432. {
  433. if (pid == -1)
  434. {
  435. carla_stderr2("Can't wait for pid -1");
  436. return false;
  437. }
  438. pid_t ret;
  439. for (int i=0, maxTime=WAIT_ZOMBIE_TIMEOUT/WAIT_STEP; i < maxTime; ++i)
  440. {
  441. try {
  442. ret = ::waitpid(pid, nullptr, WNOHANG);
  443. }
  444. catch (...) {
  445. break;
  446. }
  447. if (ret != 0)
  448. {
  449. if (ret == pid)
  450. return true;
  451. if (ret == -1)
  452. {
  453. carla_stderr2("waitpid(%i) failed: %s", int(pid), std::strerror(errno));
  454. return false;
  455. }
  456. carla_stderr2("we waited for child pid %i to exit but we got pid %i instead", int(pid), int(ret));
  457. return false;
  458. }
  459. carla_msleep(WAIT_STEP); /* wait 100 ms */
  460. }
  461. 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);
  462. return false;
  463. }
  464. };
  465. // -----------------------------------------------------------------------
  466. class CarlaPipeClient
  467. {
  468. protected:
  469. CarlaPipeClient()
  470. {
  471. carla_debug("CarlaPipeClient::CarlaPipeClient()");
  472. }
  473. // -------------------------------------------------------------------
  474. public:
  475. virtual ~CarlaPipeClient()
  476. {
  477. carla_debug("CarlaPipeClient::~CarlaPipeClient()");
  478. stop();
  479. }
  480. void stop()
  481. {
  482. }
  483. };
  484. // -----------------------------------------------------------------------
  485. #endif // CARLA_PIPE_UTILS_HPP_INCLUDED