Debian Codegraph @

support/babel/tads.c

raw symbols SCIP
1 /*
2 * tads.c - Treaty of Babel common functions for tads2 and tads3 modules
3 *
4 * This file depends on treaty_builder.h
5 *
6 * This file is public domain, but note that any changes to this file may
7 * render it noncompliant with the Treaty of Babel
8 *
9 * Modified
10 *. 04/08/2006 LRRaszewski - changed babel API calls to threadsafe versions
11 *. 04/08/2006 MJRoberts - initial implementation
12 */
13
14
15 #include "treaty.h"
16 #include <ctype.h>
17 #include <stdio.h>
18 #include <string.h>
19 #include <stdlib.h>
20 #include "tads.h"
21 #include "md5.h"
22
23 #define ASSERT_OUTPUT_SIZE(x) \
24 do { if (output_extent < (x)) return INVALID_USAGE_RV; } while (0)
25
26 #define T2_SIGNATURE "TADS2 bin\012\015\032"
27 #define T3_SIGNATURE "T3-image\015\012\032"
28
29 #ifndef FALSE
30 #define FALSE 0
31 #endif
32 #ifndef TRUE
33 #define TRUE 1
34 #endif
35 /* ------------------------------------------------------------------------ */
36 /*
37 * private structures
38 */
39
40 /*
41 * resource information structure - this encapsulates the location and size
42 * of a binary resource object embedded in a story file
43 */
44 typedef struct resinfo resinfo;
45 struct resinfo
46 {
47 /* pointer and length of the data in the story file buffer */
48 const char *ptr;
49 int32 len;
50
51 /* tads major version (currently, 2 or 3) */
52 int tads_version;
53 };
54
55 /*
56 * Name/value pair list entry
57 */
58 typedef struct valinfo valinfo;
59 struct valinfo
60 {
61 const char *name;
62 size_t name_len;
63
64 /* value string */
65 char *val;
66 size_t val_len;
67
68 /* next entry in the list */
69 valinfo *nxt;
70 };
71
72
73 /* ------------------------------------------------------------------------ */
74 /*
75 * forward declarations
76 */
77
78 static valinfo *parse_sf_game_info(const void *story_file, int32 story_len,
79 int *version);
80 static valinfo *parse_game_info(const char *gi_file, int32 gi_len);
81 static int find_resource(const void *story_file, int32 story_len,
82 const char *resname, resinfo *info);
83 static int find_cover_art(const void *story_file, int32 story_len,
84 resinfo *resp, int32 *image_format,
85 int32 *width, int32 *height);
86 static int t2_find_res(const void *story_file, int32 story_len,
87 const char *resname, resinfo *info);
88 static int t3_find_res(const void *story_file, int32 story_len,
89 const char *resname, resinfo *info);
90 static valinfo *find_by_key(valinfo *list_head, const char *key);
91 static void delete_valinfo_list(valinfo *head);
92 static int32 generate_md5_ifid(void *story_file, int32 extent,
93 char *output, int32 output_extent);
94 static int32 synth_ifiction(valinfo *vals, int tads_version,
95 char *buf, int32 bufsize,
96 void *story_file, int32 extent);
97 static int get_png_dim(const void *img, int32 extent,
98 int32 *xout, int32 *yout);
99 static int get_jpeg_dim(const void *img, int32 extent,
100 int32 *xout, int32 *yout);
101
102
103
104 /* ------------------------------------------------------------------------ */
105 /*
106 * Get the IFID for a given story file.
107 */
108 int32 tads_get_story_file_IFID(void *story_file, int32 extent,
109 char *output, int32 output_extent)
110 {
111 valinfo *vals;
112
113 /* if we have GameInfo, try looking for an IFID there */
114 if ((vals = parse_sf_game_info(story_file, extent, 0)) != 0)
115 {
116 valinfo *val;
117 int found = 0;
118
119 /* find the "IFID" key */
120 if ((val = find_by_key(vals, "IFID")) != 0)
121 {
122 char *p;
123
124 /* copy the output as a null-terminated string */
125 ASSERT_OUTPUT_SIZE((int32)val->val_len + 1);
126 memcpy(output, val->val, val->val_len);
127 output[val->val_len] = '\0';
128
129 /*
130 * count up the IFIDs in the buffer - there might be more than
131 * one, separated by commas
132 */
133 for (found = 1, p = output ; *p != '\0' ; ++p)
134 {
135 /* if this is a comma, it delimits a new IFID */
136 if (*p == ',')
137 ++found;
138 }
139 }
140
141 /* delete the GameInfo list */
142 delete_valinfo_list(vals);
143
144 /* if we found an IFID, indicate how many results we found */
145 if (found != 0)
146 return found;
147 }
148
149 /*
150 * we didn't find an IFID in the GameInfo, so generate a default IFID
151 * using the MD5 method
152 */
153 return generate_md5_ifid(story_file, extent, output, output_extent);
154 }
155
156 /*
157 * Get the size of the ifiction metadata for the game
158 */
159 int32 tads_get_story_file_metadata_extent(void *story_file, int32 extent)
160 {
161 valinfo *vals;
162 int32 ret;
163 int ver;
164
165 /*
166 * First, make sure we have a GameInfo record. If we don't, simply
167 * indicate that there's no metadata to fetch.
168 */
169 if ((vals = parse_sf_game_info(story_file, extent, &ver)) == 0)
170 return NO_REPLY_RV;
171
172 /*
173 * Run the ifiction synthesizer with no output buffer, to calculate the
174 * size we need.
175 */
176 ret = synth_ifiction(vals, ver, 0, 0, story_file, extent);
177
178 /* delete the value list */
179 delete_valinfo_list(vals);
180
181 /* return the required size */
182 return ret;
183 }
184
185 /*
186 * Get the ifiction metadata for the game
187 */
188 int32 tads_get_story_file_metadata(void *story_file, int32 extent,
189 char *buf, int32 bufsize)
190 {
191 valinfo *vals;
192 int32 ret;
193 int ver;
194
195 /* make sure we have metadata to fetch */
196 if ((vals = parse_sf_game_info(story_file, extent, &ver)) == 0)
197 return NO_REPLY_RV;
198
199 /* synthesize the ifiction data into the output buffer */
200 ret = synth_ifiction(vals, ver, buf, bufsize, story_file, extent);
201
202 /* if that required more space than we had available, return an error */
203 if (ret > bufsize)
204 ret = INVALID_USAGE_RV;
205
206 /* delete the value list */
207 delete_valinfo_list(vals);
208
209 /* return the result */
210 return ret;
211 }
212
213 /*
214 * Extended interface: turn a GameInfo record into an iFiction record.
215 * Call with a null buffer and zero buffer len to figure the size of the
216 * output buffer required.
217 */
218 int32 xtads_gameinfo_to_ifiction(int tads_version,
219 const char *gi_txt, int32 gi_len,
220 char *buf, int32 bufsize)
221 {
222 valinfo *vals;
223 int32 ret;
224
225 /* make sure we have metadata to fetch */
226 if ((vals = parse_game_info(gi_txt, gi_len)) == 0)
227 return NO_REPLY_RV;
228
229 /* synthesize the ifiction data into the output buffer */
230 ret = synth_ifiction(vals, tads_version, buf, bufsize, 0, 0);
231
232 /* if that required more space than we had available, return an error */
233 if (bufsize != 0 && ret > bufsize)
234 ret = INVALID_USAGE_RV;
235
236 /* delete the value list */
237 delete_valinfo_list(vals);
238
239 /* return the result */
240 return ret;
241 }
242
243 /*
244 * Get the size of the cover art
245 */
246 int32 tads_get_story_file_cover_extent(void *story_file, int32 story_len)
247 {
248 resinfo res;
249
250 /* look for the cover art resource */
251 if (find_cover_art(story_file, story_len, &res, 0, 0, 0))
252 return res.len;
253 else
254 return NO_REPLY_RV;
255 }
256
257 /*
258 * Get the format of the cover art
259 */
260 int32 tads_get_story_file_cover_format(void *story_file, int32 story_len)
261 {
262 int32 typ;
263
264 /* look for CoverArt.jpg */
265 if (find_cover_art(story_file, story_len, 0, &typ, 0, 0))
266 return typ;
267 else
268 return NO_REPLY_RV;
269 }
270
271 /*
272 * Get the cover art data
273 */
274 int32 tads_get_story_file_cover(void *story_file, int32 story_len,
275 void *outbuf, int32 output_extent)
276 {
277 resinfo res;
278
279 /* look for CoverArt.jpg, then for CoverArt.png */
280 if (find_cover_art(story_file, story_len, &res, 0, 0, 0))
281 {
282 /* got it - copy the data to the buffer */
283 ASSERT_OUTPUT_SIZE(res.len);
284 memcpy(outbuf, res.ptr, res.len);
285
286 /* success */
287 return res.len;
288 }
289
290 /* otherwise, we didn't find it */
291 return NO_REPLY_RV;
292 }
293
294 /* ------------------------------------------------------------------------ */
295 /*
296 * Generate a default IFID using the MD5 hash method
297 */
298 static int32 generate_md5_ifid(void *story_file, int32 extent,
299 char *output, int32 output_extent)
300 {
301 md5_state_t md5;
302 unsigned char md5_buf[16];
303 char *p;
304 int i;
305
306 /* calculate the MD5 hash of the story file */
307 md5_init(&md5);
308 md5_append(&md5, story_file, extent);
309 md5_finish(&md5, md5_buf);
310
311 /* make sure we have room to store the result */
312 ASSERT_OUTPUT_SIZE(39);
313
314 /* the prefix is "TADS2-" or "TADS3-", depending on the format */
315 if (tads_match_sig(story_file, extent, T2_SIGNATURE))
316 strcpy(output, "TADS2-");
317 else
318 strcpy(output, "TADS3-");
319
320 /* the rest is the MD5 hash of the file, as hex digits */
321 for (i = 0, p = output + strlen(output) ; i < 16 ; p += 2, ++i)
322 sprintf(p, "%02X", md5_buf[i]);
323
324 /* indicate that we found one result */
325 return 1;
326 }
327
328 /* ------------------------------------------------------------------------ */
329 /*
330 * Some UTF-8 utility functions and macros. We use our own rather than the
331 * ctype.h macros because we're parsing UTF-8 text.
332 */
333
334 /* is c a space? */
335 #define u_isspace(c) ((unsigned char)(c) < 128 && isspace(c))
336
337 /* is c a horizontal space? */
338 #define u_ishspace(c) (u_isspace(c) && (c) != '\n' && (c) != '\r')
339
340 /* is-newline - matches \n, \r, and \u2028 */
341 static int u_isnl(const char *p, int32 len)
342 {
343 return (*p == '\n'
344 || *p == '\r'
345 || (len >= 3
346 && *(unsigned char *)p == 0xe2
347 && *(unsigned char *)(p+1) == 0x80
348 && *(unsigned char *)(p+2) == 0xa8));
349 }
350
351 /* skip to the next utf-8 character */
352 static void nextc(const char **p, int32 *len)
353 {
354 /* skip the first byte */
355 if (*len != 0)
356 {
357 ++*p;
358 --*len;
359 }
360 /* skip continuation bytes */
361 while (*len != 0 && (**p & 0xC0) == 0x80)
362 {
363 ++*p;
364 --*len;
365 }
366 }
367
368 /* skip to the previous utf-8 character */
369 static void prevc(const char **p, int32 *len)
370 {
371 /* move back one byte */
372 --*p; ++*len;
373
374 /* keep skipping as long as we're looking at continuation characters */
375 while ((**p & 0xC0) == 0x80)
376 {
377 --*p;
378 ++*len;
379 }
380 }
381
382 /*
383 * Skip a newline sequence. Skips all common conventions, including \n,
384 * \r, \n\r, \r\n, and \u2028.
385 */
386 static void skip_newline(const char **p, int32 *rem)
387 {
388 /* make sure we have something to skip */
389 if (*rem == 0)
390 return;
391
392 /* check what we have */
393 switch (**(const unsigned char **)p)
394 {
395 case '\n':
396 /* skip \n or \n\r */
397 nextc(p, rem);
398 if (**p == '\r')
399 nextc(p, rem);
400 break;
401
402 case '\r':
403 /* skip \r or \r\n */
404 nextc(p, rem);
405 if (**p == '\n')
406 nextc(p, rem);
407 break;
408
409 case 0xe2:
410 /* \u2028 (unicode line separator) - just skip the one character */
411 nextc(p, rem);
412 break;
413 }
414 }
415
416 /*
417 * Skip to the next line
418 */
419 static void skip_to_next_line(const char **p, int32 *rem)
420 {
421 /* look for the next newline */
422 for ( ; *rem != 0 ; nextc(p, rem))
423 {
424 /* if this is a newline of some kind, we're at the end of the line */
425 if (u_isnl(*p, *rem))
426 {
427 /* skip the newline, and we're done */
428 skip_newline(p, rem);
429 break;
430 }
431 }
432 }
433
434
435 /* ------------------------------------------------------------------------ */
436 /*
437 * ifiction synthesizer output context
438 */
439 typedef struct synthctx synthctx;
440 struct synthctx
441 {
442 /* the current output pointer */
443 char *buf;
444
445 /* the number of bytes remaining in the output buffer */
446 int32 buf_size;
447
448 /*
449 * the total number of bytes needed for the output (this might be more
450 * than we've actually written, since we count up the bytes required
451 * even if we need more space than the buffer provides)
452 */
453 int32 total_size;
454
455 /* the head of the name/value pair list from the parsed GameInfo */
456 valinfo *vals;
457 };
458
459 /* initialize a synthesizer context */
460 static void init_synthctx(synthctx *ctx, char *buf, int32 bufsize,
461 valinfo *vals)
462 {
463 /* set up at the beginning of the output buffer */
464 ctx->buf = buf;
465 ctx->buf_size = bufsize;
466
467 /* we haven't written anything to the output buffer yet */
468 ctx->total_size = 0;
469
470 /* remember the name/value pair list */
471 ctx->vals = vals;
472 }
473
474 /*
475 * Write out a chunk to a synthesized ifiction record, updating pointers
476 * and counters. We won't copy past the end of the buffer, but we'll
477 * continue counting the output length needed in any case.
478 */
479 static void write_ifiction(synthctx *ctx, const char *src, size_t srclen)
480 {
481 int32 copy_len;
482
483 /* copy as much as we can, up to the remaining buffer size */
484 copy_len = srclen;
485 if (copy_len > ctx->buf_size)
486 copy_len = ctx->buf_size;
487
488 /* do the copying, if any */
489 if (copy_len != 0)
490 {
491 /* copy the bytes */
492 memcpy(ctx->buf, src, (size_t)copy_len);
493
494 /* adjust the buffer pointer and output buffer size remaining */
495 ctx->buf += copy_len;
496 ctx->buf_size -= copy_len;
497 }
498
499 /* count this source data in the total size */
500 ctx->total_size += srclen;
501 }
502
503 /* write a null-terminated chunk to the synthesized ifiction record */
504 static void write_ifiction_z(synthctx *ctx, const char *src)
505 {
506 write_ifiction(ctx, src, strlen(src));
507 }
508
509 /*
510 * Write a PCDATA string to the synthesized ifiction record. In
511 * particular, we rewrite '<', '>', and '&' as '&lt;', '&gt;', and '&amp;',
512 * respectively; we trim off leading and trailing spaces; and we compress
513 * each run of whitespace down to a single \u0020 (' ') character.
514 *
515 * If 'desc' is TRUE, it means that we're writing Description contents, in
516 * which case we convert \n to <br/>.
517 */
518 static void write_ifiction_pcdata(synthctx *ctx, const char *p, size_t len,
519 int desc)
520 {
521 /* first, skip any leading whitespace */
522 for ( ; len != 0 && u_ishspace(*p) ; ++p, --len) ;
523
524 /* keep going until we run out of string */
525 for (;;)
526 {
527 const char *start;
528
529 /* scan to the next whitespace or markup-significant character */
530 for (start = p ;
531 len != 0 && !u_ishspace(*p)
532 && *p != '<' && *p != '>' && *p != '&' && *p != '\\' ;
533 ++p, --len) ;
534
535 /* write the part up to here */
536 if (p != start)
537 write_ifiction(ctx, start, p - start);
538
539 /* if we've reached the end of the string, we can stop */
540 if (len == 0)
541 break;
542
543 /* check what stopped us */
544 switch (*p)
545 {
546 case '<':
547 write_ifiction_z(ctx, "&lt;");
548 ++p;
549 --len;
550 break;
551
552 case '>':
553 write_ifiction_z(ctx, "&gt;");
554 ++p;
555 --len;
556 break;
557
558 case '&':
559 write_ifiction_z(ctx, "&amp;");
560 ++p;
561 --len;
562 break;
563
564 case '\\':
565 /* skip the '\\' */
566 ++p;
567 --len;
568
569 /* in Description fields, \n becomes <br/> */
570 if (len > 0 && *p == 'n')
571 {
572 /* write the translation */
573 write_ifiction_z(ctx, "<br/>");
574
575 /* skip the 'n' */
576 ++p;
577 --len;
578 }
579 else if (len > 1 && *(p+1) == '\\')
580 {
581 /* '\\' is just a single '\' */
582 write_ifiction_z(ctx, "\\");
583
584 /* skip the second '\' */
585 ++p;
586 --len;
587 }
588 else
589 {
590 /* no 'n' after the '\', so it's just a backslash */
591 write_ifiction_z(ctx, "\\");
592 }
593 break;
594
595 default:
596 /*
597 * The only other thing that could have stopped us is
598 * whitespace. Skip all consecutive whitespace.
599 */
600 for ( ; len != 0 && u_ishspace(*p) ; ++p, --len);
601
602 /*
603 * if that's not the end of the string, replace the run of
604 * whitespace with a single space character in the output; if
605 * we've reached the end of the string, we don't even want to
606 * do that, since we want to trim off trailing spaces
607 */
608 if (len != 0)
609 write_ifiction_z(ctx, " ");
610 break;
611 }
612 }
613 }
614
615 /*
616 * Translate a GameInfo keyed value to the corresponding ifiction tagged
617 * value. We find the GameInfo value keyed by 'gameinfo_key', and write
618 * out the same string under the ifiction XML tag 'ifiction_tag'. We write
619 * a complete XML container sequence - <tag>value</tag>.
620 *
621 * If the given GameInfo key doesn't exist, we use the default value string
622 * 'dflt', if given. If the GameInfo key doesn't exist and 'dflt' is null,
623 * we don't write anything - we don't even write the open/close tags.
624 *
625 * If 'html' is true, we assume the value is in html format, and we write
626 * it untranslated. Otherwise, we write it as PCDATA, translating markup
627 * characters into '&' entities and compressing whitespace.
628 */
629 static void write_ifiction_xlat_base(synthctx *ctx, int indent,
630 const char *gameinfo_key,
631 const char *ifiction_tag,
632 const char *dflt, int html, int desc)
633 {
634 valinfo *val;
635 const char *valstr;
636 size_t vallen;
637
638 /* look up the GameInfo key */
639 if ((val = find_by_key(ctx->vals, gameinfo_key)) != 0)
640 {
641 /* we found the GameInfo value - use it */
642 valstr = val->val;
643 vallen = val->val_len;
644 }
645 else if (dflt != 0)
646 {
647 /* the GameInfo value doesn't exist, but we have a default - use it */
648 valstr = dflt;
649 vallen = strlen(dflt);
650 }
651 else
652 {
653 /* there's no GameInfo value and no default, so write nothing */
654 return;
655 }
656
657 /* write the indentation */
658 while (indent != 0)
659 {
660 static const char spaces[] = " ";
661 size_t cur;
662
663 /* figure how much we can write on this round */
664 cur = indent;
665 if (cur > sizeof(spaces) - 1)
666 cur = sizeof(spaces) - 1;
667
668 /* write it */
669 write_ifiction(ctx, spaces, cur);
670
671 /* deduct it from the amount remaining */
672 indent -= cur;
673 }
674
675 /* write the open tag */
676 write_ifiction_z(ctx, "<");
677 write_ifiction_z(ctx, ifiction_tag);
678 write_ifiction_z(ctx, ">");
679
680 /* write the value, applying pcdata translations */
681 if (html)
682 write_ifiction(ctx, valstr, vallen);
683 else
684 write_ifiction_pcdata(ctx, valstr, vallen, desc);
685
686 /* write the close tag */
687 write_ifiction_z(ctx, "</");
688 write_ifiction_z(ctx, ifiction_tag);
689 write_ifiction_z(ctx, ">\n");
690 }
691
692 #define write_ifiction_xlat(ctx, indent, gikey, iftag, dflt) \
693 write_ifiction_xlat_base(ctx, indent, gikey, iftag, dflt, FALSE, FALSE)
694
695 #define write_ifiction_xlat_html(ctx, indent, gikey, iftag, dflt) \
696 write_ifiction_xlat_base(ctx, indent, gikey, iftag, dflt, TRUE, FALSE)
697
698 #define write_ifiction_xlat_desc(ctx, indent, gikey, iftag, dflt) \
699 write_ifiction_xlat_base(ctx, indent, gikey, iftag, dflt, FALSE, TRUE)
700
701
702 /*
703 * Retrieve the next author name from the GameInfo "Author" format. The
704 * format is as follows:
705 *
706 * name <email> <email>... ; ...
707 *
708 * That is, each author is listed with a name followed by one or more email
709 * addresses in angle brackets, and multiple authors are separated by
710 * semicolons.
711 */
712 static int scan_author_name(const char **p, size_t *len,
713 const char **start, const char **end)
714 {
715 /* keep going until we find a non-empty author name */
716 for (;;)
717 {
718 /* skip leading spaces */
719 for ( ; *len != 0 && u_ishspace(**p) ; ++*p, --*len) ;
720
721 /* if we ran out of string, there's definitely no author name */
722 if (*len == 0)
723 return FALSE;
724
725 /*
726 * Find the end of this author name. The author name ends at the
727 * next semicolon or angle bracket.
728 */
729 for (*start = *p ; *len != 0 && **p != ';' && **p != '<' ;
730 ++*p, --*len) ;
731
732 /* trim off any trailing spaces */
733 for (*end = *p ; *end > *start && u_ishspace(*(*end - 1)) ; --*end) ;
734
735 /* now skip any email addresses */
736 while (*len != 0 && **p == '<')
737 {
738 /* skip to the closing bracket */
739 for (++*p, --*len ; *len != 0 && **p != '>' ; ++*p, --*len) ;
740
741 /* skip the bracket */
742 if (*len != 0)
743 {
744 ++*p;
745 --*len;
746 }
747 /* skip whitespace */
748 for ( ; *len != 0 && u_ishspace(**p) ; ++*p, --*len) ;
749
750 /*
751 * if we're not at a semicolon, another angle bracket, or the
752 * end of the string, it's a syntax error
753 */
754 if (*len != 0 && **p != '<' && **p != ';')
755 {
756 *len = 0;
757 return FALSE;
758 }
759 }
760
761 /* if we're at a semicolon, skip it */
762 if (*len != 0 && **p == ';')
763 {
764 ++*p;
765 --*len;
766 }
767 /*
768 * if we found a non-empty name, return it; otherwise, continue on
769 * to the next semicolon section
770 */
771 if (*end != *start)
772 return TRUE;
773 }
774 }
775
776
777 /*
778 * Synthesize an ifiction record for the given GameInfo name/value pair
779 * list. Returns the number of bytes required for the result, including
780 * null termination. We'll copy as much as we can to the output buffer, up
781 * to bufsize; if the buffer size is insufficient to hold the result, we'll
782 * still indicate the length needed for the full result, but we're careful
783 * not to actually copy anything past the end of the buffer.
784 */
785 static int32 synth_ifiction(valinfo *vals, int tads_version,
786 char *buf, int32 bufsize,
787 void *story_file, int32 extent)
788 {
789 char default_ifid[TREATY_MINIMUM_EXTENT];
790 valinfo *ifid = find_by_key(vals, "IFID");
791 const char *ifid_val;
792 size_t ifid_len;
793 valinfo *author = find_by_key(vals, "AuthorEmail");
794 valinfo *url = find_by_key(vals, "Url");
795 synthctx ctx;
796 const char *p;
797 size_t rem;
798 int32 art_fmt;
799 int32 art_wid, art_ht;
800 const char *format_id = 0;
801
802 /* initialize the output content */
803 init_synthctx(&ctx, buf, bufsize, vals);
804
805 /* make sure the tads version is one we know how to handle */
806 if (tads_version == 2)
807 format_id = "tads2";
808 else if (tads_version == 3)
809 format_id = "tads3";
810 else
811 return NO_REPLY_RV;
812
813 /*
814 * The IFID is mandatory. If there's not an IFID specifically listed
815 * in the GameInfo, we need to generate the default IFID based on the
816 * MD5 hash of the game file.
817 */
818 if (ifid != 0)
819 {
820 /* use the explicit IFID(s) listed in the GameInfo */
821 ifid_val = ifid->val;
822 ifid_len = ifid->val_len;
823 }
824 else if (story_file != 0)
825 {
826 /* generate the default IFID */
827 generate_md5_ifid(story_file, extent,
828 default_ifid, TREATY_MINIMUM_EXTENT);
829
830 /* use this as the IFID */
831 ifid_val = default_ifid;
832 ifid_len = strlen(default_ifid);
833 }
834 else
835 {
836 return NO_REPLY_RV;
837 }
838
839 /* write the header, and start the <identification> section */
840 write_ifiction_z(
841 &ctx,
842 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
843 "<ifindex version=\"1.0\" "
844 "xmlns=\"http://babel.ifarchive.org/protocol/iFiction/\">\n"
845 " <!-- Bibliographic data translated from TADS GameInfo -->\n"
846 " <story>\n"
847 " <colophon>\n"
848 " <generator>Babel</generator>\n"
849 " <generatorversion>" TREATY_VERSION "</generatorversion>\n"
850 " <originated>2006-04-14</originated>\n"
851 " </colophon>\n"
852 " <identification>\n");
853
854 /* write each IFID (there might be several) */
855 for (p = ifid_val, rem = ifid_len ; rem != 0 ; )
856 {
857 const char *start;
858 const char *end;
859
860 /* skip leading spaces */
861 for ( ; rem != 0 && u_ishspace(*p) ; ++p, --rem) ;
862
863 /* find the end of this IFID */
864 for (start = p ; rem != 0 && *p != ',' ; ++p, --rem) ;
865
866 /* remove trailing spaces */
867 for (end = p ; end > start && u_ishspace(*(end-1)) ; --end) ;
868
869 /* if we found one, write it out */
870 if (end != start)
871 {
872 write_ifiction_z(&ctx, " <ifid>");
873 write_ifiction(&ctx, start, end - start);
874 write_ifiction_z(&ctx, "</ifid>\n");
875 }
876
877 /* skip the comma */
878 if (rem != 0 && *p == ',')
879 {
880 ++p;
881 --rem;
882 }
883 }
884
885 /* add the format information */
886 write_ifiction_z(&ctx, " <format>");
887 write_ifiction_z(&ctx, format_id);
888 write_ifiction_z(&ctx, "</format>\n");
889
890 /* close the <identification> section and start the <bibliographic> */
891 write_ifiction_z(&ctx,
892 " </identification>\n"
893 " <bibliographic>\n");
894
895 /* write the various bibliographic data */
896 write_ifiction_xlat(&ctx, 6, "Name", "title", "An Interactive Fiction");
897 write_ifiction_xlat(&ctx, 6, "Headline", "headline", 0);
898 write_ifiction_xlat_desc(&ctx, 6, "Desc", "description", 0);
899 write_ifiction_xlat(&ctx, 6, "Genre", "genre", 0);
900 write_ifiction_xlat(&ctx, 6, "Forgiveness", "forgiveness", 0);
901 write_ifiction_xlat(&ctx, 6, "Series", "series", 0);
902 write_ifiction_xlat(&ctx, 6, "SeriesNumber", "seriesnumber", 0);
903 write_ifiction_xlat(&ctx, 6, "Language", "language", 0);
904 write_ifiction_xlat(&ctx, 6, "FirstPublished", "firstpublished", 0);
905
906 /* if there's an author, write the list of author names */
907 if (author != 0)
908 {
909 int cnt;
910 int i;
911 const char *start;
912 const char *end;
913
914 /* start the <author> tag */
915 write_ifiction_z(&ctx, " <author>");
916
917 /*
918 * first, count up the number of authors - authors are separated by
919 * semicolons, so there's one more author than there are semicolons
920 */
921 for (p = author->val, rem = author->val_len, cnt = 1 ;
922 scan_author_name(&p, &rem, &start, &end) ; ) ;
923
924 /*
925 * Now generate the list of authors. If there are multiple
926 * authors, use commas to separate them.
927 */
928 for (p = author->val, rem = author->val_len, i = 0 ; ; ++i)
929 {
930 /* scan this author's name */
931 if (!scan_author_name(&p, &rem, &start, &end))
932 break;
933
934 /* write out this author name */
935 write_ifiction_pcdata(&ctx, start, end - start, FALSE);
936
937 /* if there's another name to come, write a separator */
938 if (i + 1 < cnt)
939 {
940 /*
941 * write just "and" to separate two items; write ","
942 * between items in lists of more than two, with ",and"
943 * between the last two items
944 */
945 write_ifiction_z(&ctx,
946 cnt == 2 ? " and " :
947 i + 2 < cnt ? ", " : ", and ");
948 }
949 }
950
951 /* end the <author> tag */
952 write_ifiction_z(&ctx, "</author>\n");
953 }
954 else
955 write_ifiction_z(&ctx, " <author>Anonymous</author>\n");
956
957 /* end the biblio section */
958 write_ifiction_z(&ctx, " </bibliographic>\n");
959
960 /* if there's cover art, add its information */
961 if (story_file != 0
962 && find_cover_art(story_file, extent, 0, &art_fmt, &art_wid, &art_ht)
963 && (art_fmt == PNG_COVER_FORMAT || art_fmt == JPEG_COVER_FORMAT))
964 {
965 char buf[200];
966
967 sprintf(buf,
968 " <cover>\n"
969 " <format>%s</format>\n"
970 " <height>%lu</height>\n"
971 " <width>%lu</width>\n"
972 " </cover>\n",
973 art_fmt == PNG_COVER_FORMAT ? "png" : "jpg",
974 (long)art_ht, (long)art_wid);
975
976 write_ifiction_z(&ctx, buf);
977 }
978
979 /* if there's an author email, include it */
980 if (author != 0 || url != 0)
981 {
982 const char *p;
983 size_t rem;
984 int i;
985
986 /* open the section */
987 write_ifiction_z(&ctx, " <contacts>\n");
988
989 /* add the author email, if provided */
990 if (author != 0)
991 {
992 /* write the email list */
993 for (i = 0, p = author->val, rem = author->val_len ; ; ++i)
994 {
995 const char *start;
996
997 /* skip to the next email address */
998 for ( ; rem != 0 && *p != '<' ; ++p, --rem) ;
999
1000 /* if we didn't find an email address, we're done */
1001 if (rem == 0)
1002 break;
1003
1004 /* find the matching '>' */
1005 for (++p, --rem, start = p ; rem != 0 && *p != '>' ;
1006 ++p, --rem) ;
1007
1008 /*
1009 * if this is the first one, open the section; otherwise,
1010 * add a comma
1011 */
1012 if (i == 0)
1013 write_ifiction_z(&ctx, " <authoremail>");
1014 else
1015 write_ifiction_z(&ctx, ",");
1016
1017 /* write this address */
1018 write_ifiction(&ctx, start, p - start);
1019
1020 /*
1021 * skip the closing bracket, if there is one; if we're out
1022 * of string, we're done
1023 */
1024 if (rem != 0)
1025 {
1026 ++p;
1027 --rem;
1028 }
1029 else
1030 break;
1031 }
1032
1033 /* if we found any emails to write, end the section */
1034 if (i != 0)
1035 write_ifiction_z(&ctx, "</authoremail>\n");
1036 }
1037
1038 /* if there's a URL, add it */
1039 if (url != 0)
1040 {
1041 write_ifiction_z(&ctx, " <url>");
1042 write_ifiction(&ctx, url->val, url->val_len);
1043 write_ifiction_z(&ctx, "</url>\n");
1044 }
1045
1046 /* close the section */
1047 write_ifiction_z(&ctx, " </contacts>\n");
1048 }
1049
1050 /* add the tads-specific section */
1051 write_ifiction_z(&ctx, " <");
1052 write_ifiction_z(&ctx, format_id);
1053 write_ifiction_z(&ctx, ">\n");
1054
1055 write_ifiction_xlat(&ctx, 6, "Version", "version", 0);
1056 write_ifiction_xlat(&ctx, 6, "ReleaseDate", "releasedate", 0);
1057 write_ifiction_xlat(&ctx, 6, "PresentationProfile",
1058 "presentationprofile", 0);
1059 write_ifiction_xlat(&ctx, 6, "Byline", "byline", 0);
1060
1061 write_ifiction_z(&ctx, " </");
1062 write_ifiction_z(&ctx, format_id);
1063 write_ifiction_z(&ctx, ">\n");
1064
1065 /* close the story section and the main body */
1066 write_ifiction_z(&ctx, " </story>\n</ifindex>\n");
1067
1068 /* add the null terminator */
1069 write_ifiction(&ctx, "", 1);
1070
1071 /* return the total output size */
1072 return ctx.total_size;
1073 }
1074
1075 /* ------------------------------------------------------------------------ */
1076 /*
1077 * Check a data block to see if it starts with the given signature.
1078 */
1079 int tads_match_sig(const void *buf, int32 len, const char *sig)
1080 {
1081 /* note the length of the signature string */
1082 size_t sig_len = strlen(sig);
1083
1084 /* if matches if the buffer starts with the signature string */
1085 return (len >= (int32)sig_len && memcmp(buf, sig, sig_len) == 0);
1086 }
1087
1088
1089 /* ------------------------------------------------------------------------ */
1090 /*
1091 * portable-to-native format conversions
1092 */
1093 #define osbyte(p, ofs) \
1094 (*(((unsigned char *)(p)) + (ofs)))
1095
1096 #define osrp1(p) \
1097 ((unsigned int)osbyte(p, 0))
1098
1099 #define osrp2(p) \
1100 ((unsigned int)osbyte(p, 0) \
1101 + ((unsigned int)osbyte(p, 1) << 8))
1102
1103 #define osrp4(p) \
1104 (((unsigned long)osbyte(p, 0)) \
1105 + (((unsigned long)osbyte(p, 1)) << 8) \
1106 + (((unsigned long)osbyte(p, 2)) << 16) \
1107 + (((unsigned long)osbyte(p, 3)) << 24))
1108
1109
1110 /* ------------------------------------------------------------------------ */
1111 /*
1112 * Parse a story file and retrieve the GameInfo data. Returns the head of
1113 * a linked list of valinfo entries.
1114 */
1115 static valinfo *parse_sf_game_info(const void *story_file, int32 story_len,
1116 int *tads_version)
1117 {
1118 resinfo res;
1119
1120 /*
1121 * first, find the GameInfo resource - if it's not there, there's no
1122 * game information to parse
1123 */
1124 if (!find_resource(story_file, story_len, "GameInfo.txt", &res))
1125 return 0;
1126
1127 /* if the caller wants the TADS version number, hand it back */
1128 if (tads_version != 0)
1129 *tads_version = res.tads_version;
1130
1131 /* parse the GameInfo record */
1132 return parse_game_info(res.ptr, res.len);
1133 }
1134
1135 /* ------------------------------------------------------------------------ */
1136 /*
1137 * Parse a GameInfo text record
1138 */
1139 static valinfo *parse_game_info(const char *ptr, int32 len)
1140 {
1141 const char *p;
1142 int32 rem;
1143 valinfo *val_head = 0;
1144
1145 /* parse the data */
1146 for (p = ptr, rem = len ; rem != 0 ; )
1147 {
1148 const char *name_start;
1149 size_t name_len;
1150 const char *val_start;
1151 valinfo *val;
1152 const char *inp;
1153 int32 inlen;
1154 char *outp;
1155
1156 /* skip any leading whitespace */
1157 while (rem != 0 && u_isspace(*p))
1158 {
1159 ++p;
1160 --rem;
1161 }
1162
1163 /* if the line starts with '#', it's a comment, so skip it */
1164 if (rem != 0 && *p == '#')
1165 {
1166 skip_to_next_line(&p, &rem);
1167 continue;
1168 }
1169
1170 /* we must have the start of a name - note it */
1171 name_start = p;
1172
1173 /* skip ahead to a space or colon */
1174 while (rem != 0 && *p != ':' && !u_ishspace(*p))
1175 nextc(&p, &rem);
1176
1177 /* note the length of the name */
1178 name_len = p - name_start;
1179
1180 /* skip any whitespace before the presumed colon */
1181 while (rem != 0 && u_ishspace(*p))
1182 nextc(&p, &rem);
1183
1184 /* if we're not at a colon, the line is ill-formed, so skip it */
1185 if (rem == 0 || *p != ':')
1186 {
1187 /* skip the entire line, and go back for the next one */
1188 skip_to_next_line(&p, &rem);
1189 continue;
1190 }
1191
1192 /* skip the colon and any whitespace immediately after it */
1193 for (nextc(&p, &rem) ; rem != 0 && u_ishspace(*p) ; nextc(&p, &rem)) ;
1194
1195 /* note where the value starts */
1196 val_start = p;
1197
1198 /*
1199 * Scan the value to get its length. The value runs from here to
1200 * the next newline that's not followed immediately by a space.
1201 */
1202 while (rem != 0)
1203 {
1204 const char *nl;
1205 int32 nlrem;
1206
1207 /* skip to the next line */
1208 skip_to_next_line(&p, &rem);
1209
1210 /* if we're at eof, we can stop now */
1211 if (rem == 0)
1212 break;
1213
1214 /* note where this line starts */
1215 nl = p;
1216 nlrem = rem;
1217
1218 /*
1219 * if we're at a non-whitespace character, it's definitely not
1220 * a continuation line
1221 */
1222 if (!u_ishspace(*p))
1223 break;
1224
1225 /*
1226 * check for spaces followed by a non-space character - this
1227 * would signify a continuation line
1228 */
1229 for ( ; rem != 0 && u_ishspace(*p) ; nextc(&p, &rem)) ;
1230 if (rem == 0 || u_isnl(p, rem))
1231 {
1232 /*
1233 * we're at end of file, we found a line with nothing but
1234 * whitespace, so this isn't a continuation line; go back
1235 * to the start of this line and end the value here
1236 */
1237 p = nl;
1238 rem = nlrem;
1239 break;
1240 }
1241
1242 /*
1243 * We found whitespace followed by non-whitespace, so this is a
1244 * continuation line. Keep going for now.
1245 */
1246 }
1247
1248 /* remove any trailing newlines */
1249 while (p > val_start)
1250 {
1251 /* move back one character */
1252 prevc(&p, &rem);
1253
1254 /*
1255 * if it's a newline, keep going; otherwise, keep this
1256 * character and stop trimming
1257 */
1258 if (!u_isnl(p, rem))
1259 {
1260 nextc(&p, &rem);
1261 break;
1262 }
1263 }
1264
1265 /*
1266 * Allocate a new value entry. Make room for the entry itself plus
1267 * a copy of the value. We don't need to make a copy of the name,
1268 * since we can just use the original copy from the story file
1269 * buffer. We do need a copy of the value because we might need to
1270 * transform it slightly, to remove newlines and leading spaces on
1271 * continuation lines.
1272 */
1273 val = (valinfo *)malloc(sizeof(valinfo) + (p - val_start));
1274
1275 /* link it into our list */
1276 val->nxt = val_head;
1277 val_head = val;
1278
1279 /* point the name directly to the name in the buffer */
1280 val->name = name_start;
1281 val->name_len = name_len;
1282
1283 /* point the value to the space allocated along with the valinfo */
1284 val->val = (char *)(val + 1);
1285
1286 /* store the name, removing newlines and continuation-line spaces */
1287 for (outp = val->val, inp = val_start, inlen = p - val_start ;
1288 inlen != 0 ; )
1289 {
1290 const char *l;
1291
1292 /* find the next newline */
1293 for (l = inp ; inlen != 0 && !u_isnl(inp, inlen) ;
1294 nextc(&inp, &inlen)) ;
1295
1296 /* copy this line to the output */
1297 memcpy(outp, l, inp - l);
1298 outp += inp - l;
1299
1300 /* if we're out of input, we're done */
1301 if (inlen == 0)
1302 break;
1303
1304 /* we're at a newline: replace it with a space in the output */
1305 *outp++ = ' ';
1306
1307 /* skip the newline and subsequent whitespace in the input */
1308 for (skip_newline(&inp, &inlen) ;
1309 inlen != 0 && u_ishspace(*inp) ; nextc(&inp, &inlen)) ;
1310 }
1311
1312 /* set the length of the parsed value */
1313 val->val_len = outp - val->val;
1314
1315 /* skip to the next line and continue parsing */
1316 skip_to_next_line(&p, &rem);
1317 }
1318
1319 /* return the head of the linked list of value entries */
1320 return val_head;
1321 }
1322
1323 /* ------------------------------------------------------------------------ */
1324 /*
1325 * Portable memicmp implementation
1326 */
1327 static int tmemicmp(const char *a, const char *b, size_t len)
1328 {
1329 /* scan each character */
1330 for ( ; len != 0 ; ++a, ++b, --len)
1331 {
1332 /* get the lower-case version of each current character */
1333 char ca = isupper(*a) ? tolower(*a) : *a;
1334 char cb = isupper(*b) ? tolower(*b) : *b;
1335
1336 /* check for mismatch */
1337 if (ca < cb)
1338 return -1;
1339 else if (ca > cb)
1340 return 1;
1341 }
1342
1343 /* all bytes match */
1344 return 0;
1345 }
1346
1347 /* ------------------------------------------------------------------------ */
1348 /*
1349 * Given a valinfo list obtained from parse_game_info(), find the value for
1350 * the given key
1351 */
1352 static valinfo *find_by_key(valinfo *list_head, const char *key)
1353 {
1354 valinfo *p;
1355 size_t key_len = strlen(key);
1356
1357 /* scan the list for the given key */
1358 for (p = list_head ; p != 0 ; p = p->nxt)
1359 {
1360 /* if this one matches the key we're looking for, return it */
1361 if (p->name_len == key_len && tmemicmp(p->name, key, key_len) == 0)
1362 return p;
1363 }
1364
1365 /* no luck */
1366 return 0;
1367 }
1368
1369 /* ------------------------------------------------------------------------ */
1370 /*
1371 * Delete a valinfo list obtained from parse_game_info()
1372 */
1373 static void delete_valinfo_list(valinfo *head)
1374 {
1375 /* keep going until we run out of entries */
1376 while (head != 0)
1377 {
1378 /* remember the next entry, before we delete this one */
1379 valinfo *nxt = head->nxt;
1380
1381 /* delete this one */
1382 free(head);
1383
1384 /* move on to the next one */
1385 head = nxt;
1386 }
1387 }
1388
1389 /* ------------------------------------------------------------------------ */
1390 /*
1391 * Find the cover art resource. We'll look for .system/CoverArt.jpg and
1392 * .system/CoverArt.png, in that order.
1393 */
1394 static int find_cover_art(const void *story_file, int32 story_len,
1395 resinfo *resp, int32 *image_format,
1396 int32 *width, int32 *height)
1397 {
1398 resinfo res;
1399 int32 x, y;
1400
1401 /* if they didn't want the resource info, provide a placeholder */
1402 if (resp == 0)
1403 resp = &res;
1404
1405 /* look for .system/CoverArt.jpg first */
1406 if (find_resource(story_file, story_len, ".system/CoverArt.jpg", resp))
1407 {
1408 /* get the width and height */
1409 if (!get_jpeg_dim(resp->ptr, resp->len, &x, &y))
1410 return FALSE;
1411
1412 /* hand back the width and height if it was requested */
1413 if (width != 0)
1414 *width = x;
1415 if (height != 0)
1416 *height = y;
1417
1418 /* tell them it's a JPEG image */
1419 if (image_format != 0)
1420 *image_format = JPEG_COVER_FORMAT;
1421
1422 /* indicate success */
1423 return TRUE;
1424 }
1425
1426 /* look for .system/CoverArt.png second */
1427 if (find_resource(story_file, story_len, ".system/CoverArt.png", resp))
1428 {
1429 /* get the width and height */
1430 if (!get_png_dim(resp->ptr, resp->len, &x, &y))
1431 return FALSE;
1432
1433 /* hand back the width and height if it was requested */
1434 if (width != 0)
1435 *width = x;
1436 if (height != 0)
1437 *height = y;
1438
1439 /* tell them it's a PNG image */
1440 if (image_format != 0)
1441 *image_format = PNG_COVER_FORMAT;
1442
1443 /* indicate success */
1444 return TRUE;
1445 }
1446
1447 /* didn't find it */
1448 return FALSE;
1449 }
1450
1451 /* ------------------------------------------------------------------------ */
1452 /*
1453 * Find a resource in a TADS 2 or 3 story file that's been loaded into
1454 * memory. On success, fills in the offset and size of the resource and
1455 * returns TRUE; if the resource isn't found, returns FALSE.
1456 */
1457 static int find_resource(const void *story_file, int32 story_len,
1458 const char *resname, resinfo *info)
1459 {
1460 /* if there's no file, there's no resource */
1461 if (story_file == 0)
1462 return FALSE;
1463
1464 /* check for tads 2 */
1465 if (tads_match_sig(story_file, story_len, T2_SIGNATURE))
1466 {
1467 info->tads_version = 2;
1468 return t2_find_res(story_file, story_len, resname, info);
1469 }
1470
1471 /* check for tads 3 */
1472 if (tads_match_sig(story_file, story_len, T3_SIGNATURE))
1473 {
1474 info->tads_version = 3;
1475 return t3_find_res(story_file, story_len, resname, info);
1476 }
1477
1478 /* it's not one of ours */
1479 return FALSE;
1480 }
1481
1482 /* ------------------------------------------------------------------------ */
1483 /*
1484 * Find a resource in a tads 2 game file
1485 */
1486 static int t2_find_res(const void *story_file, int32 story_len,
1487 const char *resname, resinfo *info)
1488 {
1489 const char *basep = (const char *)story_file;
1490 const char *endp = basep + story_len;
1491 const char *p;
1492 size_t resname_len;
1493
1494 /* note the length of the name we're seeking */
1495 resname_len = strlen(resname);
1496
1497 /*
1498 * skip past the tads 2 file header (13 bytes for the signature, 7
1499 * bytes for the version header, 2 bytes for the flags, 26 bytes for
1500 * the timestamp)
1501 */
1502 p = basep + 13 + 7 + 2 + 26;
1503
1504 /*
1505 * scan the sections in the file; stop on $EOF, and skip everything
1506 * else but HTMLRES, which is the section type that
1507 */
1508 while (p < endp)
1509 {
1510 unsigned long endofs;
1511
1512 /*
1513 * We're pointing to a section block header, which looks like this:
1514 *
1515 *. <byte> type-length
1516 *. <byte * type-length> type-name
1517 *. <uint32> next-section-address
1518 */
1519
1520 /* read the ending offset */
1521 endofs = osrp4(p + 1 + osrp1(p));
1522
1523 /* check the type */
1524 if (p[0] == 7 && memcmp(p + 1, "HTMLRES", 7) == 0)
1525 {
1526 unsigned long found_ofs;
1527 int found;
1528 unsigned long entry_cnt;
1529
1530 /* we haven't found the resource yet */
1531 found = FALSE;
1532
1533 /*
1534 * It's a multimedia resource block. Skip the section block
1535 * header and look at the index table - the index table
1536 * consists of a uint32 giving the number of entries, followed
1537 * by a reserved uint32, followed by the entries.
1538 */
1539 p += 12;
1540 entry_cnt = osrp4(p);
1541
1542 /* skip to the first index entry */
1543 p += 8;
1544
1545 /* scan the index entries */
1546 for ( ; entry_cnt != 0 ; --entry_cnt)
1547 {
1548 unsigned long res_ofs;
1549 unsigned long res_siz;
1550 size_t name_len;
1551
1552 /*
1553 * We're at the next index entry, which looks like this:
1554 *
1555 *. <uint32> resource-address (bytes from end of index)
1556 *. <uint32> resource-length (in bytes)
1557 *. <uint2> name-length
1558 *. <byte * name-length> name
1559 */
1560 res_ofs = osrp4(p);
1561 res_siz = osrp4(p + 4);
1562 name_len = osrp2(p + 8);
1563 p += 10;
1564
1565 /* check for a match to the name we're looking for */
1566 if (name_len == resname_len
1567 && tmemicmp(resname, p, name_len) == 0)
1568 {
1569 /*
1570 * it's the one we want - note its resource location
1571 * and size, but keep scanning for now, since we need
1572 * to find the end of the index before we'll know where
1573 * the actual resources begin
1574 */
1575 found = TRUE;
1576 found_ofs = res_ofs;
1577 info->len = res_siz;
1578 }
1579
1580 /* skip this one's name */
1581 p += name_len;
1582 }
1583
1584 /*
1585 * if we found our resource, the current seek position is the
1586 * base of the offset we found in the directory; so we can
1587 * finally fix up the offset to give the actual file location
1588 * and return the result
1589 */
1590 if (found)
1591 {
1592 /* fix up the offset with the actual file location */
1593 info->ptr = p + found_ofs;
1594
1595 /* tell the caller we found it */
1596 return TRUE;
1597 }
1598 }
1599 else if (p[0] == 4 && memcmp(p + 1, "$EOF", 4) == 0)
1600 {
1601 /*
1602 * that's the end of the file - we've finished without finding
1603 * the resource, so return failure
1604 */
1605 return FALSE;
1606 }
1607
1608 /* move to the next section */
1609 p = basep + endofs;
1610 }
1611
1612 /*
1613 * reached EOF without an $EOF marker - file must be corrupted; return
1614 * 'not found'
1615 */
1616 return FALSE;
1617 }
1618
1619 /* ------------------------------------------------------------------------ */
1620 /*
1621 * Find a resource in a T3 image file
1622 */
1623 static int t3_find_res(const void *story_file, int32 story_len,
1624 const char *resname, resinfo *info)
1625 {
1626 const char *basep = (const char *)story_file;
1627 const char *endp = basep + story_len;
1628 const char *p;
1629 size_t resname_len;
1630
1631 /* note the length of the name we're seeking */
1632 resname_len = strlen(resname);
1633
1634 /*
1635 * skip the file header - 11 bytes for the signature, 2 bytes for the
1636 * format version, 32 reserved bytes, and 24 bytes for the timestamp
1637 */
1638 p = basep + 11 + 2 + 32 + 24;
1639
1640 /* scan the data blocks */
1641 while (p < endp)
1642 {
1643 unsigned long siz;
1644
1645 /*
1646 * We're at the next block header, which looks like this:
1647 *
1648 *. <byte * 4> type-name
1649 *. <uint32> block-size
1650 *. <uint16> flags
1651 */
1652
1653 /* get the block size */
1654 siz = osrp4(p + 4);
1655
1656 /* check the type */
1657 if (memcmp(p, "MRES", 4) == 0)
1658 {
1659 unsigned int entry_cnt;
1660 unsigned int i;
1661 const char *blockp;
1662
1663 /* skip the header */
1664 p += 10;
1665
1666 /*
1667 * remember the location of the base of the block - the data
1668 * seek location for each index entry is given as an offset
1669 * from this location
1670 */
1671 blockp = p;
1672
1673 /* the first thing in the table is the number of entries */
1674 entry_cnt = osrp2(p);
1675 p += 2;
1676
1677 /* read the entries */
1678 for (i = 0 ; i < entry_cnt ; ++i)
1679 {
1680 unsigned long entry_ofs;
1681 unsigned long entry_siz;
1682 size_t entry_name_len;
1683 char namebuf[256];
1684 char *xp;
1685 size_t xi;
1686
1687 /*
1688 * Parse this index entry:
1689 *
1690 *. <uint32> address (as offset from the block base)
1691 *. <uint32> size (in bytes)
1692 *. <uint8> name-length
1693 *. <byte * name-length> name (all bytes XORed with 0xFF)
1694 */
1695 entry_ofs = osrp4(p);
1696 entry_siz = osrp4(p + 4);
1697 entry_name_len = (unsigned char)p[8];
1698
1699 /* unmask the name */
1700 memcpy(namebuf, p + 9, resname_len);
1701 for (xi = resname_len, xp = namebuf ; xi != 0 ; --xi)
1702 *xp++ ^= 0xFF;
1703
1704 /* if this is the one we're looking for, return it */
1705 if (entry_name_len == resname_len
1706 && tmemicmp(resname, namebuf, resname_len) == 0)
1707 {
1708 /*
1709 * fill in the return information - note that the entry
1710 * offset given in the header is an offset from data
1711 * block's starting location, so fix this up to an
1712 * absolute seek location for the return value
1713 */
1714 info->ptr = blockp + entry_ofs;
1715 info->len = entry_siz;
1716
1717 /* return success */
1718 return TRUE;
1719 }
1720
1721 /* skip this entry (header + name length) */
1722 p += 9 + entry_name_len;
1723 }
1724
1725 /*
1726 * if we got this far, we didn't find the name; so skip past
1727 * the MRES section by adding the section length to the base
1728 * pointer, and resume the main file scan
1729 */
1730 p = blockp + siz;
1731 }
1732 else if (memcmp(p, "EOF ", 4) == 0)
1733 {
1734 /*
1735 * end of file - we've finished without finding the resource,
1736 * so return failure
1737 */
1738 return FALSE;
1739 }
1740 else
1741 {
1742 /*
1743 * we don't care about anything else - just skip this block and
1744 * keep going; to skip the block, simply seek ahead past the
1745 * block header and then past the block's contents, using the
1746 * size given the in block header
1747 */
1748 p += siz + 10;
1749 }
1750 }
1751
1752 /*
1753 * reached EOF without an EOF marker - file must be corrupted; return
1754 * 'not found'
1755 */
1756 return FALSE;
1757 }
1758
1759 /* ------------------------------------------------------------------------ */
1760 /*
1761 * JPEG and PNG information extraction (based on the versions in
1762 * babel_story_functions.c)
1763 */
1764 static int get_jpeg_dim(const void *img, int32 extent,
1765 int32 *xout, int32 *yout)
1766 {
1767 const unsigned char *dp=(const unsigned char *) img;
1768 const unsigned char *ep=dp+extent;
1769 unsigned int t1, t2, w, h;
1770
1771 t1 = *dp++;
1772 t2 = *dp++;
1773 if (t1 != 0xff || t2 != 0xD8)
1774 return FALSE;
1775
1776 while(1)
1777 {
1778 if (dp>ep) return FALSE;
1779 for(t1=*(dp++);t1!=0xff;t1=*(dp++)) if (dp>ep) return FALSE;
1780 do { t1=*(dp++); if (dp>ep) return FALSE;} while (t1 == 0xff);
1781
1782 if ((t1 & 0xF0) == 0xC0 && !(t1==0xC4 || t1==0xC8 || t1==0xCC))
1783 {
1784 dp+=3;
1785 if (dp>ep) return FALSE;
1786 h=*(dp++) << 8;
1787 if (dp>ep) return FALSE;
1788 h|=*(dp++);
1789 if (dp>ep) return FALSE;
1790 w=*(dp++) << 8;
1791 if (dp>ep) return FALSE;
1792 w|=*(dp);
1793
1794 *xout = w;
1795 *yout = h;
1796 return TRUE;
1797 }
1798 else if (t1==0xD8 || t1==0xD9)
1799 break;
1800 else
1801 {
1802 int l;
1803
1804 if (dp>ep) return FALSE;
1805 l=*(dp++) << 8;
1806 if (dp>ep) return FALSE;
1807 l|= *(dp++);
1808 l-=2;
1809 dp+=l;
1810 if (dp>ep) return FALSE;
1811 }
1812 }
1813 return FALSE;
1814 }
1815
1816 static int32 png_read_int(const unsigned char *mem)
1817 {
1818 int32 i4 = mem[0],
1819 i3 = mem[1],
1820 i2 = mem[2],
1821 i1 = mem[3];
1822 return i1 | (i2<<8) | (i3<<16) | (i4<<24);
1823 }
1824
1825
1826 static int get_png_dim(const void *img, int32 extent,
1827 int32 *xout, int32 *yout)
1828 {
1829 const unsigned char *dp=(const unsigned char *)img;
1830
1831 if (extent<33 ||
1832 !(dp[0]==137 && dp[1]==80 && dp[2]==78 && dp[3]==71 &&
1833 dp[4]==13 && dp[5] == 10 && dp[6] == 26 && dp[7]==10)||
1834 !(dp[12]=='I' && dp[13]=='H' && dp[14]=='D' && dp[15]=='R'))
1835 return FALSE;
1836
1837 *xout = png_read_int(dp+16);
1838 *yout = png_read_int(dp+20);
1839 return TRUE;
1840 }
1841
1842 /* ------------------------------------------------------------------------ */
1843 /*
1844 * Testing main() - this implements a set of unit tests on the tads
1845 * version.
1846 */
1847
1848 #ifdef TADS_TEST
1849
1850 #include "babel_handler.h"
1851
1852 void main(int argc, char **argv)
1853 {
1854 FILE *fp;
1855 int32 siz;
1856 void *buf;
1857 valinfo *head;
1858 int32 rv;
1859 int tadsver;
1860 char outbuf[TREATY_MINIMUM_EXTENT];
1861
1862 /* check arguments */
1863 if (argc != 2)
1864 {
1865 printf("usage: tads <game-file>\n");
1866 exit(1);
1867 }
1868
1869 /* initialize the babel subsystems */
1870 babel_init(argv[1]);
1871
1872 /* open the story file */
1873 if ((fp = fopen(argv[1], "rb")) == 0)
1874 {
1875 printf("error opening input file\n");
1876 exit(2);
1877 }
1878
1879 /* check the file size */
1880 fseek(fp, 0, SEEK_END);
1881 siz = ftell(fp);
1882 fseek(fp, 0, SEEK_SET);
1883
1884 /* allocate space for it */
1885 if ((buf = malloc(siz)) == 0)
1886 {
1887 printf("error allocating space to load file\n");
1888 exit(2);
1889 }
1890
1891 /* load it */
1892 if ((int32)fread(buf, 1, siz, fp) != siz)
1893 {
1894 printf("error reading file\n");
1895 exit(2);
1896 }
1897
1898 /* done with the file */
1899 fclose(fp);
1900
1901
1902
1903 /* ===== test 1 - basic parse_sf_game_info() test ===== */
1904
1905 /* parse the gameinfo record and print the results */
1906 if ((head = parse_sf_game_info(buf, siz, &tadsver)) != 0)
1907 {
1908 valinfo *val;
1909
1910 printf("found GameInfo - tads major version = %d\n", tadsver);
1911 for (val = head ; val != 0 ; val = val->nxt)
1912 {
1913 printf("%.*s=[%.*s]\n",
1914 (int)val->name_len, val->name,
1915 (int)val->val_len, val->val);
1916 }
1917 printf("\n");
1918 }
1919 else
1920 printf("no GameInfo found\n\n");
1921
1922
1923
1924 /* ===== test 2 - test the get_story_file_IFID generator ===== */
1925 rv = tads_get_story_file_IFID(buf, siz, outbuf, TREATY_MINIMUM_EXTENT);
1926 if (rv == 1)
1927 printf("IFID = [%s]\n\n", outbuf);
1928 else
1929 printf("IFID return code = %ld\n", rv);
1930
1931
1932
1933 /* ===== test 3 - test the ifiction synthesizer ===== */
1934 if ((rv = tads_get_story_file_metadata_extent(buf, siz)) > 0)
1935 {
1936 char *ifbuf;
1937
1938 /* try allocating the space */
1939 if ((ifbuf = malloc((size_t)rv)) != 0)
1940 {
1941 /* synthesize the story file */
1942 rv = tads_get_story_file_metadata(buf, siz, ifbuf, rv);
1943 if (rv > 0)
1944 printf("ifiction metadata:\n=====\n%.*s\n=====\n\n",
1945 (int)rv, ifbuf);
1946 else
1947 printf("tads_get_story_file_metadata result = %ld\n", rv);
1948 }
1949 else
1950 printf("unable to allocate %ld bytes for metadata record\n", rv);
1951 }
1952 else
1953 printf("tads_get_story_file_metadata_extent result code = %ld\n", rv);
1954
1955
1956 /* free the loaded story file buffer */
1957 free(buf);
1958 }
1959
1960
1961 #endif /* TADS_TEST */