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.

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