zfile.c 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361
  1. /* Copyright (C) 1989, 2000-2004, artofcode LLC. All rights reserved.
  2. This software is provided AS-IS with no warranty, either express or
  3. implied.
  4. This software is distributed under license and may not be copied,
  5. modified or distributed except as expressly authorized under the terms
  6. of the license contained in the file LICENSE in this distribution.
  7. For more information about licensing, please refer to
  8. http://www.ghostscript.com/licensing/. For information on
  9. commercial licensing, go to http://www.artifex.com/licensing/ or
  10. contact Artifex Software, Inc., 101 Lucas Valley Road #110,
  11. San Rafael, CA 94903, U.S.A., +1(415)492-9861.
  12. */
  13. /* $Id: zfile.c,v 1.42 2005/07/14 15:14:39 alexcher Exp $ */
  14. /* Non-I/O file operators */
  15. #include "memory_.h"
  16. #include "string_.h"
  17. #include "unistd_.h"
  18. #include "ghost.h"
  19. #include "gscdefs.h" /* for gx_io_device_table */
  20. #include "gsutil.h" /* for bytes_compare */
  21. #include "gp.h"
  22. #include "gpmisc.h"
  23. #include "gsfname.h"
  24. #include "gsstruct.h" /* for registering root */
  25. #include "gxalloc.h" /* for streams */
  26. #include "oper.h"
  27. #include "dstack.h" /* for systemdict */
  28. #include "estack.h" /* for filenameforall, .execfile */
  29. #include "ialloc.h"
  30. #include "ilevel.h" /* %names only work in Level 2 */
  31. #include "interp.h" /* gs_errorinfo_put_string prototype */
  32. #include "iname.h"
  33. #include "isave.h" /* for restore */
  34. #include "idict.h"
  35. #include "iutil.h"
  36. #include "stream.h"
  37. #include "strimpl.h"
  38. #include "sfilter.h"
  39. #include "gxiodev.h" /* must come after stream.h */
  40. /* and before files.h */
  41. #include "files.h"
  42. #include "main.h" /* for gs_lib_paths */
  43. #include "store.h"
  44. /* Import the IODevice table. */
  45. extern_gx_io_device_table();
  46. /* Import the dtype of the stdio IODevices. */
  47. extern const char iodev_dtype_stdio[];
  48. /* Forward references: file name parsing. */
  49. private int parse_file_name(const ref * op, gs_parsed_file_name_t * pfn, bool safemode);
  50. private int parse_real_file_name(const ref * op,
  51. gs_parsed_file_name_t * pfn,
  52. gs_memory_t *mem, client_name_t cname);
  53. private int parse_file_access_string(const ref *op, char file_access[4]);
  54. /* Forward references: other. */
  55. private int execfile_finish(i_ctx_t *);
  56. private int execfile_cleanup(i_ctx_t *);
  57. private int zopen_file(i_ctx_t *, const gs_parsed_file_name_t *pfn,
  58. const char *file_access, stream **ps,
  59. gs_memory_t *mem);
  60. private iodev_proc_open_file(iodev_os_open_file);
  61. private void file_init_stream(stream *s, FILE *file, const char *fmode,
  62. byte *buffer, uint buffer_size);
  63. stream_proc_report_error(filter_report_error);
  64. /*
  65. * Since there can be many file objects referring to the same file/stream,
  66. * we can't simply free a stream when we close it. On the other hand,
  67. * we don't want freed streams to clutter up memory needlessly.
  68. * Our solution is to retain the freed streams, and reuse them.
  69. * To prevent an old file object from being able to access a reused stream,
  70. * we keep a serial number in each stream, and check it against a serial
  71. * number stored in the file object (as the "size"); when we close a file,
  72. * we increment its serial number. If the serial number ever overflows,
  73. * we leave it at zero, and do not reuse the stream.
  74. * (This will never happen.)
  75. *
  76. * Storage management for this scheme is a little tricky. We maintain an
  77. * invariant that says that a stream opened at a given save level always
  78. * uses a stream structure allocated at that level. By doing this, we don't
  79. * need to keep track separately of streams open at a level vs. streams
  80. * allocated at a level. To make this interact properly with save and
  81. * restore, we maintain a list of all streams allocated at this level, both
  82. * open and closed. We store this list in the allocator: this is a hack,
  83. * but it simplifies bookkeeping (in particular, it guarantees the list is
  84. * restored properly by a restore).
  85. *
  86. * We want to close streams freed by restore and by garbage collection. We
  87. * use the finalization procedure for this. For restore, we don't have to
  88. * do anything special to make this happen. For garbage collection, we do
  89. * something more drastic: we simply clear the list of known streams (at all
  90. * save levels). Any streams open at the time of garbage collection will no
  91. * longer participate in the list of known streams, but this does no harm;
  92. * it simply means that they won't get reused, and can only be reclaimed by
  93. * a future garbage collection or restore.
  94. */
  95. /*
  96. * Define the default stream buffer sizes. For file streams,
  97. * this is arbitrary, since the C library or operating system
  98. * does its own buffering in addition.
  99. * However, a buffer size of at least 2K bytes is necessary to prevent
  100. * JPEG decompression from running very slow. When less than 2K, an
  101. * intermediate filter is installed that transfers 1 byte at a time
  102. * causing many aborted roundtrips through the JPEG filter code.
  103. */
  104. #define DEFAULT_BUFFER_SIZE 2048
  105. const uint file_default_buffer_size = DEFAULT_BUFFER_SIZE;
  106. /* An invalid file object */
  107. private stream invalid_file_stream;
  108. stream *const invalid_file_entry = &invalid_file_stream;
  109. /* Initialize the file table */
  110. private int
  111. zfile_init(i_ctx_t *i_ctx_p)
  112. {
  113. /* Create and initialize an invalid (closed) stream. */
  114. /* Initialize the stream for the sake of the GC, */
  115. /* and so it can act as an empty input stream. */
  116. stream *const s = &invalid_file_stream;
  117. s_init(s, NULL);
  118. sread_string(s, NULL, 0);
  119. s->next = s->prev = 0;
  120. s_init_no_id(s);
  121. return 0;
  122. }
  123. /* Make an invalid file object. */
  124. void
  125. make_invalid_file(ref * fp)
  126. {
  127. make_file(fp, avm_invalid_file_entry, ~0, invalid_file_entry);
  128. }
  129. /* Check a file name for permission by stringmatch on one of the */
  130. /* strings of the permitgroup array. */
  131. private int
  132. check_file_permissions_reduced(i_ctx_t *i_ctx_p, const char *fname, int len,
  133. const char *permitgroup)
  134. {
  135. long i;
  136. ref *permitlist = NULL;
  137. /* an empty string (first character == 0) if '\' character is */
  138. /* recognized as a file name separator as on DOS & Windows */
  139. const char *win_sep2 = "\\";
  140. bool use_windows_pathsep = (gs_file_name_check_separator(win_sep2, 1, win_sep2) == 1);
  141. uint plen = gp_file_name_parents(fname, len);
  142. /* Assuming a reduced file name. */
  143. if (dict_find_string(&(i_ctx_p->userparams), permitgroup, &permitlist) <= 0)
  144. return 0; /* if Permissions not found, just allow access */
  145. for (i=0; i<r_size(permitlist); i++) {
  146. ref permitstring;
  147. const string_match_params win_filename_params = {
  148. '*', '?', '\\', true, true /* ignore case & '/' == '\\' */
  149. };
  150. const byte *permstr;
  151. uint permlen;
  152. int cwd_len = 0;
  153. if (array_get(imemory, permitlist, i, &permitstring) < 0 ||
  154. r_type(&permitstring) != t_string
  155. )
  156. break; /* any problem, just fail */
  157. permstr = permitstring.value.bytes;
  158. permlen = r_size(&permitstring);
  159. /*
  160. * Check if any file name is permitted with "*".
  161. */
  162. if (permlen == 1 && permstr[0] == '*')
  163. return 0; /* success */
  164. /*
  165. * If the filename starts with parent references,
  166. * the permission element must start with same number of parent references.
  167. */
  168. if (plen != 0 && plen != gp_file_name_parents((const char *)permstr, permlen))
  169. continue;
  170. cwd_len = gp_file_name_cwds((const char *)permstr, permlen);
  171. /*
  172. * If the permission starts with "./", absolute paths
  173. * are not permitted.
  174. */
  175. if (cwd_len > 0 && gp_file_name_is_absolute(fname, len))
  176. continue;
  177. /*
  178. * If the permission starts with "./", relative paths
  179. * with no "./" are allowed as well as with "./".
  180. * 'fname' has no "./" because it is reduced.
  181. */
  182. if (string_match( (const unsigned char*) fname, len,
  183. permstr + cwd_len, permlen - cwd_len,
  184. use_windows_pathsep ? &win_filename_params : NULL))
  185. return 0; /* success */
  186. }
  187. /* not found */
  188. return e_invalidfileaccess;
  189. }
  190. /* Check a file name for permission by stringmatch on one of the */
  191. /* strings of the permitgroup array */
  192. private int
  193. check_file_permissions(i_ctx_t *i_ctx_p, const char *fname, int len,
  194. const char *permitgroup)
  195. {
  196. char fname_reduced[gp_file_name_sizeof];
  197. uint rlen = sizeof(fname_reduced);
  198. if (gp_file_name_reduce(fname, len, fname_reduced, &rlen) != gp_combine_success)
  199. return e_invalidaccess; /* fail if we couldn't reduce */
  200. return check_file_permissions_reduced(i_ctx_p, fname_reduced, rlen, permitgroup);
  201. }
  202. /* <name_string> <access_string> file <file> */
  203. private int
  204. zfile(i_ctx_t *i_ctx_p)
  205. {
  206. os_ptr op = osp;
  207. char file_access[4];
  208. gs_parsed_file_name_t pname;
  209. int code = parse_file_access_string(op, file_access);
  210. stream *s;
  211. if (code < 0)
  212. return code;
  213. code = parse_file_name(op - 1, &pname, i_ctx_p->LockFilePermissions);
  214. if (code < 0)
  215. return code;
  216. /*
  217. * HACK: temporarily patch the current context pointer into the
  218. * state pointer for stdio-related devices. See ziodev.c for
  219. * more information.
  220. */
  221. if (pname.iodev && pname.iodev->dtype == iodev_dtype_stdio) {
  222. bool statement = (strcmp(pname.iodev->dname, "%statementedit%") == 0);
  223. bool lineedit = (strcmp(pname.iodev->dname, "%lineedit%") == 0);
  224. if (pname.fname)
  225. return_error(e_invalidfileaccess);
  226. if (statement || lineedit) {
  227. /* These need special code to support callouts */
  228. gx_io_device *indev = gs_findiodevice((const byte *)"%stdin", 6);
  229. stream *ins;
  230. if (strcmp(file_access, "r"))
  231. return_error(e_invalidfileaccess);
  232. indev->state = i_ctx_p;
  233. code = (indev->procs.open_device)(indev, file_access, &ins, imemory);
  234. indev->state = 0;
  235. if (code < 0)
  236. return code;
  237. check_ostack(2);
  238. push(2);
  239. make_stream_file(op - 3, ins, file_access);
  240. make_bool(op-2, statement);
  241. make_int(op-1, 0);
  242. make_string(op, icurrent_space, 0, NULL);
  243. return zfilelineedit(i_ctx_p);
  244. }
  245. pname.iodev->state = i_ctx_p;
  246. code = (*pname.iodev->procs.open_device)(pname.iodev,
  247. file_access, &s, imemory);
  248. pname.iodev->state = NULL;
  249. } else {
  250. if (pname.iodev == NULL)
  251. pname.iodev = iodev_default;
  252. code = zopen_file(i_ctx_p, &pname, file_access, &s, imemory);
  253. }
  254. if (code < 0)
  255. return code;
  256. code = ssetfilename(s, op[-1].value.const_bytes, r_size(op - 1));
  257. if (code < 0) {
  258. sclose(s);
  259. return_error(e_VMerror);
  260. }
  261. make_stream_file(op - 1, s, file_access);
  262. pop(1);
  263. return code;
  264. }
  265. /*
  266. * Files created with .tempfile permit some operations even if the
  267. * temp directory is not explicitly named on the PermitFile... path
  268. * The names 'SAFETY' and 'tempfiles' are defined by gs_init.ps
  269. */
  270. private bool
  271. file_is_tempfile(i_ctx_t *i_ctx_p, const ref *op)
  272. {
  273. ref *SAFETY;
  274. ref *tempfiles;
  275. ref kname;
  276. if (dict_find_string(systemdict, "SAFETY", &SAFETY) <= 0 ||
  277. dict_find_string(SAFETY, "tempfiles", &tempfiles) <= 0)
  278. return false;
  279. if (name_ref(imemory, op->value.bytes, r_size(op), &kname, -1) < 0 ||
  280. dict_find(tempfiles, &kname, &SAFETY) <= 0)
  281. return false;
  282. return true;
  283. }
  284. /* ------ Level 2 extensions ------ */
  285. /* <string> deletefile - */
  286. private int
  287. zdeletefile(i_ctx_t *i_ctx_p)
  288. {
  289. os_ptr op = osp;
  290. gs_parsed_file_name_t pname;
  291. int code = parse_real_file_name(op, &pname, imemory, "deletefile");
  292. if (code < 0)
  293. return code;
  294. if (pname.iodev == iodev_default) {
  295. if ((code = check_file_permissions(i_ctx_p, pname.fname, pname.len,
  296. "PermitFileControl")) < 0 &&
  297. !file_is_tempfile(i_ctx_p, op)) {
  298. return code;
  299. }
  300. }
  301. code = (*pname.iodev->procs.delete_file)(pname.iodev, pname.fname);
  302. gs_free_file_name(&pname, "deletefile");
  303. if (code < 0)
  304. return code;
  305. pop(1);
  306. return 0;
  307. }
  308. /* <template> <proc> <scratch> filenameforall - */
  309. private int file_continue(i_ctx_t *);
  310. private int file_cleanup(i_ctx_t *);
  311. private int
  312. zfilenameforall(i_ctx_t *i_ctx_p)
  313. {
  314. os_ptr op = osp;
  315. file_enum *pfen;
  316. gx_io_device *iodev = NULL;
  317. gs_parsed_file_name_t pname;
  318. int code = 0;
  319. check_write_type(*op, t_string);
  320. check_proc(op[-1]);
  321. check_read_type(op[-2], t_string);
  322. /* Push a mark, the iodev, devicenamelen, the scratch string, the enumerator, */
  323. /* and the procedure, and invoke the continuation. */
  324. check_estack(7);
  325. /* Get the iodevice */
  326. code = parse_file_name(op - 2, &pname, i_ctx_p->LockFilePermissions);
  327. if (code < 0)
  328. return code;
  329. iodev = (pname.iodev == NULL) ? iodev_default : pname.iodev;
  330. /* Check for several conditions that just cause us to return success */
  331. if (pname.len == 0 || iodev->procs.enumerate_files == iodev_no_enumerate_files) {
  332. pop(3);
  333. return 0; /* no pattern, or device not found -- just return */
  334. }
  335. pfen = iodev->procs.enumerate_files(iodev, (const char *)pname.fname,
  336. pname.len, imemory);
  337. if (pfen == 0)
  338. return_error(e_VMerror);
  339. push_mark_estack(es_for, file_cleanup);
  340. ++esp;
  341. make_istruct(esp, 0, iodev);
  342. ++esp;
  343. make_int(esp, r_size(op-2) - pname.len);
  344. *++esp = *op;
  345. ++esp;
  346. make_istruct(esp, 0, pfen);
  347. *++esp = op[-1];
  348. pop(3);
  349. code = file_continue(i_ctx_p);
  350. return (code == o_pop_estack ? o_push_estack : code);
  351. }
  352. /* Continuation operator for enumerating files */
  353. private int
  354. file_continue(i_ctx_t *i_ctx_p)
  355. {
  356. os_ptr op = osp;
  357. es_ptr pscratch = esp - 2;
  358. file_enum *pfen = r_ptr(esp - 1, file_enum);
  359. long devlen = esp[-3].value.intval;
  360. gx_io_device *iodev = r_ptr(esp - 4, gx_io_device);
  361. uint len = r_size(pscratch);
  362. uint code;
  363. if (len < devlen)
  364. return_error(e_rangecheck); /* not even room for device len */
  365. memcpy((char *)pscratch->value.bytes, iodev->dname, devlen);
  366. code = iodev->procs.enumerate_next(pfen, (char *)pscratch->value.bytes + devlen,
  367. len - devlen);
  368. if (code == ~(uint) 0) { /* all done */
  369. esp -= 5; /* pop proc, pfen, devlen, iodev , mark */
  370. return o_pop_estack;
  371. } else if (code > len) /* overran string */
  372. return_error(e_rangecheck);
  373. else {
  374. push(1);
  375. ref_assign(op, pscratch);
  376. r_set_size(op, code + devlen);
  377. push_op_estack(file_continue); /* come again */
  378. *++esp = pscratch[2]; /* proc */
  379. return o_push_estack;
  380. }
  381. }
  382. /* Cleanup procedure for enumerating files */
  383. private int
  384. file_cleanup(i_ctx_t *i_ctx_p)
  385. {
  386. gx_io_device *iodev = r_ptr(esp + 2, gx_io_device);
  387. iodev->procs.enumerate_close(r_ptr(esp + 5, file_enum));
  388. return 0;
  389. }
  390. /* <string1> <string2> renamefile - */
  391. private int
  392. zrenamefile(i_ctx_t *i_ctx_p)
  393. {
  394. os_ptr op = osp;
  395. gs_parsed_file_name_t pname1, pname2;
  396. int code = parse_real_file_name(op - 1, &pname1, imemory,
  397. "renamefile(from)");
  398. if (code < 0)
  399. return code;
  400. pname2.fname = 0;
  401. code = parse_real_file_name(op, &pname2, imemory, "renamefile(to)");
  402. if (code >= 0) {
  403. if (pname1.iodev != pname2.iodev ) {
  404. if (pname1.iodev == iodev_default)
  405. pname1.iodev = pname2.iodev;
  406. if (pname2.iodev == iodev_default)
  407. pname2.iodev = pname1.iodev;
  408. }
  409. if (pname1.iodev != pname2.iodev ||
  410. (pname1.iodev == iodev_default &&
  411. /*
  412. * We require FileControl permissions on the source path
  413. * unless it is a temporary file. Also, we require FileControl
  414. * and FileWriting permissions to the destination file/path.
  415. */
  416. ((check_file_permissions(i_ctx_p, pname1.fname, pname1.len,
  417. "PermitFileControl") < 0 &&
  418. !file_is_tempfile(i_ctx_p, op - 1)) ||
  419. (check_file_permissions(i_ctx_p, pname2.fname, pname2.len,
  420. "PermitFileControl") < 0 ||
  421. check_file_permissions(i_ctx_p, pname2.fname, pname2.len,
  422. "PermitFileWriting") < 0 )))) {
  423. code = gs_note_error(e_invalidfileaccess);
  424. } else {
  425. code = (*pname1.iodev->procs.rename_file)(pname1.iodev,
  426. pname1.fname, pname2.fname);
  427. }
  428. }
  429. gs_free_file_name(&pname2, "renamefile(to)");
  430. gs_free_file_name(&pname1, "renamefile(from)");
  431. if (code < 0)
  432. return code;
  433. pop(2);
  434. return 0;
  435. }
  436. /* <file> status <open_bool> */
  437. /* <string> status <pages> <bytes> <ref_time> <creation_time> true */
  438. /* <string> status false */
  439. private int
  440. zstatus(i_ctx_t *i_ctx_p)
  441. {
  442. os_ptr op = osp;
  443. switch (r_type(op)) {
  444. case t_file:
  445. {
  446. stream *s;
  447. make_bool(op, (file_is_valid(s, op) ? 1 : 0));
  448. }
  449. return 0;
  450. case t_string:
  451. {
  452. gs_parsed_file_name_t pname;
  453. struct stat fstat;
  454. int code = parse_file_name(op, &pname, i_ctx_p->LockFilePermissions);
  455. if (code < 0)
  456. return code;
  457. code = gs_terminate_file_name(&pname, imemory, "status");
  458. if (code < 0)
  459. return code;
  460. code = (*pname.iodev->procs.file_status)(pname.iodev,
  461. pname.fname, &fstat);
  462. switch (code) {
  463. case 0:
  464. check_ostack(4);
  465. /*
  466. * Check to make sure that the file size fits into
  467. * a PostScript integer. (On some systems, long is
  468. * 32 bits, but file sizes are 64 bits.)
  469. */
  470. push(4);
  471. make_int(op - 4, stat_blocks(&fstat));
  472. make_int(op - 3, fstat.st_size);
  473. /*
  474. * We can't check the value simply by using ==,
  475. * because signed/unsigned == does the wrong thing.
  476. * Instead, since integer assignment only keeps the
  477. * bottom bits, we convert the values to double
  478. * and then test for equality. This handles all
  479. * cases of signed/unsigned or width mismatch.
  480. */
  481. if ((double)op[-4].value.intval !=
  482. (double)stat_blocks(&fstat) ||
  483. (double)op[-3].value.intval !=
  484. (double)fstat.st_size
  485. )
  486. return_error(e_limitcheck);
  487. make_int(op - 2, fstat.st_mtime);
  488. make_int(op - 1, fstat.st_ctime);
  489. make_bool(op, 1);
  490. break;
  491. case e_undefinedfilename:
  492. make_bool(op, 0);
  493. code = 0;
  494. }
  495. gs_free_file_name(&pname, "status");
  496. return code;
  497. }
  498. default:
  499. return_op_typecheck(op);
  500. }
  501. }
  502. /* ------ Non-standard extensions ------ */
  503. /* <executable_file> .execfile - */
  504. private int
  505. zexecfile(i_ctx_t *i_ctx_p)
  506. {
  507. os_ptr op = osp;
  508. check_type_access(*op, t_file, a_executable | a_read | a_execute);
  509. check_estack(4); /* cleanup, file, finish, file */
  510. push_mark_estack(es_other, execfile_cleanup);
  511. *++esp = *op;
  512. push_op_estack(execfile_finish);
  513. return zexec(i_ctx_p);
  514. }
  515. /* Finish normally. */
  516. private int
  517. execfile_finish(i_ctx_t *i_ctx_p)
  518. {
  519. check_ostack(1);
  520. esp -= 2;
  521. execfile_cleanup(i_ctx_p);
  522. return o_pop_estack;
  523. }
  524. /* Clean up by closing the file. */
  525. private int
  526. execfile_cleanup(i_ctx_t *i_ctx_p)
  527. {
  528. check_ostack(1);
  529. *++osp = esp[2];
  530. return zclosefile(i_ctx_p);
  531. }
  532. /* - .filenamelistseparator <string> */
  533. private int
  534. zfilenamelistseparator(i_ctx_t *i_ctx_p)
  535. {
  536. os_ptr op = osp;
  537. push(1);
  538. make_const_string(op, avm_foreign | a_readonly, 1,
  539. (const byte *)&gp_file_name_list_separator);
  540. return 0;
  541. }
  542. /* <name> .filenamesplit <dir> <base> <extension> */
  543. private int
  544. zfilenamesplit(i_ctx_t *i_ctx_p)
  545. {
  546. os_ptr op = osp;
  547. check_read_type(*op, t_string);
  548. /****** NOT IMPLEMENTED YET ******/
  549. return_error(e_undefined);
  550. }
  551. /* <string> .libfile <file> true */
  552. /* <string> .libfile <string> false */
  553. private int
  554. zlibfile(i_ctx_t *i_ctx_p)
  555. {
  556. os_ptr op = osp;
  557. int code;
  558. byte cname[gp_file_name_sizeof];
  559. uint clen;
  560. gs_parsed_file_name_t pname;
  561. stream *s;
  562. check_ostack(2);
  563. code = parse_file_name(op, &pname, i_ctx_p->LockFilePermissions);
  564. if (code < 0)
  565. return code;
  566. if (pname.iodev == NULL)
  567. pname.iodev = iodev_default;
  568. if (pname.iodev != iodev_default) { /* Non-OS devices don't have search paths (yet). */
  569. code = zopen_file(i_ctx_p, &pname, "r", &s, imemory);
  570. if (code >= 0) {
  571. code = ssetfilename(s, op->value.const_bytes, r_size(op));
  572. if (code < 0) {
  573. sclose(s);
  574. return_error(e_VMerror);
  575. }
  576. }
  577. if (code < 0) {
  578. push(1);
  579. make_false(op);
  580. return 0;
  581. }
  582. make_stream_file(op, s, "r");
  583. } else {
  584. ref fref;
  585. code = lib_file_open(i_ctx_p->lib_path, i_ctx_p, pname.fname, pname.len, cname, sizeof(cname),
  586. &clen, &fref, imemory);
  587. if (code >= 0) {
  588. s = fptr(&fref);
  589. code = ssetfilename(s, cname, clen);
  590. if (code < 0) {
  591. sclose(s);
  592. return_error(e_VMerror);
  593. }
  594. }
  595. if (code < 0) {
  596. if (code == e_VMerror || code == e_invalidfileaccess)
  597. return code;
  598. push(1);
  599. make_false(op);
  600. return 0;
  601. }
  602. ref_assign(op, &fref);
  603. }
  604. push(1);
  605. make_true(op);
  606. return 0;
  607. }
  608. /* A "simple" prefix is defined as a (possibly empty) string of
  609. alphanumeric, underscore, and hyphen characters. */
  610. private bool
  611. prefix_is_simple(const char *pstr)
  612. {
  613. int i;
  614. char c;
  615. for (i = 0; (c = pstr[i]) != 0; i++) {
  616. if (!(c == '-' || c == '_' || (c >= '0' && c <= '9') ||
  617. (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')))
  618. return false;
  619. }
  620. return true;
  621. }
  622. /* <prefix|null> <access_string> .tempfile <name_string> <file> */
  623. private int
  624. ztempfile(i_ctx_t *i_ctx_p)
  625. {
  626. os_ptr op = osp;
  627. const char *pstr;
  628. char fmode[4];
  629. int code = parse_file_access_string(op, fmode);
  630. char prefix[gp_file_name_sizeof];
  631. char fname[gp_file_name_sizeof];
  632. uint fnlen;
  633. FILE *sfile;
  634. stream *s;
  635. byte *buf;
  636. if (code < 0)
  637. return code;
  638. strcat(fmode, gp_fmode_binary_suffix);
  639. if (r_has_type(op - 1, t_null))
  640. pstr = gp_scratch_file_name_prefix;
  641. else {
  642. uint psize;
  643. check_read_type(op[-1], t_string);
  644. psize = r_size(op - 1);
  645. if (psize >= gp_file_name_sizeof)
  646. return_error(e_rangecheck);
  647. memcpy(prefix, op[-1].value.const_bytes, psize);
  648. prefix[psize] = 0;
  649. pstr = prefix;
  650. }
  651. if (gp_file_name_is_absolute(pstr, strlen(pstr))) {
  652. if (check_file_permissions(i_ctx_p, pstr, strlen(pstr),
  653. "PermitFileWriting") < 0) {
  654. return_error(e_invalidfileaccess);
  655. }
  656. } else if (!prefix_is_simple(pstr)) {
  657. return_error(e_invalidfileaccess);
  658. }
  659. s = file_alloc_stream(imemory, "ztempfile(stream)");
  660. if (s == 0)
  661. return_error(e_VMerror);
  662. buf = gs_alloc_bytes(imemory, file_default_buffer_size,
  663. "ztempfile(buffer)");
  664. if (buf == 0)
  665. return_error(e_VMerror);
  666. sfile = gp_open_scratch_file(pstr, fname, fmode);
  667. if (sfile == 0) {
  668. gs_free_object(imemory, buf, "ztempfile(buffer)");
  669. return_error(e_invalidfileaccess);
  670. }
  671. fnlen = strlen(fname);
  672. file_init_stream(s, sfile, fmode, buf, file_default_buffer_size);
  673. code = ssetfilename(s, (const unsigned char*) fname, fnlen);
  674. if (code < 0) {
  675. sclose(s);
  676. iodev_default->procs.delete_file(iodev_default, fname);
  677. return_error(e_VMerror);
  678. }
  679. make_const_string(op - 1, a_readonly | icurrent_space, fnlen,
  680. s->file_name.data);
  681. make_stream_file(op, s, fmode);
  682. return code;
  683. }
  684. /* ------ Initialization procedure ------ */
  685. const op_def zfile_op_defs[] =
  686. {
  687. {"1deletefile", zdeletefile},
  688. {"1.execfile", zexecfile},
  689. {"2file", zfile},
  690. {"3filenameforall", zfilenameforall},
  691. {"0.filenamelistseparator", zfilenamelistseparator},
  692. {"1.filenamesplit", zfilenamesplit},
  693. {"1.libfile", zlibfile},
  694. {"2renamefile", zrenamefile},
  695. {"1status", zstatus},
  696. {"2.tempfile", ztempfile},
  697. /* Internal operators */
  698. {"0%file_continue", file_continue},
  699. {"0%execfile_finish", execfile_finish},
  700. op_def_end(zfile_init)
  701. };
  702. /* ------ File name parsing ------ */
  703. /* Parse a file name into device and individual name. */
  704. /* See gsfname.c for details. */
  705. private int
  706. parse_file_name(const ref * op, gs_parsed_file_name_t * pfn, bool safemode)
  707. {
  708. int code;
  709. check_read_type(*op, t_string);
  710. code = gs_parse_file_name(pfn, (const char *)op->value.const_bytes,
  711. r_size(op));
  712. if (code < 0)
  713. return code;
  714. /*
  715. * Check here for the %pipe device which is illegal when
  716. * LockFilePermissions is true. In the future we might want to allow
  717. * the %pipe device to be included on the PermitFile... paths, but
  718. * for now it is simply disallowed.
  719. */
  720. if (pfn->iodev && safemode && strcmp(pfn->iodev->dname, "%pipe%") == 0)
  721. return e_invalidfileaccess;
  722. return code;
  723. }
  724. /* Parse a real (non-device) file name and convert to a C string. */
  725. /* See gsfname.c for details. */
  726. private int
  727. parse_real_file_name(const ref *op, gs_parsed_file_name_t *pfn,
  728. gs_memory_t *mem, client_name_t cname)
  729. {
  730. check_read_type(*op, t_string);
  731. return gs_parse_real_file_name(pfn, (const char *)op->value.const_bytes,
  732. r_size(op), mem, cname);
  733. }
  734. /* Parse the access string for opening a file. */
  735. /* [4] is for r/w, +, b, \0. */
  736. private int
  737. parse_file_access_string(const ref *op, char file_access[4])
  738. {
  739. const byte *astr;
  740. check_read_type(*op, t_string);
  741. astr = op->value.const_bytes;
  742. switch (r_size(op)) {
  743. case 2:
  744. if (astr[1] != '+')
  745. return_error(e_invalidfileaccess);
  746. file_access[1] = '+';
  747. file_access[2] = 0;
  748. break;
  749. case 1:
  750. file_access[1] = 0;
  751. break;
  752. default:
  753. return_error(e_invalidfileaccess);
  754. }
  755. switch (astr[0]) {
  756. case 'r':
  757. case 'w':
  758. case 'a':
  759. break;
  760. default:
  761. return_error(e_invalidfileaccess);
  762. }
  763. file_access[0] = astr[0];
  764. return 0;
  765. }
  766. /* ------ Stream opening ------ */
  767. /*
  768. * Open a file specified by a parsed file name (which may be only a
  769. * device).
  770. */
  771. private int
  772. zopen_file(i_ctx_t *i_ctx_p, const gs_parsed_file_name_t *pfn,
  773. const char *file_access, stream **ps, gs_memory_t *mem)
  774. {
  775. gx_io_device *const iodev = pfn->iodev;
  776. if (pfn->fname == NULL) /* just a device */
  777. return iodev->procs.open_device(iodev, file_access, ps, mem);
  778. else { /* file */
  779. iodev_proc_open_file((*open_file)) = iodev->procs.open_file;
  780. if (open_file == 0)
  781. open_file = iodev_os_open_file;
  782. /* Check OS files to make sure we allow the type of access */
  783. if (open_file == iodev_os_open_file) {
  784. int code = check_file_permissions(i_ctx_p, pfn->fname, pfn->len,
  785. file_access[0] == 'r' ? "PermitFileReading" : "PermitFileWriting");
  786. if (code < 0)
  787. return code;
  788. }
  789. return open_file(iodev, pfn->fname, pfn->len, file_access, ps, mem);
  790. }
  791. }
  792. /*
  793. * Define the file_open procedure for the %os% IODevice (also used, as the
  794. * default, for %pipe% and possibly others).
  795. */
  796. private int
  797. iodev_os_open_file(gx_io_device * iodev, const char *fname, uint len,
  798. const char *file_access, stream ** ps, gs_memory_t * mem)
  799. {
  800. return file_open_stream(fname, len, file_access,
  801. file_default_buffer_size, ps,
  802. iodev, iodev->procs.fopen, mem);
  803. }
  804. /* Make a t_file reference to a stream. */
  805. void
  806. make_stream_file(ref * pfile, stream * s, const char *access)
  807. {
  808. uint attrs =
  809. (access[1] == '+' ? a_write + a_read + a_execute : 0) |
  810. imemory_space((gs_ref_memory_t *) s->memory);
  811. if (access[0] == 'r') {
  812. make_file(pfile, attrs | (a_read | a_execute), s->read_id, s);
  813. s->write_id = 0;
  814. } else {
  815. make_file(pfile, attrs | a_write, s->write_id, s);
  816. s->read_id = 0;
  817. }
  818. }
  819. private gp_file_name_combine_result
  820. gp_file_name_combine_patch(const char *prefix, uint plen, const char *fname, uint flen,
  821. bool no_sibling, char *buffer, uint *blen)
  822. {
  823. return gp_file_name_combine(prefix, plen, fname, flen, no_sibling, buffer, blen);
  824. }
  825. /* Prepare a stream with a file name. */
  826. /* Return 0 if successful, error code if not. */
  827. /* On a successful return, the C file name is in the stream buffer. */
  828. /* If fname==0, set up stream, and buffer. */
  829. private int
  830. file_prepare_stream(const char *fname, uint len, const char *file_access,
  831. uint buffer_size, stream ** ps, char fmode[4],
  832. gx_io_device *iodev, gs_memory_t *mem)
  833. {
  834. byte *buffer;
  835. register stream *s;
  836. /* Open the file, always in binary mode. */
  837. strcpy(fmode, file_access);
  838. strcat(fmode, gp_fmode_binary_suffix);
  839. if (buffer_size == 0)
  840. buffer_size = file_default_buffer_size;
  841. if (len >= buffer_size) /* we copy the file name into the buffer */
  842. return_error(e_limitcheck);
  843. /* Allocate the stream first, since it persists */
  844. /* even after the file has been closed. */
  845. s = file_alloc_stream(mem, "file_prepare_stream");
  846. if (s == 0)
  847. return_error(e_VMerror);
  848. /* Allocate the buffer. */
  849. buffer = gs_alloc_bytes(mem, buffer_size, "file_prepare_stream(buffer)");
  850. if (buffer == 0)
  851. return_error(e_VMerror);
  852. if (fname != 0) {
  853. memcpy(buffer, fname, len);
  854. buffer[len] = 0; /* terminate string */
  855. } else
  856. buffer[0] = 0; /* safety */
  857. s->cbuf = buffer;
  858. s->bsize = s->cbsize = buffer_size;
  859. *ps = s;
  860. return 0;
  861. }
  862. private int
  863. check_file_permissions_aux(i_ctx_t *i_ctx_p, char *fname, uint flen)
  864. { /* i_ctx_p is NULL running init files. */
  865. /* fname must be reduced. */
  866. if (i_ctx_p == NULL)
  867. return 0;
  868. if (check_file_permissions_reduced(i_ctx_p, fname, flen, "PermitFileReading") < 0)
  869. return_error(e_invalidfileaccess);
  870. return 0;
  871. }
  872. /* The startup code calls this to open @-files. */
  873. private int
  874. lib_fopen_with_libpath(gs_file_path_ptr lib_path,
  875. const gs_memory_t *mem,
  876. i_ctx_t *i_ctx_p,
  877. gx_io_device *iodev,
  878. const char *fname, uint flen, char fmode[4], char *buffer, int blen,
  879. FILE **file)
  880. { /* i_ctx_p is NULL running init files.
  881. * lib_path and mem are never NULL
  882. */
  883. bool starting_arg_file = false;
  884. bool search_with_no_combine = false;
  885. bool search_with_combine = false;
  886. if (i_ctx_p != NULL) {
  887. starting_arg_file = i_ctx_p->starting_arg_file;
  888. i_ctx_p->starting_arg_file = false;
  889. } else
  890. starting_arg_file = true;
  891. if (gp_file_name_is_absolute(fname, flen)) {
  892. search_with_no_combine = true;
  893. search_with_combine = false;
  894. } else {
  895. search_with_no_combine = starting_arg_file;
  896. search_with_combine = true;
  897. }
  898. if (search_with_no_combine) {
  899. uint blen1 = blen;
  900. if (gp_file_name_reduce(fname, flen, buffer, &blen1) != gp_combine_success)
  901. goto skip;
  902. if (iodev->procs.fopen(iodev, buffer, fmode, file,
  903. buffer, blen) == 0) {
  904. if (starting_arg_file ||
  905. check_file_permissions_aux(i_ctx_p, buffer, blen1) >= 0)
  906. return 0;
  907. iodev->procs.fclose(iodev, *file);
  908. *file = NULL;
  909. return_error(e_invalidfileaccess);
  910. } else
  911. *file = NULL;
  912. skip:;
  913. }
  914. if (search_with_combine) {
  915. const gs_file_path *pfpath = lib_path;
  916. uint pi;
  917. for (pi = 0; pi < r_size(&pfpath->list); ++pi) {
  918. const ref *prdir = pfpath->list.value.refs + pi;
  919. const char *pstr = (const char *)prdir->value.const_bytes;
  920. uint plen = r_size(prdir), blen1 = blen;
  921. gp_file_name_combine_result r = gp_file_name_combine_patch(pstr, plen,
  922. fname, flen, false, buffer, &blen1);
  923. if (r != gp_combine_success)
  924. continue;
  925. if (iodev->procs.fopen(iodev, buffer, fmode, file,
  926. buffer, blen) == 0) {
  927. if (starting_arg_file ||
  928. check_file_permissions_aux(i_ctx_p, buffer, blen1) >= 0)
  929. return 0;
  930. iodev->procs.fclose(iodev, *file);
  931. *file = NULL;
  932. return_error(e_invalidfileaccess);
  933. }
  934. *file = NULL; /* safety */
  935. }
  936. }
  937. return_error(e_undefinedfilename);
  938. }
  939. /* The startup code calls this to open @-files. */
  940. FILE *
  941. lib_fopen(const gs_file_path_ptr pfpath, const gs_memory_t *mem, const char *fname)
  942. {
  943. /* We need a buffer to hold the expanded file name. */
  944. char buffer[gp_file_name_sizeof];
  945. /* We can't count on the IODevice table to have been initialized yet. */
  946. /* Allocate a copy of the default IODevice. */
  947. gx_io_device iodev_default_copy = *gx_io_device_table[0];
  948. char fmode[3] = "r";
  949. FILE *file = NULL;
  950. strcat(fmode, gp_fmode_binary_suffix);
  951. lib_fopen_with_libpath(pfpath, mem, NULL, &iodev_default_copy, fname, strlen(fname),
  952. fmode, buffer, sizeof(buffer), &file);
  953. return file;
  954. }
  955. /* Open a file stream on an OS file and create a file object, */
  956. /* using the search paths. */
  957. /* The startup code calls this to open the initialization file gs_init.ps. */
  958. int
  959. lib_file_open(const gs_file_path_ptr pfpath,
  960. i_ctx_t *i_ctx_p, const char *fname, uint len, byte * cname, uint max_clen,
  961. uint * pclen, ref * pfile, gs_memory_t *mem)
  962. { /* i_ctx_p is NULL running init files. */
  963. stream *s;
  964. int code;
  965. char fmode[4]; /* r/w/a, [+], [b], null */
  966. char *buffer;
  967. uint blen;
  968. gx_io_device *iodev = iodev_default;
  969. FILE *file;
  970. code = file_prepare_stream(fname, len, "r", file_default_buffer_size,
  971. &s, fmode, iodev, mem);
  972. if (code < 0)
  973. return code;
  974. if (fname == 0)
  975. return 0;
  976. buffer = (char *)s->cbuf;
  977. code = lib_fopen_with_libpath(pfpath, mem, i_ctx_p,
  978. iodev, fname, len, fmode, buffer, s->bsize, &file);
  979. if (code < 0) {
  980. s->cbuf = NULL;
  981. s->bsize = s->cbsize = 0;
  982. gs_free_object(mem, buffer, "lib_file_open");
  983. return code;
  984. }
  985. file_init_stream(s, file, fmode, (byte *)buffer, s->bsize);
  986. /* Get the name from the stream buffer. */
  987. blen = strlen(buffer);
  988. if (blen > max_clen) {
  989. sclose(s);
  990. return_error(e_limitcheck);
  991. }
  992. memcpy(cname, buffer, blen);
  993. *pclen = blen;
  994. make_stream_file(pfile, s, "r");
  995. return 0;
  996. }
  997. /* Open a file stream that reads a string. */
  998. /* (This is currently used only by the ccinit feature.) */
  999. /* The string must be allocated in non-garbage-collectable (foreign) space. */
  1000. int
  1001. file_read_string(const byte *str, uint len, ref *pfile, gs_ref_memory_t *imem)
  1002. {
  1003. stream *s = file_alloc_stream((gs_memory_t *)imem, "file_read_string");
  1004. if (s == 0)
  1005. return_error(e_VMerror);
  1006. sread_string(s, str, len);
  1007. s->foreign = 1;
  1008. s->write_id = 0;
  1009. make_file(pfile, a_readonly | imemory_space(imem), s->read_id, s);
  1010. s->save_close = s->procs.close;
  1011. s->procs.close = file_close_disable;
  1012. return 0;
  1013. }
  1014. /*
  1015. * Set up a file stream on an OS file. The caller has allocated the
  1016. * stream and buffer.
  1017. */
  1018. private void
  1019. file_init_stream(stream *s, FILE *file, const char *fmode, byte *buffer,
  1020. uint buffer_size)
  1021. {
  1022. switch (fmode[0]) {
  1023. case 'a':
  1024. sappend_file(s, file, buffer, buffer_size);
  1025. break;
  1026. case 'r':
  1027. /* Defeat buffering for terminals. */
  1028. {
  1029. struct stat rstat;
  1030. fstat(fileno(file), &rstat);
  1031. sread_file(s, file, buffer,
  1032. (S_ISCHR(rstat.st_mode) ? 1 : buffer_size));
  1033. }
  1034. break;
  1035. case 'w':
  1036. swrite_file(s, file, buffer, buffer_size);
  1037. }
  1038. if (fmode[1] == '+')
  1039. s->file_modes |= s_mode_read | s_mode_write;
  1040. s->save_close = s->procs.close;
  1041. s->procs.close = file_close_file;
  1042. }
  1043. /* Open a file stream, optionally on an OS file. */
  1044. /* Return 0 if successful, error code if not. */
  1045. /* On a successful return, the C file name is in the stream buffer. */
  1046. /* If fname==0, set up the file entry, stream, and buffer, */
  1047. /* but don't open an OS file or initialize the stream. */
  1048. int
  1049. file_open_stream(const char *fname, uint len, const char *file_access,
  1050. uint buffer_size, stream ** ps, gx_io_device *iodev,
  1051. iodev_proc_fopen_t fopen_proc, gs_memory_t *mem)
  1052. {
  1053. int code;
  1054. FILE *file;
  1055. char fmode[4]; /* r/w/a, [+], [b], null */
  1056. if (!iodev)
  1057. iodev = iodev_default;
  1058. code = file_prepare_stream(fname, len, file_access, buffer_size, ps, fmode,
  1059. (!iodev ? iodev_default : iodev), mem);
  1060. if (code < 0)
  1061. return code;
  1062. if (fname == 0)
  1063. return 0;
  1064. code = (*fopen_proc)(iodev, (char *)(*ps)->cbuf, fmode, &file,
  1065. (char *)(*ps)->cbuf, (*ps)->bsize);
  1066. if (code < 0)
  1067. return code;
  1068. file_init_stream(*ps, file, fmode, (*ps)->cbuf, (*ps)->bsize);
  1069. return 0;
  1070. }
  1071. /* Report an error by storing it in the stream's error_string. */
  1072. int
  1073. filter_report_error(stream_state * st, const char *str)
  1074. {
  1075. if_debug1('s', "[s]stream error: %s\n", str);
  1076. strncpy(st->error_string, str, STREAM_MAX_ERROR_STRING);
  1077. /* Ensure null termination. */
  1078. st->error_string[STREAM_MAX_ERROR_STRING] = 0;
  1079. return 0;
  1080. }
  1081. /* Open a file stream for a filter. */
  1082. int
  1083. filter_open(const char *file_access, uint buffer_size, ref * pfile,
  1084. const stream_procs * procs, const stream_template * template,
  1085. const stream_state * st, gs_memory_t *mem)
  1086. {
  1087. stream *s;
  1088. uint ssize = gs_struct_type_size(template->stype);
  1089. stream_state *sst = 0;
  1090. int code;
  1091. if (template->stype != &st_stream_state) {
  1092. sst = s_alloc_state(mem, template->stype, "filter_open(stream_state)");
  1093. if (sst == 0)
  1094. return_error(e_VMerror);
  1095. }
  1096. code = file_open_stream((char *)0, 0, file_access, buffer_size, &s,
  1097. (gx_io_device *)0, (iodev_proc_fopen_t)0, mem);
  1098. if (code < 0) {
  1099. gs_free_object(mem, sst, "filter_open(stream_state)");
  1100. return code;
  1101. }
  1102. s_std_init(s, s->cbuf, s->bsize, procs,
  1103. (*file_access == 'r' ? s_mode_read : s_mode_write));
  1104. s->procs.process = template->process;
  1105. s->save_close = s->procs.close;
  1106. s->procs.close = file_close_file;
  1107. if (sst == 0) {
  1108. /* This stream doesn't have any state of its own. */
  1109. /* Hack: use the stream itself as the state. */
  1110. sst = (stream_state *) s;
  1111. } else if (st != 0) /* might not have client parameters */
  1112. memcpy(sst, st, ssize);
  1113. s->state = sst;
  1114. s_init_state(sst, template, mem);
  1115. sst->report_error = filter_report_error;
  1116. if (template->init != 0) {
  1117. code = (*template->init)(sst);
  1118. if (code < 0) {
  1119. gs_free_object(mem, sst, "filter_open(stream_state)");
  1120. gs_free_object(mem, s->cbuf, "filter_open(buffer)");
  1121. return code;
  1122. }
  1123. }
  1124. make_stream_file(pfile, s, file_access);
  1125. return 0;
  1126. }
  1127. /* Allocate and return a file stream. */
  1128. /* Return 0 if the allocation failed. */
  1129. /* The stream is initialized to an invalid state, so the caller need not */
  1130. /* worry about cleaning up if a later step in opening the stream fails. */
  1131. stream *
  1132. file_alloc_stream(gs_memory_t * mem, client_name_t cname)
  1133. {
  1134. stream *s;
  1135. gs_ref_memory_t *imem = 0;
  1136. /*
  1137. * HACK: Figure out whether this is a gs_ref_memory_t.
  1138. * Avoiding this hack would require rippling a change
  1139. * from gs_memory_t to gs_ref_memory_t into the open_file and
  1140. * open_device procedures of gx_io_device, which in turn would
  1141. * impact other things we don't want to change.
  1142. */
  1143. if (mem->procs.free_object == gs_ref_memory_procs.free_object)
  1144. imem = (gs_ref_memory_t *) mem;
  1145. if (imem) {
  1146. /* Look first for a free stream allocated at this level. */
  1147. s = imem->streams;
  1148. while (s != 0) {
  1149. if (!s_is_valid(s) && s->read_id != 0 /* i.e. !overflowed */ ) {
  1150. s->is_temp = 0; /* not a temp stream */
  1151. return s;
  1152. }
  1153. s = s->next;
  1154. }
  1155. }
  1156. s = s_alloc(mem, cname);
  1157. if (s == 0)
  1158. return 0;
  1159. s_init_ids(s);
  1160. s->is_temp = 0; /* not a temp stream */
  1161. /*
  1162. * Disable the stream now (in case we can't open the file,
  1163. * or a filter init procedure fails) so that `restore' won't
  1164. * crash when it tries to close open files.
  1165. */
  1166. s_disable(s);
  1167. if (imem) {
  1168. /* Add s to the list of files. */
  1169. if (imem->streams != 0)
  1170. imem->streams->prev = s;
  1171. s->next = imem->streams;
  1172. imem->streams = s;
  1173. } else {
  1174. s->next = 0;
  1175. }
  1176. s->prev = 0;
  1177. return s;
  1178. }
  1179. /* ------ Stream closing ------ */
  1180. /*
  1181. * Finish closing a file stream. This used to check whether it was
  1182. * currentfile, but we don't have to do this any longer. This replaces the
  1183. * close procedure for the std* streams, which cannot actually be closed.
  1184. *
  1185. * This is exported for ziodev.c. */
  1186. int
  1187. file_close_finish(stream * s)
  1188. {
  1189. return 0;
  1190. }
  1191. /*
  1192. * Close a file stream, but don't deallocate the buffer. This replaces the
  1193. * close procedure for %lineedit and %statementedit. (This is WRONG: these
  1194. * streams should allocate a new buffer each time they are opened, but that
  1195. * would overstress the allocator right now.) This is exported for ziodev.c.
  1196. * This also replaces the close procedure for the string-reading stream
  1197. * created for gs_run_string.
  1198. */
  1199. int
  1200. file_close_disable(stream * s)
  1201. {
  1202. int code = (*s->save_close)(s);
  1203. if (code)
  1204. return code;
  1205. /* Increment the IDs to prevent further access. */
  1206. s->read_id = s->write_id = (s->read_id | s->write_id) + 1;
  1207. return file_close_finish(s);
  1208. }
  1209. /* Close a file stream. This replaces the close procedure in the stream */
  1210. /* for normal (OS) files and for filters. */
  1211. int
  1212. file_close_file(stream * s)
  1213. {
  1214. stream *stemp = s->strm;
  1215. gs_memory_t *mem;
  1216. int code = file_close_disable(s);
  1217. if (code)
  1218. return code;
  1219. /*
  1220. * Check for temporary streams created for filters.
  1221. * There may be more than one in the case of a procedure-based filter,
  1222. * or if we created an intermediate stream to ensure
  1223. * a large enough buffer. Note that these streams may have been
  1224. * allocated by file_alloc_stream, so we mustn't free them.
  1225. */
  1226. while (stemp != 0 && stemp->is_temp != 0) {
  1227. stream *snext = stemp->strm;
  1228. mem = stemp->memory;
  1229. if (stemp->is_temp > 1)
  1230. gs_free_object(mem, stemp->cbuf,
  1231. "file_close(temp stream buffer)");
  1232. s_disable(stemp);
  1233. stemp = snext;
  1234. }
  1235. mem = s->memory;
  1236. gs_free_object(mem, s->cbuf, "file_close(buffer)");
  1237. if (s->close_strm && stemp != 0)
  1238. return sclose(stemp);
  1239. return 0;
  1240. }
  1241. /* Close a file object. */
  1242. /* This is exported only for gsmain.c. */
  1243. int
  1244. file_close(ref * pfile)
  1245. {
  1246. stream *s;
  1247. if (file_is_valid(s, pfile)) { /* closing a closed file is a no-op */
  1248. if (sclose(s))
  1249. return_error(e_ioerror);
  1250. }
  1251. return 0;
  1252. }