sys_start_process.c 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221
  1. /**
  2. * @file sys_start_process.c
  3. * @author Ambroz Bizjak <ambrop7@gmail.com>
  4. *
  5. * @section LICENSE
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are met:
  9. * 1. Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * 2. Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * 3. Neither the name of the author nor the
  15. * names of its contributors may be used to endorse or promote products
  16. * derived from this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  19. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  27. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. *
  29. * @section DESCRIPTION
  30. *
  31. * Synopsis:
  32. * sys.start_process(list command, string mode [, map options])
  33. *
  34. * Options:
  35. * "keep_stdout":"true" - Start the program with the same stdout as the NCD process.
  36. * Must not be present if the process is being opened for reading.
  37. * "keep_stderr":true" - Start the program with the same stderr as the NCD process.
  38. * "do_setsid":"true" - Call setsid() in the child before exec. This is needed to
  39. * start the 'agetty' program.
  40. * "username":username_string - Start the process under the permissions of the
  41. * specified user.
  42. * "term_on_deinit":"false" - do not send SIGTERM to the process when this statement
  43. * is requested to terminate
  44. *
  45. * Variables:
  46. * is_error - "true" if there was an error starting the process, "false" if the process
  47. * has been started successfully
  48. *
  49. * Synopsis:
  50. * sys.start_process::wait()
  51. *
  52. * Variables:
  53. * exit_status - the exit code if the process terminated normally, -1 if it terminated
  54. * with a signal
  55. *
  56. * Synopsis:
  57. * sys.start_process::terminate()
  58. * sys.start_process::kill()
  59. *
  60. * Synopsis:
  61. * sys.start_process::read_pipe()
  62. *
  63. * Description:
  64. * Creates a read interface to the process's standard output. Data is read using the
  65. * read() method on this object. Read errors are reported implicitly by this statement
  66. * going down and the 'is_error' variable changing to "true".
  67. * When read_pipe() is initialized for a process, it takes ownership of the read pipe
  68. * to the process. When read_pipe() is requested to terminate, it will close the pipe.
  69. * Attempting to initialize read_pipe() on a process which was not started with 'r'
  70. * in the mode argument, or where another read_pipe() object has already taken ownership
  71. * of the read pipe, will result in throwing an error to the interpreter.
  72. *
  73. * Variables:
  74. * string is_error - "true" if there was a read error, "false" if not
  75. *
  76. * Synopsis:
  77. * sys.start_process::read_pipe::read()
  78. *
  79. * Description:
  80. * Reads some data. If a read error occurs, it is reported implicitly via the
  81. * read_pipe() object going down. If end of file is reached, this and any future read()
  82. * operations will indicate that via the 'not_eof' variable. It is guaranteed that after
  83. * EOF is reached, the read_pipe() object will not go down to report any errors.
  84. * WARNING: if a read() is requested to terminate before it has completed, the
  85. * read_pipe() will become unusable and any read() invocation after that will
  86. * throw an error to the interpreter.
  87. *
  88. * Variables:
  89. * string (empty) - data that was read, or an empty string on EOF
  90. * string not_eof - "true" is EOF was not reached, "false" if it was
  91. *
  92. * Synopsis:
  93. * sys.start_process::write_pipe()
  94. *
  95. * Description:
  96. * Creates a write interface to the process's standard input. Data is written using the
  97. * write() method on this object. Write errors are reported implicitly by this statement
  98. * going down and the ''is_error variable changing to "true".
  99. * When write_pipe() is initialized for a process, it takes ownership of the write pipe
  100. * to the process. When write_pipe() is requested to terminate, it will close the pipe
  101. * (unless the close() has been used).
  102. * Attempting to initialize write_pipe() on a process which was not started with 'w'
  103. * in the mode argument, or where another write_pipe() object has already taken ownership
  104. * of the write pope, will result in throwing an error to the interpreter.
  105. *
  106. * Variables:
  107. * string is_error - "true" if there was a write error, "false" if not
  108. *
  109. * Synopsis:
  110. * sys.start_process::write_pipe::write(string data)
  111. *
  112. * Description:
  113. * Writes the given data. If a write error occurs, it is reported implicitly via the
  114. * write_pipe() object going down.
  115. * WARNING: if a write() is requested to terminate before it has completed, the
  116. * write_pipe() will become unusable and any write() or close() invocation after
  117. * that will throw an error to the interpreter.
  118. *
  119. * Synopsis:
  120. * sys.start_process::write_pipe::close(string data)
  121. *
  122. * Description:
  123. * Closes the write pipe. This will make whatever is reading the other end of the pipe
  124. * encounter EOF after it has read any pending data. It is guaranteed that after the
  125. * pipe is closed, the write_pipe() object will not go down to report any errors.
  126. * After close() is performed, any further write() or close() calls are disallowed and
  127. * will throw errors to the interpreter.
  128. */
  129. #include <stdlib.h>
  130. #include <string.h>
  131. #include <stdio.h>
  132. #include <inttypes.h>
  133. #include <limits.h>
  134. #include <unistd.h>
  135. #include <misc/offset.h>
  136. #include <structure/LinkedList0.h>
  137. #include <system/BProcess.h>
  138. #include <system/BConnection.h>
  139. #include <ncd/NCDModule.h>
  140. #include <ncd/static_strings.h>
  141. #include <ncd/extra/NCDBuf.h>
  142. #include <ncd/extra/value_utils.h>
  143. #include <ncd/extra/build_cmdline.h>
  144. #include <ncd/extra/NCDBProcessOpts.h>
  145. #include <generated/blog_channel_ncd_sys_start_process.h>
  146. #define ModuleLog(i, ...) NCDModuleInst_Backend_Log((i), BLOG_CURRENT_CHANNEL, __VA_ARGS__)
  147. #define READ_BUF_SIZE 8192
  148. #define PROCESS_STATE_ERROR 1
  149. #define PROCESS_STATE_RUNNING 2
  150. #define PROCESS_STATE_TERMINATED 3
  151. #define PROCESS_STATE_DYING 4
  152. #define READER_STATE_RUNNING 1
  153. #define READER_STATE_EOF 2
  154. #define READER_STATE_ERROR 3
  155. #define READER_STATE_ABORTED 4
  156. #define WRITER_STATE_RUNNING 1
  157. #define WRITER_STATE_CLOSED 2
  158. #define WRITER_STATE_ERROR 3
  159. #define WRITER_STATE_ABORTED 4
  160. struct process_instance {
  161. NCDModuleInst *i;
  162. BProcess process;
  163. LinkedList0 waits_list;
  164. int term_on_deinit;
  165. int read_fd;
  166. int write_fd;
  167. int exit_status;
  168. int state;
  169. };
  170. struct wait_instance {
  171. NCDModuleInst *i;
  172. struct process_instance *pinst;
  173. LinkedList0Node waits_list_node;
  174. int exit_status;
  175. };
  176. struct read_pipe_instance {
  177. NCDModuleInst *i;
  178. int state;
  179. int read_fd;
  180. BConnection connection;
  181. NCDBufStore store;
  182. struct read_instance *read_inst;
  183. };
  184. struct read_instance {
  185. NCDModuleInst *i;
  186. struct read_pipe_instance *read_pipe_inst;
  187. NCDBuf *buf;
  188. size_t read_size;
  189. };
  190. struct write_pipe_instance {
  191. NCDModuleInst *i;
  192. int state;
  193. int write_fd;
  194. BConnection connection;
  195. struct write_instance *write_inst;
  196. };
  197. struct write_instance {
  198. NCDModuleInst *i;
  199. struct write_pipe_instance *write_pipe_inst;
  200. b_cstring cstr;
  201. size_t pos;
  202. };
  203. static int parse_mode (NCDModuleInst *i, NCDValRef mode_arg, int *out_read, int *out_write)
  204. {
  205. if (!NCDVal_IsString(mode_arg)) {
  206. ModuleLog(i, BLOG_ERROR, "mode argument must be a string");
  207. return 0;
  208. }
  209. *out_read = 0;
  210. *out_write = 0;
  211. b_cstring cstr = NCDVal_StringCstring(mode_arg);
  212. B_CSTRING_LOOP_CHARS(cstr, char_pos, ch, {
  213. if (ch == 'r') {
  214. *out_read = 1;
  215. }
  216. else if (ch == 'w') {
  217. *out_write = 1;
  218. }
  219. else {
  220. ModuleLog(i, BLOG_ERROR, "invalid character in mode argument");
  221. return 0;
  222. }
  223. })
  224. return 1;
  225. }
  226. static void process_free (struct process_instance *o)
  227. {
  228. // close write fd
  229. if (o->write_fd != -1) {
  230. if (close(o->write_fd) < 0) {
  231. ModuleLog(o->i, BLOG_ERROR, "close failed");
  232. }
  233. }
  234. // close read fd
  235. if (o->read_fd != -1) {
  236. if (close(o->read_fd) < 0) {
  237. ModuleLog(o->i, BLOG_ERROR, "close failed");
  238. }
  239. }
  240. NCDModuleInst_Backend_Dead(o->i);
  241. }
  242. static void process_handler (void *vo, int normally, uint8_t normally_exit_status)
  243. {
  244. struct process_instance *o = vo;
  245. ASSERT(o->state == PROCESS_STATE_RUNNING || o->state == PROCESS_STATE_DYING)
  246. ModuleLog(o->i, BLOG_INFO, "process terminated");
  247. // free process
  248. BProcess_Free(&o->process);
  249. // remember exit code
  250. o->exit_status = (!normally ? -1 : normally_exit_status);
  251. // finish waits
  252. LinkedList0Node *ln;
  253. while ((ln = LinkedList0_GetFirst(&o->waits_list))) {
  254. struct wait_instance *winst = UPPER_OBJECT(ln, struct wait_instance, waits_list_node);
  255. ASSERT(winst->pinst == o)
  256. LinkedList0_Remove(&o->waits_list, &winst->waits_list_node);
  257. winst->pinst = NULL;
  258. winst->exit_status = o->exit_status;
  259. NCDModuleInst_Backend_Up(winst->i);
  260. }
  261. // if we have been requested to die, then die now
  262. if (o->state == PROCESS_STATE_DYING) {
  263. process_free(o);
  264. return;
  265. }
  266. // set state
  267. o->state = PROCESS_STATE_TERMINATED;
  268. }
  269. static int opts_func_unknown (void *user, NCDValRef key, NCDValRef val)
  270. {
  271. struct process_instance *o = user;
  272. if (NCDVal_IsString(key) && NCDVal_StringEquals(key, "term_on_deinit")) {
  273. o->term_on_deinit = ncd_read_boolean(val);
  274. return 1;
  275. }
  276. return 0;
  277. }
  278. static void process_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  279. {
  280. struct process_instance *o = vo;
  281. o->i = i;
  282. NCDModuleInst_Backend_PassMemToMethods(i);
  283. // check arguments
  284. NCDValRef command_arg;
  285. NCDValRef mode_arg;
  286. NCDValRef options_arg = NCDVal_NewInvalid();
  287. if (!NCDVal_ListRead(params->args, 2, &command_arg, &mode_arg) &&
  288. !NCDVal_ListRead(params->args, 3, &command_arg, &mode_arg, &options_arg)
  289. ) {
  290. ModuleLog(i, BLOG_ERROR, "wrong arity");
  291. goto fail0;
  292. }
  293. // parse mode
  294. int is_read;
  295. int is_write;
  296. if (!parse_mode(i, mode_arg, &is_read, &is_write)) {
  297. goto fail0;
  298. }
  299. // parse options
  300. NCDBProcessOpts opts;
  301. int keep_stdout;
  302. int keep_stderr;
  303. o->term_on_deinit = 1;
  304. if (!NCDBProcessOpts_Init2(&opts, options_arg, opts_func_unknown, o, i, BLOG_CURRENT_CHANNEL, &keep_stdout, &keep_stderr)) {
  305. goto fail0;
  306. }
  307. // keep-stdout option and read mode are not compatible
  308. if (keep_stdout && is_read) {
  309. ModuleLog(i, BLOG_ERROR, "keep-stdout and read mode are not compatible");
  310. goto fail1;
  311. }
  312. // prepare for creating pipes
  313. int fds[4];
  314. int fds_map[3];
  315. int start_num_fds = opts.nfds;
  316. int num_fds = start_num_fds;
  317. memcpy(fds, opts.fds, num_fds * sizeof(int));
  318. memcpy(fds_map, opts.fds_map, num_fds * sizeof(int));
  319. int read_fd = -1;
  320. int write_fd = -1;
  321. // create read pipe
  322. if (is_read) {
  323. int pipefd[2];
  324. if (pipe(pipefd) < 0) {
  325. ModuleLog(i, BLOG_ERROR, "pipe failed");
  326. goto error1;
  327. }
  328. read_fd = pipefd[0];
  329. fds[num_fds] = pipefd[1];
  330. fds_map[num_fds++] = STDOUT_FILENO;
  331. }
  332. // create write pipe
  333. if (is_write) {
  334. int pipefd[2];
  335. if (pipe(pipefd) < 0) {
  336. ModuleLog(i, BLOG_ERROR, "pipe failed");
  337. goto error1;
  338. }
  339. write_fd = pipefd[1];
  340. fds[num_fds] = pipefd[0];
  341. fds_map[num_fds++] = STDIN_FILENO;
  342. }
  343. // terminate fds array
  344. fds[num_fds] = -1;
  345. // build process parameters struct
  346. struct BProcess_params p_params = {};
  347. p_params.fds = fds;
  348. p_params.fds_map = fds_map;
  349. p_params.do_setsid = opts.do_setsid;
  350. p_params.username = opts.username;
  351. // build command line
  352. char *exec;
  353. CmdLine cl;
  354. if (!ncd_build_cmdline(i, BLOG_CURRENT_CHANNEL, command_arg, &exec, &cl)) {
  355. goto error1;
  356. }
  357. // start process
  358. int res = BProcess_Init2(&o->process, i->params->iparams->manager, process_handler, o, exec, CmdLine_Get(&cl), p_params);
  359. CmdLine_Free(&cl);
  360. free(exec);
  361. if (!res) {
  362. ModuleLog(i, BLOG_ERROR, "BProcess_Init failed");
  363. goto error1;
  364. }
  365. // close child fds
  366. while (num_fds-- > start_num_fds) {
  367. if (close(fds[num_fds]) < 0) {
  368. ModuleLog(i, BLOG_ERROR, "close failed");
  369. }
  370. }
  371. // free opts
  372. NCDBProcessOpts_Free(&opts);
  373. // init waits list
  374. LinkedList0_Init(&o->waits_list);
  375. // remember our fds
  376. o->read_fd = read_fd;
  377. o->write_fd = write_fd;
  378. // set state
  379. o->state = PROCESS_STATE_RUNNING;
  380. // go up
  381. NCDModuleInst_Backend_Up(i);
  382. return;
  383. fail1:
  384. NCDBProcessOpts_Free(&opts);
  385. fail0:
  386. NCDModuleInst_Backend_DeadError(i);
  387. return;
  388. error1:
  389. if (write_fd != -1) {
  390. if (close(write_fd) < 0) {
  391. ModuleLog(i, BLOG_ERROR, "close failed");
  392. }
  393. }
  394. if (read_fd != -1) {
  395. if (close(read_fd) < 0) {
  396. ModuleLog(i, BLOG_ERROR, "close failed");
  397. }
  398. }
  399. while (num_fds-- > start_num_fds) {
  400. if (close(fds[num_fds]) < 0) {
  401. ModuleLog(i, BLOG_ERROR, "close failed");
  402. }
  403. }
  404. NCDBProcessOpts_Free(&opts);
  405. o->read_fd = -1;
  406. o->write_fd = -1;
  407. o->state = PROCESS_STATE_ERROR;
  408. NCDModuleInst_Backend_Up(i);
  409. }
  410. static void process_func_die (void *vo)
  411. {
  412. struct process_instance *o = vo;
  413. ASSERT(o->state != PROCESS_STATE_DYING)
  414. // if process is not running, die immediately
  415. if (o->state != PROCESS_STATE_RUNNING) {
  416. process_free(o);
  417. return;
  418. }
  419. if (o->term_on_deinit) {
  420. ModuleLog(o->i, BLOG_INFO, "terminating process");
  421. // send termination signal
  422. BProcess_Terminate(&o->process);
  423. } else {
  424. ModuleLog(o->i, BLOG_INFO, "not terminating process as requested");
  425. }
  426. // set state
  427. o->state = PROCESS_STATE_DYING;
  428. }
  429. static int process_func_getvar (void *vo, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  430. {
  431. struct process_instance *o = vo;
  432. if (name == NCD_STRING_IS_ERROR) {
  433. int is_error = (o->state == PROCESS_STATE_ERROR);
  434. *out = ncd_make_boolean(mem, is_error, o->i->params->iparams->string_index);
  435. return 1;
  436. }
  437. return 0;
  438. }
  439. static void wait_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  440. {
  441. struct wait_instance *o = vo;
  442. o->i = i;
  443. if (!NCDVal_ListRead(params->args, 0)) {
  444. ModuleLog(i, BLOG_ERROR, "wrong arity");
  445. goto fail0;
  446. }
  447. struct process_instance *pinst = params->method_user;
  448. if (pinst->state == PROCESS_STATE_ERROR) {
  449. ModuleLog(i, BLOG_ERROR, "wait() is disallowed after the process has failed to start");
  450. goto fail0;
  451. }
  452. if (pinst->state == PROCESS_STATE_TERMINATED) {
  453. // not waiting, set no pinst
  454. o->pinst = NULL;
  455. // remember exit code
  456. o->exit_status = pinst->exit_status;
  457. // go up
  458. NCDModuleInst_Backend_Up(i);
  459. } else {
  460. // waitint, set pinst
  461. o->pinst = pinst;
  462. // insert to waits list
  463. LinkedList0_Prepend(&pinst->waits_list, &o->waits_list_node);
  464. }
  465. return;
  466. fail0:
  467. NCDModuleInst_Backend_DeadError(i);
  468. }
  469. static void wait_func_die (void *vo)
  470. {
  471. struct wait_instance *o = vo;
  472. // remove from waits list
  473. if (o->pinst) {
  474. LinkedList0_Remove(&o->pinst->waits_list, &o->waits_list_node);
  475. }
  476. NCDModuleInst_Backend_Dead(o->i);
  477. }
  478. static int wait_func_getvar (void *vo, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  479. {
  480. struct wait_instance *o = vo;
  481. ASSERT(!o->pinst)
  482. if (name == NCD_STRING_EXIT_STATUS) {
  483. if (o->exit_status == -1) {
  484. *out = NCDVal_NewString(mem, "-1");
  485. } else {
  486. *out = ncd_make_uintmax(mem, o->exit_status);
  487. }
  488. return 1;
  489. }
  490. return 0;
  491. }
  492. static void terminate_kill_new_common (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params, int is_kill)
  493. {
  494. if (!NCDVal_ListRead(params->args, 0)) {
  495. ModuleLog(i, BLOG_ERROR, "wrong arity");
  496. goto fail0;
  497. }
  498. struct process_instance *pinst = params->method_user;
  499. if (pinst->state == PROCESS_STATE_ERROR) {
  500. ModuleLog(i, BLOG_ERROR, "terminate()/kill() is disallowed after the process has failed to start");
  501. goto fail0;
  502. }
  503. if (pinst->state != PROCESS_STATE_TERMINATED) {
  504. if (is_kill) {
  505. BProcess_Kill(&pinst->process);
  506. } else {
  507. BProcess_Terminate(&pinst->process);
  508. }
  509. }
  510. NCDModuleInst_Backend_Up(i);
  511. return;
  512. fail0:
  513. NCDModuleInst_Backend_DeadError(i);
  514. }
  515. static void terminate_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  516. {
  517. terminate_kill_new_common(vo, i, params, 0);
  518. }
  519. static void kill_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  520. {
  521. terminate_kill_new_common(vo, i, params, 1);
  522. }
  523. static void read_pipe_free_connection (struct read_pipe_instance *o)
  524. {
  525. // disconnect read instance
  526. if (o->read_inst) {
  527. ASSERT(o->read_inst->read_pipe_inst == o)
  528. o->read_inst->read_pipe_inst = NULL;
  529. }
  530. // free store
  531. NCDBufStore_Free(&o->store);
  532. // free connection read interface
  533. BConnection_RecvAsync_Free(&o->connection);
  534. // free connection
  535. BConnection_Free(&o->connection);
  536. // close fd
  537. if (close(o->read_fd) < 0) {
  538. ModuleLog(o->i, BLOG_ERROR, "close failed");
  539. }
  540. }
  541. static void read_pipe_abort (struct read_pipe_instance *o)
  542. {
  543. ASSERT(o->state == READER_STATE_RUNNING)
  544. // release connection resources
  545. read_pipe_free_connection(o);
  546. // set state
  547. o->state = READER_STATE_ABORTED;
  548. }
  549. static void read_pipe_connection_handler (void *vo, int event)
  550. {
  551. struct read_pipe_instance *o = vo;
  552. ASSERT(o->state == READER_STATE_RUNNING)
  553. if (event == BCONNECTION_EVENT_RECVCLOSED) {
  554. // if we have read operation, make it finish with eof
  555. if (o->read_inst) {
  556. ASSERT(o->read_inst->read_pipe_inst == o)
  557. ASSERT(o->read_inst->buf)
  558. o->read_inst->read_pipe_inst = NULL;
  559. o->read_inst->read_size = 0;
  560. NCDModuleInst_Backend_Up(o->read_inst->i);
  561. o->read_inst = NULL;
  562. }
  563. // free connection resources
  564. read_pipe_free_connection(o);
  565. // set state closed
  566. o->state = READER_STATE_EOF;
  567. return;
  568. }
  569. ModuleLog(o->i, BLOG_ERROR, "read pipe error");
  570. // free connection resources
  571. read_pipe_free_connection(o);
  572. // set state error
  573. o->state = READER_STATE_ERROR;
  574. // backtrack
  575. NCDModuleInst_Backend_DownUp(o->i);
  576. }
  577. static void read_pipe_recv_handler_done (void *vo, int data_len)
  578. {
  579. struct read_pipe_instance *o = vo;
  580. ASSERT(o->state == READER_STATE_RUNNING)
  581. ASSERT(o->read_inst)
  582. ASSERT(o->read_inst->read_pipe_inst == o)
  583. ASSERT(o->read_inst->buf)
  584. ASSERT(data_len > 0)
  585. ASSERT(data_len <= NCDBufStore_BufSize(&o->store))
  586. // finish read operation
  587. o->read_inst->read_pipe_inst = NULL;
  588. o->read_inst->read_size = data_len;
  589. NCDModuleInst_Backend_Up(o->read_inst->i);
  590. o->read_inst = NULL;
  591. }
  592. static void read_pipe_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  593. {
  594. struct read_pipe_instance *o = vo;
  595. o->i = i;
  596. NCDModuleInst_Backend_PassMemToMethods(i);
  597. if (!NCDVal_ListRead(params->args, 0)) {
  598. ModuleLog(i, BLOG_ERROR, "wrong arity");
  599. goto fail0;
  600. }
  601. struct process_instance *pinst = params->method_user;
  602. if (pinst->read_fd == -1) {
  603. ModuleLog(i, BLOG_ERROR, "process did not start successfully, was not opened for reading or a read_pipe was already created");
  604. goto fail0;
  605. }
  606. // init connection
  607. if (!BConnection_Init(&o->connection, BConnection_source_pipe(pinst->read_fd), i->params->iparams->reactor, o, read_pipe_connection_handler)) {
  608. ModuleLog(i, BLOG_ERROR, "BConnection_Init failed");
  609. goto fail0;
  610. }
  611. // init connection read interface
  612. BConnection_RecvAsync_Init(&o->connection);
  613. // set recv done callback
  614. StreamRecvInterface_Receiver_Init(BConnection_RecvAsync_GetIf(&o->connection), read_pipe_recv_handler_done, o);
  615. // init store
  616. NCDBufStore_Init(&o->store, READ_BUF_SIZE);
  617. // set variables
  618. o->state = READER_STATE_RUNNING;
  619. o->read_fd = pinst->read_fd;
  620. o->read_inst = NULL;
  621. // steal read fd from process instance
  622. pinst->read_fd = -1;
  623. // go up
  624. NCDModuleInst_Backend_Up(i);
  625. return;
  626. fail0:
  627. NCDModuleInst_Backend_DeadError(i);
  628. }
  629. static void read_pipe_func_die (void *vo)
  630. {
  631. struct read_pipe_instance *o = vo;
  632. // free connection resources
  633. if (o->state == READER_STATE_RUNNING) {
  634. read_pipe_free_connection(o);
  635. }
  636. NCDModuleInst_Backend_Dead(o->i);
  637. }
  638. static int read_pipe_func_getvar (void *vo, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  639. {
  640. struct read_pipe_instance *o = vo;
  641. if (name == NCD_STRING_IS_ERROR) {
  642. int is_error = (o->state == READER_STATE_ERROR);
  643. *out = ncd_make_boolean(mem, is_error, o->i->params->iparams->string_index);
  644. return 1;
  645. }
  646. return 0;
  647. }
  648. static void read_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  649. {
  650. struct read_instance *o = vo;
  651. o->i = i;
  652. if (!NCDVal_ListRead(params->args, 0)) {
  653. ModuleLog(i, BLOG_ERROR, "wrong arity");
  654. goto fail0;
  655. }
  656. struct read_pipe_instance *read_pipe_inst = params->method_user;
  657. // check if a read error has already occured
  658. if (read_pipe_inst->state == READER_STATE_ERROR) {
  659. ModuleLog(i, BLOG_ERROR, "read() is disallowed after a read error has occured");
  660. goto fail0;
  661. }
  662. // check if the read_pipe has been aborted
  663. if (read_pipe_inst->state == READER_STATE_ABORTED) {
  664. ModuleLog(i, BLOG_ERROR, "read() is disallowed after a read() has been aborted");
  665. goto fail0;
  666. }
  667. // if EOF has already been encountered, complete the read immediately
  668. if (read_pipe_inst->state == READER_STATE_EOF) {
  669. o->buf = NULL;
  670. o->read_pipe_inst = NULL;
  671. o->read_size = 0;
  672. NCDModuleInst_Backend_Up(i);
  673. return;
  674. }
  675. ASSERT(read_pipe_inst->state == READER_STATE_RUNNING)
  676. // check if there's already a read in progress
  677. if (read_pipe_inst->read_inst) {
  678. ModuleLog(i, BLOG_ERROR, "read() is disallowed while another read() is in progress");
  679. goto fail0;
  680. }
  681. // get buffer
  682. o->buf = NCDBufStore_GetBuf(&read_pipe_inst->store);
  683. if (!o->buf) {
  684. ModuleLog(i, BLOG_ERROR, "NCDBufStore_GetBuf failed");
  685. goto fail0;
  686. }
  687. // set read_pipe
  688. o->read_pipe_inst = read_pipe_inst;
  689. // register read in read_pipe
  690. read_pipe_inst->read_inst = o;
  691. // receive
  692. size_t buf_size = NCDBufStore_BufSize(&read_pipe_inst->store);
  693. int to_read = (buf_size > INT_MAX ? INT_MAX : buf_size);
  694. StreamRecvInterface_Receiver_Recv(BConnection_RecvAsync_GetIf(&read_pipe_inst->connection), (uint8_t *)NCDBuf_Data(o->buf), to_read);
  695. return;
  696. fail0:
  697. NCDModuleInst_Backend_DeadError(i);
  698. }
  699. static void read_func_die (void *vo)
  700. {
  701. struct read_instance *o = vo;
  702. // if we're receiving, abort read_pipe
  703. if (o->read_pipe_inst) {
  704. ASSERT(o->read_pipe_inst->state == READER_STATE_RUNNING)
  705. ASSERT(o->read_pipe_inst->read_inst == o)
  706. ASSERT(o->buf)
  707. read_pipe_abort(o->read_pipe_inst);
  708. }
  709. // release buffer
  710. if (o->buf) {
  711. NCDRefTarget_Deref(NCDBuf_RefTarget(o->buf));
  712. }
  713. NCDModuleInst_Backend_Dead(o->i);
  714. }
  715. static int read_func_getvar (void *vo, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  716. {
  717. struct read_instance *o = vo;
  718. ASSERT(!o->read_pipe_inst)
  719. ASSERT(!(o->read_size > 0) || o->buf)
  720. if (name == NCD_STRING_EMPTY) {
  721. if (o->read_size > 0) {
  722. *out = NCDVal_NewExternalString(mem, NCDBuf_Data(o->buf), o->read_size, NCDBuf_RefTarget(o->buf));
  723. } else {
  724. *out = NCDVal_NewIdString(mem, NCD_STRING_EMPTY, o->i->params->iparams->string_index);
  725. }
  726. return 1;
  727. }
  728. if (name == NCD_STRING_NOT_EOF) {
  729. int not_eof = (o->read_size > 0);
  730. *out = ncd_make_boolean(mem, not_eof, o->i->params->iparams->string_index);
  731. return 1;
  732. }
  733. return 0;
  734. }
  735. static void write_pipe_free_connection (struct write_pipe_instance *o)
  736. {
  737. // disconnect write instance
  738. if (o->write_inst) {
  739. ASSERT(o->write_inst->write_pipe_inst == o)
  740. o->write_inst->write_pipe_inst = NULL;
  741. }
  742. // free connection send interface
  743. BConnection_SendAsync_Free(&o->connection);
  744. // free connection
  745. BConnection_Free(&o->connection);
  746. // close fd
  747. if (close(o->write_fd) < 0) {
  748. ModuleLog(o->i, BLOG_ERROR, "close failed");
  749. }
  750. }
  751. static void write_pipe_abort (struct write_pipe_instance *o)
  752. {
  753. ASSERT(o->state == WRITER_STATE_RUNNING)
  754. // release connection resources
  755. write_pipe_free_connection(o);
  756. // set state
  757. o->state = WRITER_STATE_ABORTED;
  758. }
  759. static void write_pipe_close (struct write_pipe_instance *o)
  760. {
  761. ASSERT(o->state == WRITER_STATE_RUNNING)
  762. // release connection resources
  763. write_pipe_free_connection(o);
  764. // set state
  765. o->state = WRITER_STATE_CLOSED;
  766. }
  767. static void write_pipe_connection_handler (void *vo, int event)
  768. {
  769. struct write_pipe_instance *o = vo;
  770. ASSERT(o->state == WRITER_STATE_RUNNING)
  771. ModuleLog(o->i, BLOG_ERROR, "write pipe error");
  772. // free connection resources
  773. write_pipe_free_connection(o);
  774. // set state error
  775. o->state = WRITER_STATE_ERROR;
  776. // backtrack
  777. NCDModuleInst_Backend_DownUp(o->i);
  778. }
  779. static void write_pipe_send_handler_done (void *vo, int data_len)
  780. {
  781. struct write_pipe_instance *o = vo;
  782. ASSERT(o->state == WRITER_STATE_RUNNING)
  783. ASSERT(o->write_inst)
  784. ASSERT(o->write_inst->write_pipe_inst == o)
  785. ASSERT(data_len > 0)
  786. ASSERT(data_len <= o->write_inst->cstr.length - o->write_inst->pos)
  787. struct write_instance *wr = o->write_inst;
  788. // update write progress
  789. wr->pos += data_len;
  790. // if there is more data, start another write operation
  791. if (wr->pos < wr->cstr.length) {
  792. size_t chunk_length;
  793. const char *chunk_data = b_cstring_get(wr->cstr, wr->pos, wr->cstr.length - wr->pos, &chunk_length);
  794. size_t to_send = (chunk_length > INT_MAX ? INT_MAX : chunk_length);
  795. StreamPassInterface_Sender_Send(BConnection_SendAsync_GetIf(&o->connection), (uint8_t *)chunk_data, to_send);
  796. return;
  797. }
  798. // finish write operation
  799. wr->write_pipe_inst = NULL;
  800. NCDModuleInst_Backend_Up(wr->i);
  801. o->write_inst = NULL;
  802. }
  803. static void write_pipe_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  804. {
  805. struct write_pipe_instance *o = vo;
  806. o->i = i;
  807. NCDModuleInst_Backend_PassMemToMethods(i);
  808. if (!NCDVal_ListRead(params->args, 0)) {
  809. ModuleLog(i, BLOG_ERROR, "wrong arity");
  810. goto fail0;
  811. }
  812. struct process_instance *pinst = params->method_user;
  813. if (pinst->write_fd == -1) {
  814. ModuleLog(i, BLOG_ERROR, "process did not start successfully, was not opened for writing or a write_pipe was already created");
  815. goto fail0;
  816. }
  817. // init connection
  818. if (!BConnection_Init(&o->connection, BConnection_source_pipe(pinst->write_fd), i->params->iparams->reactor, o, write_pipe_connection_handler)) {
  819. ModuleLog(i, BLOG_ERROR, "BConnection_Init failed");
  820. goto fail0;
  821. }
  822. // init connection send interface
  823. BConnection_SendAsync_Init(&o->connection);
  824. // set send done callback
  825. StreamPassInterface_Sender_Init(BConnection_SendAsync_GetIf(&o->connection), write_pipe_send_handler_done, o);
  826. // set variables
  827. o->state = WRITER_STATE_RUNNING;
  828. o->write_fd = pinst->write_fd;
  829. o->write_inst = NULL;
  830. // steal write fd from process instance
  831. pinst->write_fd = -1;
  832. // go up
  833. NCDModuleInst_Backend_Up(i);
  834. return;
  835. fail0:
  836. NCDModuleInst_Backend_DeadError(i);
  837. }
  838. static void write_pipe_func_die (void *vo)
  839. {
  840. struct write_pipe_instance *o = vo;
  841. // free connection resources
  842. if (o->state == WRITER_STATE_RUNNING) {
  843. write_pipe_free_connection(o);
  844. }
  845. NCDModuleInst_Backend_Dead(o->i);
  846. }
  847. static int write_pipe_func_getvar (void *vo, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  848. {
  849. struct write_pipe_instance *o = vo;
  850. if (name == NCD_STRING_IS_ERROR) {
  851. int is_error = (o->state == WRITER_STATE_ERROR);
  852. *out = ncd_make_boolean(mem, is_error, o->i->params->iparams->string_index);
  853. return 1;
  854. }
  855. return 0;
  856. }
  857. static void write_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  858. {
  859. struct write_instance *o = vo;
  860. o->i = i;
  861. NCDValRef data_arg;
  862. if (!NCDVal_ListRead(params->args, 1, &data_arg)) {
  863. ModuleLog(i, BLOG_ERROR, "wrong arity");
  864. goto fail0;
  865. }
  866. if (!NCDVal_IsString(data_arg)) {
  867. ModuleLog(i, BLOG_ERROR, "wrong type");
  868. goto fail0;
  869. }
  870. struct write_pipe_instance *write_pipe_inst = params->method_user;
  871. // check if a write error has already occured
  872. if (write_pipe_inst->state == WRITER_STATE_ERROR) {
  873. ModuleLog(i, BLOG_ERROR, "write() is disallowed after a write error has occured");
  874. goto fail0;
  875. }
  876. // check if the write_pipe has been aborted
  877. if (write_pipe_inst->state == WRITER_STATE_ABORTED) {
  878. ModuleLog(i, BLOG_ERROR, "write() is disallowed after a write() has been aborted");
  879. goto fail0;
  880. }
  881. // check if the write_pipe has been aborted
  882. if (write_pipe_inst->state == WRITER_STATE_CLOSED) {
  883. ModuleLog(i, BLOG_ERROR, "write() is disallowed after close() has been called");
  884. goto fail0;
  885. }
  886. ASSERT(write_pipe_inst->state == WRITER_STATE_RUNNING)
  887. // check if there's already a write in progress
  888. if (write_pipe_inst->write_inst) {
  889. ModuleLog(i, BLOG_ERROR, "write() is disallowed while another write() is in progress");
  890. goto fail0;
  891. }
  892. // initialize write progress state
  893. o->cstr = NCDVal_StringCstring(data_arg);
  894. o->pos = 0;
  895. // if there's nothing to send, go up immediately
  896. if (o->cstr.length == 0) {
  897. o->write_pipe_inst = NULL;
  898. NCDModuleInst_Backend_Up(i);
  899. return;
  900. }
  901. // set write_pipe
  902. o->write_pipe_inst = write_pipe_inst;
  903. // register write in write_pipe
  904. write_pipe_inst->write_inst = o;
  905. // start send operation
  906. size_t chunk_length;
  907. const char *chunk_data = b_cstring_get(o->cstr, o->pos, o->cstr.length - o->pos, &chunk_length);
  908. size_t to_send = (chunk_length > INT_MAX ? INT_MAX : chunk_length);
  909. StreamPassInterface_Sender_Send(BConnection_SendAsync_GetIf(&write_pipe_inst->connection), (uint8_t *)chunk_data, to_send);
  910. return;
  911. fail0:
  912. NCDModuleInst_Backend_DeadError(i);
  913. }
  914. static void write_func_die (void *vo)
  915. {
  916. struct write_instance *o = vo;
  917. // if we're sending, abort write_pipe
  918. if (o->write_pipe_inst) {
  919. ASSERT(o->write_pipe_inst->state == WRITER_STATE_RUNNING)
  920. ASSERT(o->write_pipe_inst->write_inst == o)
  921. write_pipe_abort(o->write_pipe_inst);
  922. }
  923. NCDModuleInst_Backend_Dead(o->i);
  924. }
  925. static void close_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  926. {
  927. if (!NCDVal_ListRead(params->args, 0)) {
  928. ModuleLog(i, BLOG_ERROR, "wrong arity");
  929. goto fail0;
  930. }
  931. struct write_pipe_instance *write_pipe_inst = params->method_user;
  932. // check if a write error has already occured
  933. if (write_pipe_inst->state == WRITER_STATE_ERROR) {
  934. ModuleLog(i, BLOG_ERROR, "close() is disallowed after a write error has occured");
  935. goto fail0;
  936. }
  937. // check if the write_pipe has been aborted
  938. if (write_pipe_inst->state == WRITER_STATE_ABORTED) {
  939. ModuleLog(i, BLOG_ERROR, "close() is disallowed after a write() has been aborted");
  940. goto fail0;
  941. }
  942. // check if the write_pipe has been closed
  943. if (write_pipe_inst->state == WRITER_STATE_CLOSED) {
  944. ModuleLog(i, BLOG_ERROR, "close() is disallowed after close() has been called");
  945. goto fail0;
  946. }
  947. // close
  948. write_pipe_close(write_pipe_inst);
  949. // go up
  950. NCDModuleInst_Backend_Up(i);
  951. return;
  952. fail0:
  953. NCDModuleInst_Backend_DeadError(i);
  954. }
  955. static struct NCDModule modules[] = {
  956. {
  957. .type = "sys.start_process",
  958. .func_new2 = process_func_new,
  959. .func_die = process_func_die,
  960. .func_getvar2 = process_func_getvar,
  961. .alloc_size = sizeof(struct process_instance),
  962. .flags = NCDMODULE_FLAG_ACCEPT_NON_CONTINUOUS_STRINGS
  963. }, {
  964. .type = "sys.start_process::wait",
  965. .func_new2 = wait_func_new,
  966. .func_die = wait_func_die,
  967. .func_getvar2 = wait_func_getvar,
  968. .alloc_size = sizeof(struct wait_instance),
  969. .flags = NCDMODULE_FLAG_ACCEPT_NON_CONTINUOUS_STRINGS
  970. }, {
  971. .type = "sys.start_process::terminate",
  972. .func_new2 = terminate_func_new,
  973. .flags = NCDMODULE_FLAG_ACCEPT_NON_CONTINUOUS_STRINGS
  974. }, {
  975. .type = "sys.start_process::kill",
  976. .func_new2 = kill_func_new,
  977. .flags = NCDMODULE_FLAG_ACCEPT_NON_CONTINUOUS_STRINGS
  978. }, {
  979. .type = "sys.start_process::read_pipe",
  980. .func_new2 = read_pipe_func_new,
  981. .func_die = read_pipe_func_die,
  982. .func_getvar2 = read_pipe_func_getvar,
  983. .alloc_size = sizeof(struct read_pipe_instance),
  984. .flags = NCDMODULE_FLAG_ACCEPT_NON_CONTINUOUS_STRINGS
  985. }, {
  986. .type = "sys.start_process::read_pipe::read",
  987. .func_new2 = read_func_new,
  988. .func_die = read_func_die,
  989. .func_getvar2 = read_func_getvar,
  990. .alloc_size = sizeof(struct read_instance),
  991. .flags = NCDMODULE_FLAG_ACCEPT_NON_CONTINUOUS_STRINGS
  992. }, {
  993. .type = "sys.start_process::write_pipe",
  994. .func_new2 = write_pipe_func_new,
  995. .func_die = write_pipe_func_die,
  996. .func_getvar2 = write_pipe_func_getvar,
  997. .alloc_size = sizeof(struct write_pipe_instance),
  998. .flags = NCDMODULE_FLAG_ACCEPT_NON_CONTINUOUS_STRINGS
  999. }, {
  1000. .type = "sys.start_process::write_pipe::write",
  1001. .func_new2 = write_func_new,
  1002. .func_die = write_func_die,
  1003. .alloc_size = sizeof(struct write_instance),
  1004. .flags = NCDMODULE_FLAG_ACCEPT_NON_CONTINUOUS_STRINGS
  1005. }, {
  1006. .type = "sys.start_process::write_pipe::close",
  1007. .func_new2 = close_func_new,
  1008. .flags = NCDMODULE_FLAG_ACCEPT_NON_CONTINUOUS_STRINGS
  1009. }, {
  1010. .type = NULL
  1011. }
  1012. };
  1013. const struct NCDModuleGroup ncdmodule_sys_start_process = {
  1014. .modules = modules
  1015. };