file_open.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  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/value_utils.h>
  105. #include <generated/blog_channel_ncd_file_open.h>
  106. #define ModuleLog(i, ...) NCDModuleInst_Backend_Log((i), BLOG_CURRENT_CHANNEL, __VA_ARGS__)
  107. #define START_READ_SIZE 512
  108. #define MAX_READ_SIZE 8192
  109. struct open_instance {
  110. NCDModuleInst *i;
  111. FILE *fh;
  112. };
  113. struct read_instance {
  114. NCDModuleInst *i;
  115. char *data;
  116. size_t length;
  117. };
  118. enum {STRING_IS_ERROR, STRING_NOT_EOF};
  119. static struct NCD_string_request strings[] = {
  120. {"is_error"}, {"not_eof"}, {NULL}
  121. };
  122. static int parse_mode (const char *data, size_t mode_len, char *out)
  123. {
  124. if (mode_len == 0) {
  125. return 0;
  126. }
  127. switch (*data) {
  128. case 'r':
  129. case 'w':
  130. case 'a':
  131. *out++ = *data++;
  132. mode_len--;
  133. break;
  134. default:
  135. return 0;
  136. }
  137. if (mode_len == 0) {
  138. goto finish;
  139. }
  140. switch (*data) {
  141. case '+':
  142. *out++ = *data++;
  143. mode_len--;
  144. break;
  145. default:
  146. return 0;
  147. }
  148. if (mode_len == 0) {
  149. goto finish;
  150. }
  151. return 0;
  152. finish:
  153. *out = '\0';
  154. return 1;
  155. }
  156. static void trigger_error (struct open_instance *o)
  157. {
  158. if (o->fh) {
  159. // close file
  160. if (fclose(o->fh) != 0) {
  161. ModuleLog(o->i, BLOG_ERROR, "fclose failed");
  162. }
  163. // set no file, indicating error
  164. o->fh = NULL;
  165. }
  166. // go down and up
  167. NCDModuleInst_Backend_Down(o->i);
  168. NCDModuleInst_Backend_Up(o->i);
  169. }
  170. static void open_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  171. {
  172. struct open_instance *o = vo;
  173. o->i = i;
  174. // check arguments
  175. NCDValRef filename_arg;
  176. NCDValRef mode_arg;
  177. if (!NCDVal_ListRead(params->args, 2, &filename_arg, &mode_arg)) {
  178. ModuleLog(o->i, BLOG_ERROR, "wrong arity");
  179. goto fail0;
  180. }
  181. if (!NCDVal_IsStringNoNulls(filename_arg) || !NCDVal_IsString(mode_arg)) {
  182. ModuleLog(o->i, BLOG_ERROR, "wrong type");
  183. goto fail0;
  184. }
  185. // check mode
  186. char mode[5];
  187. if (!parse_mode(NCDVal_StringData(mode_arg), NCDVal_StringLength(mode_arg), mode)) {
  188. ModuleLog(o->i, BLOG_ERROR, "wrong mode");
  189. goto fail0;
  190. }
  191. // null terminate filename
  192. NCDValNullTermString filename_nts;
  193. if (!NCDVal_StringNullTerminate(filename_arg, &filename_nts)) {
  194. ModuleLog(i, BLOG_ERROR, "NCDVal_StringNullTerminate failed");
  195. goto fail0;
  196. }
  197. // open file
  198. o->fh = fopen(filename_nts.data, mode);
  199. NCDValNullTermString_Free(&filename_nts);
  200. if (!o->fh) {
  201. ModuleLog(o->i, BLOG_ERROR, "fopen failed");
  202. }
  203. // go up
  204. NCDModuleInst_Backend_Up(i);
  205. return;
  206. fail0:
  207. NCDModuleInst_Backend_SetError(i);
  208. NCDModuleInst_Backend_Dead(i);
  209. }
  210. static void open_func_die (void *vo)
  211. {
  212. struct open_instance *o = vo;
  213. // close file
  214. if (o->fh) {
  215. if (fclose(o->fh) != 0) {
  216. ModuleLog(o->i, BLOG_ERROR, "fclose failed");
  217. }
  218. }
  219. NCDModuleInst_Backend_Dead(o->i);
  220. }
  221. static int open_func_getvar (void *vo, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  222. {
  223. struct open_instance *o = vo;
  224. if (name == strings[STRING_IS_ERROR].id) {
  225. *out = ncd_make_boolean(mem, !o->fh, o->i->params->iparams->string_index);
  226. if (NCDVal_IsInvalid(*out)) {
  227. ModuleLog(o->i, BLOG_ERROR, "ncd_make_boolean failed");
  228. }
  229. return 1;
  230. }
  231. return 0;
  232. }
  233. static void read_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  234. {
  235. struct read_instance *o = vo;
  236. o->i = i;
  237. // check arguments
  238. if (!NCDVal_ListRead(params->args, 0)) {
  239. ModuleLog(o->i, BLOG_ERROR, "wrong arity");
  240. goto fail0;
  241. }
  242. // get open instance
  243. struct open_instance *open_inst = NCDModuleInst_Backend_GetUser((NCDModuleInst *)params->method_user);
  244. // make sure it's not in error
  245. if (!open_inst->fh) {
  246. ModuleLog(o->i, BLOG_ERROR, "open instance is in error");
  247. goto fail0;
  248. }
  249. // allocate buffer
  250. size_t capacity = START_READ_SIZE;
  251. o->data = BAlloc(capacity);
  252. if (!o->data) {
  253. ModuleLog(o->i, BLOG_ERROR, "BAlloc failed");
  254. goto fail0;
  255. }
  256. // starting with empty buffer
  257. o->length = 0;
  258. while (1) {
  259. // read
  260. size_t readed = fread(o->data + o->length, 1, capacity - o->length, open_inst->fh);
  261. if (readed == 0) {
  262. break;
  263. }
  264. ASSERT(readed <= capacity - o->length)
  265. // increment length
  266. o->length += readed;
  267. if (o->length == capacity) {
  268. // do not reallocate beyond limit
  269. if (capacity > MAX_READ_SIZE / 2) {
  270. break;
  271. }
  272. // reallocate buffer
  273. capacity *= 2;
  274. char *new_data = BRealloc(o->data, capacity);
  275. if (!new_data) {
  276. ModuleLog(o->i, BLOG_ERROR, "BRealloc failed");
  277. goto fail1;
  278. }
  279. o->data = new_data;
  280. }
  281. }
  282. if (o->length == 0) {
  283. // free buffer
  284. BFree(o->data);
  285. o->data = NULL;
  286. // if we couldn't read anything due to an error, trigger
  287. // error in the open instance, and don't go up
  288. if (!feof(open_inst->fh)) {
  289. ModuleLog(o->i, BLOG_ERROR, "fread failed");
  290. trigger_error(open_inst);
  291. return;
  292. }
  293. }
  294. // go up
  295. NCDModuleInst_Backend_Up(i);
  296. return;
  297. fail1:
  298. BFree(o->data);
  299. fail0:
  300. NCDModuleInst_Backend_SetError(i);
  301. NCDModuleInst_Backend_Dead(i);
  302. }
  303. static void read_func_die (void *vo)
  304. {
  305. struct read_instance *o = vo;
  306. // free buffer
  307. if (o->data) {
  308. BFree(o->data);
  309. }
  310. NCDModuleInst_Backend_Dead(o->i);
  311. }
  312. static int read_func_getvar (void *vo, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  313. {
  314. struct read_instance *o = vo;
  315. if (name == NCD_STRING_EMPTY) {
  316. const char *data = (!o->data ? "" : o->data);
  317. *out = NCDVal_NewStringBin(mem, (const uint8_t *)data, o->length);
  318. if (NCDVal_IsInvalid(*out)) {
  319. ModuleLog(o->i, BLOG_ERROR, "NCDVal_NewStringBin failed");
  320. }
  321. return 1;
  322. }
  323. if (name == strings[STRING_NOT_EOF].id) {
  324. *out = ncd_make_boolean(mem, (o->length != 0), o->i->params->iparams->string_index);
  325. if (NCDVal_IsInvalid(*out)) {
  326. ModuleLog(o->i, BLOG_ERROR, "ncd_make_boolean failed");
  327. }
  328. return 1;
  329. }
  330. return 0;
  331. }
  332. static void write_func_new (void *unused, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  333. {
  334. // check arguments
  335. NCDValRef data_arg;
  336. if (!NCDVal_ListRead(params->args, 1, &data_arg)) {
  337. ModuleLog(i, BLOG_ERROR, "wrong arity");
  338. goto fail0;
  339. }
  340. if (!NCDVal_IsString(data_arg)) {
  341. ModuleLog(i, BLOG_ERROR, "wrong type");
  342. goto fail0;
  343. }
  344. // get open instance
  345. struct open_instance *open_inst = NCDModuleInst_Backend_GetUser((NCDModuleInst *)params->method_user);
  346. // make sure it's not in error
  347. if (!open_inst->fh) {
  348. ModuleLog(i, BLOG_ERROR, "open instance is in error");
  349. goto fail0;
  350. }
  351. // get data pointer and length
  352. const char *data = NCDVal_StringData(data_arg);
  353. size_t length = NCDVal_StringLength(data_arg);
  354. while (length > 0) {
  355. // write
  356. size_t written = fwrite(data, 1, length, open_inst->fh);
  357. if (written == 0) {
  358. ModuleLog(i, BLOG_ERROR, "fwrite failed");
  359. trigger_error(open_inst);
  360. return;
  361. }
  362. ASSERT(written <= length)
  363. // update writing state
  364. data += written;
  365. length -= written;
  366. }
  367. // go up
  368. NCDModuleInst_Backend_Up(i);
  369. return;
  370. fail0:
  371. NCDModuleInst_Backend_SetError(i);
  372. NCDModuleInst_Backend_Dead(i);
  373. }
  374. static void seek_func_new (void *unused, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  375. {
  376. // check arguments
  377. NCDValRef position_arg;
  378. NCDValRef whence_arg;
  379. if (!NCDVal_ListRead(params->args, 2, &position_arg, &whence_arg)) {
  380. ModuleLog(i, BLOG_ERROR, "wrong arity");
  381. goto fail0;
  382. }
  383. if (!NCDVal_IsString(position_arg) || !NCDVal_IsString(whence_arg)) {
  384. ModuleLog(i, BLOG_ERROR, "wrong type");
  385. goto fail0;
  386. }
  387. // parse position
  388. int position_sign;
  389. uintmax_t position_mag;
  390. if (!parse_signmag_integer_bin(NCDVal_StringData(position_arg), NCDVal_StringLength(position_arg), &position_sign, &position_mag)) {
  391. ModuleLog(i, BLOG_ERROR, "wrong position");
  392. goto fail0;
  393. }
  394. // parse whence
  395. int whence;
  396. if (NCDVal_StringEquals(whence_arg, "set")) {
  397. whence = SEEK_SET;
  398. }
  399. else if (NCDVal_StringEquals(whence_arg, "cur")) {
  400. whence = SEEK_CUR;
  401. }
  402. else if (NCDVal_StringEquals(whence_arg, "end")) {
  403. whence = SEEK_END;
  404. }
  405. else {
  406. ModuleLog(i, BLOG_ERROR, "wrong whence");
  407. goto fail0;
  408. }
  409. // determine min/max values of off_t (non-portable hack)
  410. off_t off_t_min = (sizeof(off_t) == 8 ? INT64_MIN : INT32_MIN);
  411. off_t off_t_max = (sizeof(off_t) == 8 ? INT64_MAX : INT32_MAX);
  412. // compute position as off_t
  413. off_t position;
  414. if (position_sign < 0 && position_mag > 0) {
  415. if (position_mag - 1 > -(off_t_min + 1)) {
  416. ModuleLog(i, BLOG_ERROR, "position underflow");
  417. goto fail0;
  418. }
  419. position = -(off_t)(position_mag - 1) - 1;
  420. } else {
  421. if (position_mag > off_t_max) {
  422. ModuleLog(i, BLOG_ERROR, "position overflow");
  423. goto fail0;
  424. }
  425. position = position_mag;
  426. }
  427. // get open instance
  428. struct open_instance *open_inst = NCDModuleInst_Backend_GetUser((NCDModuleInst *)params->method_user);
  429. // make sure it's not in error
  430. if (!open_inst->fh) {
  431. ModuleLog(i, BLOG_ERROR, "open instance is in error");
  432. goto fail0;
  433. }
  434. // seek
  435. if (fseeko(open_inst->fh, position, whence) < 0) {
  436. ModuleLog(i, BLOG_ERROR, "fseeko failed");
  437. trigger_error(open_inst);
  438. return;
  439. }
  440. // go up
  441. NCDModuleInst_Backend_Up(i);
  442. return;
  443. fail0:
  444. NCDModuleInst_Backend_SetError(i);
  445. NCDModuleInst_Backend_Dead(i);
  446. }
  447. static void close_func_new (void *unused, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  448. {
  449. // check arguments
  450. if (!NCDVal_ListRead(params->args, 0)) {
  451. ModuleLog(i, BLOG_ERROR, "wrong arity");
  452. goto fail0;
  453. }
  454. // get open instance
  455. struct open_instance *open_inst = NCDModuleInst_Backend_GetUser((NCDModuleInst *)params->method_user);
  456. // make sure it's not in error
  457. if (!open_inst->fh) {
  458. ModuleLog(i, BLOG_ERROR, "open instance is in error");
  459. goto fail0;
  460. }
  461. // close
  462. int res = fclose(open_inst->fh);
  463. open_inst->fh = NULL;
  464. if (res != 0) {
  465. ModuleLog(i, BLOG_ERROR, "fclose failed");
  466. trigger_error(open_inst);
  467. return;
  468. }
  469. // go up
  470. NCDModuleInst_Backend_Up(i);
  471. return;
  472. fail0:
  473. NCDModuleInst_Backend_SetError(i);
  474. NCDModuleInst_Backend_Dead(i);
  475. }
  476. static struct NCDModule modules[] = {
  477. {
  478. .type = "file_open",
  479. .func_new2 = open_func_new,
  480. .func_die = open_func_die,
  481. .func_getvar2 = open_func_getvar,
  482. .alloc_size = sizeof(struct open_instance)
  483. }, {
  484. .type = "file_open::read",
  485. .func_new2 = read_func_new,
  486. .func_die = read_func_die,
  487. .func_getvar2 = read_func_getvar,
  488. .alloc_size = sizeof(struct read_instance)
  489. }, {
  490. .type = "file_open::write",
  491. .func_new2 = write_func_new,
  492. }, {
  493. .type = "file_open::seek",
  494. .func_new2 = seek_func_new,
  495. }, {
  496. .type = "file_open::close",
  497. .func_new2 = close_func_new,
  498. }, {
  499. .type = NULL
  500. }
  501. };
  502. const struct NCDModuleGroup ncdmodule_file_open = {
  503. .modules = modules,
  504. .strings = strings
  505. };