file_open.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. /**
  2. * @file file_open.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. * file_open(string filename, string mode)
  33. *
  34. * Variables:
  35. * string is_error - "true" if the file_open object is in error state, "false"
  36. * otherwise
  37. *
  38. * Description:
  39. * Opens a file for subsequent reading or writing. The 'mode' argument must
  40. * be one of: "r", "w", "a", "r+", "w+", "a+"; it corresponds to the mode string
  41. * that will be passed to the fopen() function.
  42. * When the file_open() statement goes up, the error state is set depending on
  43. * whether opening succeeded or failed. The 'is_error' variable should be used
  44. * to check the error state.
  45. * If an error occurs afterward within read(), write() or seek(), the error state
  46. * is set, and the file_open() statement is toggled down and back up. This way,
  47. * the same piece of user code can handle all file errors.
  48. *
  49. * Synopsis:
  50. * file_open::read()
  51. *
  52. * Variables:
  53. * string (empty) - the data which was read, or an empty string if EOF was reached
  54. * string not_eof - "false" if EOF was reached, "true" if not
  55. *
  56. * Description:
  57. * Reads data from an opened file. The file must not be in error state.
  58. * If reading fails, this statement will never go up, the error state of the
  59. * file_open() statement will be set, and the file_open() statement will trigger
  60. * backtracking (go down and up).
  61. *
  62. * Synopsis:
  63. * file_open::write(string data)
  64. *
  65. * Description:
  66. * Writes data to an opened file. The file must not be in error state.
  67. * If writing fails, this statement will never go up, the error state of the
  68. * file_open() statement will be set, and the file_open() statement will trigger
  69. * backtracking (go down and up).
  70. *
  71. * Synopsis:
  72. * file_open::seek(string position, string whence)
  73. *
  74. * Description:
  75. * Sets the file position indicator. The 'position' argument must be a possibly
  76. * negative decimal number, and is interpreted relative to 'whence'. Here, 'whence'
  77. * may be one of:
  78. * - "set", meaning beginning of file,
  79. * - "cur", meaning the current position, and
  80. * - "end", meaning the end of file.
  81. * Errors are handled as in read() and write(). Note that if the position argument
  82. * is too small or too large to convert to off_t, this is not a seek error, and only
  83. * the seek command will fail.
  84. *
  85. * Synopsis:
  86. * file_open::close()
  87. *
  88. * Description:
  89. * Closes the file. The file must not be in error state.
  90. * Errors are handled as handled as in read() and write(), i.e. the process is
  91. * backtracked to file_open() with the error state set.
  92. * On success, the error state of the file is set (but without backtracking), and
  93. * the close() statement goes up .
  94. */
  95. #include <stddef.h>
  96. #include <stdio.h>
  97. #include <stdint.h>
  98. #include <limits.h>
  99. #include <misc/debug.h>
  100. #include <misc/balloc.h>
  101. #include <misc/parse_number.h>
  102. #include <ncd/NCDModule.h>
  103. #include <ncd/static_strings.h>
  104. #include <ncd/extra/value_utils.h>
  105. #include <ncd/extra/NCDBuf.h>
  106. #include <generated/blog_channel_ncd_file_open.h>
  107. #define ModuleLog(i, ...) NCDModuleInst_Backend_Log((i), BLOG_CURRENT_CHANNEL, __VA_ARGS__)
  108. #define READ_BUF_SIZE 8192
  109. struct open_instance {
  110. NCDModuleInst *i;
  111. FILE *fh;
  112. NCDBufStore store;
  113. };
  114. struct read_instance {
  115. NCDModuleInst *i;
  116. NCDBuf *buf;
  117. size_t length;
  118. };
  119. enum {STRING_IS_ERROR, STRING_NOT_EOF};
  120. static struct NCD_string_request strings[] = {
  121. {"is_error"}, {"not_eof"}, {NULL}
  122. };
  123. static int parse_mode (const char *data, size_t mode_len, char *out)
  124. {
  125. if (mode_len == 0) {
  126. return 0;
  127. }
  128. switch (*data) {
  129. case 'r':
  130. case 'w':
  131. case 'a':
  132. *out++ = *data++;
  133. mode_len--;
  134. break;
  135. default:
  136. return 0;
  137. }
  138. if (mode_len == 0) {
  139. goto finish;
  140. }
  141. switch (*data) {
  142. case '+':
  143. *out++ = *data++;
  144. mode_len--;
  145. break;
  146. default:
  147. return 0;
  148. }
  149. if (mode_len == 0) {
  150. goto finish;
  151. }
  152. return 0;
  153. finish:
  154. *out = '\0';
  155. return 1;
  156. }
  157. static void trigger_error (struct open_instance *o)
  158. {
  159. if (o->fh) {
  160. // close file
  161. if (fclose(o->fh) != 0) {
  162. ModuleLog(o->i, BLOG_ERROR, "fclose failed");
  163. }
  164. // set no file, indicating error
  165. o->fh = NULL;
  166. }
  167. // go down and up
  168. NCDModuleInst_Backend_Down(o->i);
  169. NCDModuleInst_Backend_Up(o->i);
  170. }
  171. static void open_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  172. {
  173. struct open_instance *o = vo;
  174. o->i = i;
  175. // check arguments
  176. NCDValRef filename_arg;
  177. NCDValRef mode_arg;
  178. if (!NCDVal_ListRead(params->args, 2, &filename_arg, &mode_arg)) {
  179. ModuleLog(o->i, BLOG_ERROR, "wrong arity");
  180. goto fail0;
  181. }
  182. if (!NCDVal_IsStringNoNulls(filename_arg) || !NCDVal_IsString(mode_arg)) {
  183. ModuleLog(o->i, BLOG_ERROR, "wrong type");
  184. goto fail0;
  185. }
  186. // check mode
  187. char mode[5];
  188. if (!parse_mode(NCDVal_StringData(mode_arg), NCDVal_StringLength(mode_arg), mode)) {
  189. ModuleLog(o->i, BLOG_ERROR, "wrong mode");
  190. goto fail0;
  191. }
  192. // init store
  193. NCDBufStore_Init(&o->store, READ_BUF_SIZE);
  194. // null terminate filename
  195. NCDValNullTermString filename_nts;
  196. if (!NCDVal_StringNullTerminate(filename_arg, &filename_nts)) {
  197. ModuleLog(i, BLOG_ERROR, "NCDVal_StringNullTerminate failed");
  198. goto fail1;
  199. }
  200. // open file
  201. o->fh = fopen(filename_nts.data, mode);
  202. NCDValNullTermString_Free(&filename_nts);
  203. if (!o->fh) {
  204. ModuleLog(o->i, BLOG_ERROR, "fopen failed");
  205. }
  206. // go up
  207. NCDModuleInst_Backend_Up(i);
  208. return;
  209. fail1:
  210. NCDBufStore_Free(&o->store);
  211. fail0:
  212. NCDModuleInst_Backend_SetError(i);
  213. NCDModuleInst_Backend_Dead(i);
  214. }
  215. static void open_func_die (void *vo)
  216. {
  217. struct open_instance *o = vo;
  218. // close file
  219. if (o->fh) {
  220. if (fclose(o->fh) != 0) {
  221. ModuleLog(o->i, BLOG_ERROR, "fclose failed");
  222. }
  223. }
  224. // free store
  225. NCDBufStore_Free(&o->store);
  226. NCDModuleInst_Backend_Dead(o->i);
  227. }
  228. static int open_func_getvar (void *vo, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  229. {
  230. struct open_instance *o = vo;
  231. if (name == strings[STRING_IS_ERROR].id) {
  232. *out = ncd_make_boolean(mem, !o->fh, o->i->params->iparams->string_index);
  233. if (NCDVal_IsInvalid(*out)) {
  234. ModuleLog(o->i, BLOG_ERROR, "ncd_make_boolean failed");
  235. }
  236. return 1;
  237. }
  238. return 0;
  239. }
  240. static void read_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  241. {
  242. struct read_instance *o = vo;
  243. o->i = i;
  244. // check arguments
  245. if (!NCDVal_ListRead(params->args, 0)) {
  246. ModuleLog(o->i, BLOG_ERROR, "wrong arity");
  247. goto fail0;
  248. }
  249. // get open instance
  250. struct open_instance *open_inst = NCDModuleInst_Backend_GetUser((NCDModuleInst *)params->method_user);
  251. // make sure it's not in error
  252. if (!open_inst->fh) {
  253. ModuleLog(o->i, BLOG_ERROR, "open instance is in error");
  254. goto fail0;
  255. }
  256. // get buffer
  257. o->buf = NCDBufStore_GetBuf(&open_inst->store);
  258. if (!o->buf) {
  259. ModuleLog(o->i, BLOG_ERROR, "NCDBufStore_GetBuf failed");
  260. goto fail0;
  261. }
  262. // starting with empty buffer
  263. char *data = NCDBuf_Data(o->buf);
  264. o->length = 0;
  265. while (o->length < READ_BUF_SIZE) {
  266. // read
  267. size_t readed = fread(data + o->length, 1, READ_BUF_SIZE - o->length, open_inst->fh);
  268. if (readed == 0) {
  269. break;
  270. }
  271. ASSERT(readed <= READ_BUF_SIZE - o->length)
  272. // increment length
  273. o->length += readed;
  274. }
  275. // if we couldn't read anything due to an error, trigger
  276. // error in the open instance, and don't go up
  277. if (o->length == 0 && !feof(open_inst->fh)) {
  278. ModuleLog(o->i, BLOG_ERROR, "fread failed");
  279. trigger_error(open_inst);
  280. return;
  281. }
  282. // go up
  283. NCDModuleInst_Backend_Up(i);
  284. return;
  285. fail0:
  286. NCDModuleInst_Backend_SetError(i);
  287. NCDModuleInst_Backend_Dead(i);
  288. }
  289. static void read_func_die (void *vo)
  290. {
  291. struct read_instance *o = vo;
  292. // release buffer
  293. NCDRefTarget_Deref(NCDBuf_RefTarget(o->buf));
  294. NCDModuleInst_Backend_Dead(o->i);
  295. }
  296. static int read_func_getvar (void *vo, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  297. {
  298. struct read_instance *o = vo;
  299. if (name == NCD_STRING_EMPTY) {
  300. *out = NCDVal_NewExternalString(mem, NCDBuf_Data(o->buf), o->length, NCDBuf_RefTarget(o->buf));
  301. if (NCDVal_IsInvalid(*out)) {
  302. ModuleLog(o->i, BLOG_ERROR, "NCDVal_NewExternalString failed");
  303. }
  304. return 1;
  305. }
  306. if (name == strings[STRING_NOT_EOF].id) {
  307. *out = ncd_make_boolean(mem, (o->length != 0), o->i->params->iparams->string_index);
  308. if (NCDVal_IsInvalid(*out)) {
  309. ModuleLog(o->i, BLOG_ERROR, "ncd_make_boolean failed");
  310. }
  311. return 1;
  312. }
  313. return 0;
  314. }
  315. static void write_func_new (void *unused, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  316. {
  317. // check arguments
  318. NCDValRef data_arg;
  319. if (!NCDVal_ListRead(params->args, 1, &data_arg)) {
  320. ModuleLog(i, BLOG_ERROR, "wrong arity");
  321. goto fail0;
  322. }
  323. if (!NCDVal_IsString(data_arg)) {
  324. ModuleLog(i, BLOG_ERROR, "wrong type");
  325. goto fail0;
  326. }
  327. // get open instance
  328. struct open_instance *open_inst = NCDModuleInst_Backend_GetUser((NCDModuleInst *)params->method_user);
  329. // make sure it's not in error
  330. if (!open_inst->fh) {
  331. ModuleLog(i, BLOG_ERROR, "open instance is in error");
  332. goto fail0;
  333. }
  334. // get data pointer and length
  335. const char *data = NCDVal_StringData(data_arg);
  336. size_t length = NCDVal_StringLength(data_arg);
  337. while (length > 0) {
  338. // write
  339. size_t written = fwrite(data, 1, length, open_inst->fh);
  340. if (written == 0) {
  341. ModuleLog(i, BLOG_ERROR, "fwrite failed");
  342. trigger_error(open_inst);
  343. return;
  344. }
  345. ASSERT(written <= length)
  346. // update writing state
  347. data += written;
  348. length -= written;
  349. }
  350. // go up
  351. NCDModuleInst_Backend_Up(i);
  352. return;
  353. fail0:
  354. NCDModuleInst_Backend_SetError(i);
  355. NCDModuleInst_Backend_Dead(i);
  356. }
  357. static void seek_func_new (void *unused, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  358. {
  359. // check arguments
  360. NCDValRef position_arg;
  361. NCDValRef whence_arg;
  362. if (!NCDVal_ListRead(params->args, 2, &position_arg, &whence_arg)) {
  363. ModuleLog(i, BLOG_ERROR, "wrong arity");
  364. goto fail0;
  365. }
  366. if (!NCDVal_IsString(position_arg) || !NCDVal_IsString(whence_arg)) {
  367. ModuleLog(i, BLOG_ERROR, "wrong type");
  368. goto fail0;
  369. }
  370. // parse position
  371. int position_sign;
  372. uintmax_t position_mag;
  373. if (!parse_signmag_integer_bin(NCDVal_StringData(position_arg), NCDVal_StringLength(position_arg), &position_sign, &position_mag)) {
  374. ModuleLog(i, BLOG_ERROR, "wrong position");
  375. goto fail0;
  376. }
  377. // parse whence
  378. int whence;
  379. if (NCDVal_StringEquals(whence_arg, "set")) {
  380. whence = SEEK_SET;
  381. }
  382. else if (NCDVal_StringEquals(whence_arg, "cur")) {
  383. whence = SEEK_CUR;
  384. }
  385. else if (NCDVal_StringEquals(whence_arg, "end")) {
  386. whence = SEEK_END;
  387. }
  388. else {
  389. ModuleLog(i, BLOG_ERROR, "wrong whence");
  390. goto fail0;
  391. }
  392. // determine min/max values of off_t (non-portable hack)
  393. off_t off_t_min = (sizeof(off_t) == 8 ? INT64_MIN : INT32_MIN);
  394. off_t off_t_max = (sizeof(off_t) == 8 ? INT64_MAX : INT32_MAX);
  395. // compute position as off_t
  396. off_t position;
  397. if (position_sign < 0 && position_mag > 0) {
  398. if (position_mag - 1 > -(off_t_min + 1)) {
  399. ModuleLog(i, BLOG_ERROR, "position underflow");
  400. goto fail0;
  401. }
  402. position = -(off_t)(position_mag - 1) - 1;
  403. } else {
  404. if (position_mag > off_t_max) {
  405. ModuleLog(i, BLOG_ERROR, "position overflow");
  406. goto fail0;
  407. }
  408. position = position_mag;
  409. }
  410. // get open instance
  411. struct open_instance *open_inst = NCDModuleInst_Backend_GetUser((NCDModuleInst *)params->method_user);
  412. // make sure it's not in error
  413. if (!open_inst->fh) {
  414. ModuleLog(i, BLOG_ERROR, "open instance is in error");
  415. goto fail0;
  416. }
  417. // seek
  418. if (fseeko(open_inst->fh, position, whence) < 0) {
  419. ModuleLog(i, BLOG_ERROR, "fseeko failed");
  420. trigger_error(open_inst);
  421. return;
  422. }
  423. // go up
  424. NCDModuleInst_Backend_Up(i);
  425. return;
  426. fail0:
  427. NCDModuleInst_Backend_SetError(i);
  428. NCDModuleInst_Backend_Dead(i);
  429. }
  430. static void close_func_new (void *unused, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  431. {
  432. // check arguments
  433. if (!NCDVal_ListRead(params->args, 0)) {
  434. ModuleLog(i, BLOG_ERROR, "wrong arity");
  435. goto fail0;
  436. }
  437. // get open instance
  438. struct open_instance *open_inst = NCDModuleInst_Backend_GetUser((NCDModuleInst *)params->method_user);
  439. // make sure it's not in error
  440. if (!open_inst->fh) {
  441. ModuleLog(i, BLOG_ERROR, "open instance is in error");
  442. goto fail0;
  443. }
  444. // close
  445. int res = fclose(open_inst->fh);
  446. open_inst->fh = NULL;
  447. if (res != 0) {
  448. ModuleLog(i, BLOG_ERROR, "fclose failed");
  449. trigger_error(open_inst);
  450. return;
  451. }
  452. // go up
  453. NCDModuleInst_Backend_Up(i);
  454. return;
  455. fail0:
  456. NCDModuleInst_Backend_SetError(i);
  457. NCDModuleInst_Backend_Dead(i);
  458. }
  459. static struct NCDModule modules[] = {
  460. {
  461. .type = "file_open",
  462. .func_new2 = open_func_new,
  463. .func_die = open_func_die,
  464. .func_getvar2 = open_func_getvar,
  465. .alloc_size = sizeof(struct open_instance)
  466. }, {
  467. .type = "file_open::read",
  468. .func_new2 = read_func_new,
  469. .func_die = read_func_die,
  470. .func_getvar2 = read_func_getvar,
  471. .alloc_size = sizeof(struct read_instance)
  472. }, {
  473. .type = "file_open::write",
  474. .func_new2 = write_func_new,
  475. }, {
  476. .type = "file_open::seek",
  477. .func_new2 = seek_func_new,
  478. }, {
  479. .type = "file_open::close",
  480. .func_new2 = close_func_new,
  481. }, {
  482. .type = NULL
  483. }
  484. };
  485. const struct NCDModuleGroup ncdmodule_file_open = {
  486. .modules = modules,
  487. .strings = strings
  488. };