OSDN Git Service

eddf1113e56c811434dbcc708418f0787fbcf2a1
[lha/lha.git] / src / header.c
1 /* ------------------------------------------------------------------------ */
2 /* LHa for UNIX                                                                                                                         */
3 /*                              header.c -- header manipulate functions                                         */
4 /*                                                                                                                                                      */
5 /*              Modified                        Nobutaka Watazaki                                                       */
6 /*                                                                                                                                                      */
7 /*      Original                                                                                                Y.Tagawa                */
8 /*      modified                                                                        1991.12.16      M.Oki                   */
9 /*      Ver. 1.10  Symbolic Link added                          1993.10.01      N.Watazaki              */
10 /*      Ver. 1.13b Symbolic Link Bug Fix                        1994.08.22      N.Watazaki              */
11 /*      Ver. 1.14  Source All chagned                           1995.01.14      N.Watazaki              */
12 /*  Ver. 1.14i bug fixed                                                2000.10.06  t.okamoto       */
13 /* ------------------------------------------------------------------------ */
14 #include "lha.h"
15
16 #define DUMP_HEADER 1           /* for debugging */
17
18 #if !STRCHR_8BIT_CLEAN
19 /* should use 8 bit clean version */
20 #undef strchr
21 #undef strrchr
22 #define strchr  xstrchr
23 #define strrchr  xstrrchr
24 #endif
25
26 /* ------------------------------------------------------------------------ */
27 static char    *get_ptr;
28 #define GET_BYTE()              (*get_ptr++ & 0xff)
29
30 #if DUMP_HEADER
31 static char    *start_ptr;
32 #define setup_get(PTR)  (start_ptr = get_ptr = (PTR))
33 #define get_byte()      dump_get_byte()
34 #define skip_bytes(len) dump_skip_bytes(len)
35 #else
36 #define setup_get(PTR)  (get_ptr = (PTR))
37 #define get_byte()              GET_BYTE()
38 #define skip_bytes(len) (get_ptr += (len))
39 #endif
40 #define put_ptr                 get_ptr
41 #define setup_put(PTR)  (put_ptr = (PTR))
42 #define put_byte(c)             (*put_ptr++ = (char)(c))
43
44 int optional_archive_kanji_code = NONE;
45 int optional_system_kanji_code = NONE;
46 char *optional_archive_delim = NULL;
47 char *optional_system_delim = NULL;
48 int optional_filename_case = NONE;
49
50 #ifdef MULTIBYTE_FILENAME
51 int default_system_kanji_code = MULTIBYTE_FILENAME;
52 #else
53 int default_system_kanji_code = NONE;
54 #endif
55
56 /* ------------------------------------------------------------------------ */
57 int
58 calc_sum(p, len)
59         register char  *p;
60         register int    len;
61 {
62         register int    sum;
63
64         for (sum = 0; len; len--)
65                 sum += *p++;
66
67         return sum & 0xff;
68 }
69
70 #if DUMP_HEADER
71 static int
72 dump_get_byte()
73 {
74     int c;
75
76     if (verbose_listing && verbose > 1)
77         printf("%02d %2d: ", get_ptr - start_ptr, 1);
78     c = GET_BYTE();
79     if (verbose_listing && verbose > 1) {
80         if (isprint(c))
81             printf("%d(0x%02x) '%c'\n", c, c, c);
82         else
83             printf("%d(0x%02x)\n", c, c);
84     }
85     return c;
86 }
87
88 static void
89 dump_skip_bytes(len)
90     int len;
91 {
92     if (len == 0) return;
93     if (verbose_listing && verbose > 1) {
94         printf("%02d %2d: ", get_ptr - start_ptr, len);
95         while (len--)
96             printf("0x%02x ", GET_BYTE());
97         printf("... ignored\n");
98     }
99     else
100         get_ptr += len;
101 }
102 #endif
103
104 /* ------------------------------------------------------------------------ */
105 static int
106 get_word()
107 {
108         int             b0, b1;
109     int w;
110
111 #if DUMP_HEADER
112     if (verbose_listing && verbose > 1)
113         printf("%02d %2d: ", get_ptr - start_ptr, 2);
114 #endif
115         b0 = GET_BYTE();
116         b1 = GET_BYTE();
117     w = (b1 << 8) + b0;
118 #if DUMP_HEADER
119     if (verbose_listing && verbose > 1)
120         printf("%d(0x%04x)\n", w, w);
121 #endif
122         return w;
123 }
124
125 /* ------------------------------------------------------------------------ */
126 static void
127 put_word(v)
128         unsigned int    v;
129 {
130         put_byte(v);
131         put_byte(v >> 8);
132 }
133
134 /* ------------------------------------------------------------------------ */
135 static long
136 get_longword()
137 {
138         long            b0, b1, b2, b3;
139     long l;
140
141 #if DUMP_HEADER
142     if (verbose_listing && verbose > 1)
143         printf("%02d %2d: ", get_ptr - start_ptr, 4);
144 #endif
145         b0 = GET_BYTE();
146         b1 = GET_BYTE();
147         b2 = GET_BYTE();
148         b3 = GET_BYTE();
149     l = (b3 << 24) + (b2 << 16) + (b1 << 8) + b0;
150 #if DUMP_HEADER
151     if (verbose_listing && verbose > 1)
152         printf("%ld(0x%08lx)\n", l, l);
153 #endif
154         return l;
155 }
156
157 /* ------------------------------------------------------------------------ */
158 static void
159 put_longword(v)
160         long            v;
161 {
162         put_byte(v);
163         put_byte(v >> 8);
164         put_byte(v >> 16);
165         put_byte(v >> 24);
166 }
167
168 static int
169 get_bytes(buf, len, size)
170     char *buf;
171     int len, size;
172 {
173     int i;
174
175 #if DUMP_HEADER
176     if (verbose_listing && verbose > 1)
177         printf("%02d %2d: \"", get_ptr - start_ptr, len);
178
179     for (i = 0; i < len; i++) {
180         if (i < size) buf[i] = get_ptr[i];
181
182         if (verbose_listing && verbose > 1) {
183             if (isprint(buf[i]))
184                 printf("%c", buf[i]);
185             else
186                 printf("\\x%02x", (unsigned char)buf[i]);
187         }
188     }
189
190     if (verbose_listing && verbose > 1)
191         printf("\"\n");
192 #else
193     for (i = 0; i < len && i < size; i++)
194         buf[i] = get_ptr[i];
195 #endif
196
197     get_ptr += len;
198     return i;
199 }
200
201 static void
202 put_bytes(buf, len)
203     char *buf;
204     int len;
205 {
206     int i;
207     for (i = 0; i < len; i++)
208         put_byte(buf[i]);
209 }
210
211 /* added by Koji Arai */
212 void
213 convert_filename(name, len, size,
214                  from_code, to_code,
215                  from_delim, to_delim,
216                  case_to)
217     char *name;
218     int len;
219     int size;
220     int from_code, to_code, case_to;
221     char *from_delim, *to_delim;
222
223 {
224     int i;
225 #ifdef MULTIBYTE_FILENAME
226     char tmp[FILENAME_LENGTH];
227
228     if (from_code == CODE_SJIS && to_code == CODE_UTF8) {
229         for (i = 0; i < len; i++)
230             /* FIXME: provisionally fix for the Mac OS CoreFoundation */
231             if ((unsigned char)name[i] == LHA_PATHSEP)  name[i] = '/';
232         sjis_to_utf8(tmp, name, sizeof(tmp));
233         strncpy(name, tmp, size);
234         name[size-1] = 0;
235         len = strlen(name);
236         for (i = 0; i < len; i++)
237             if (name[i] == '/')  name[i] = LHA_PATHSEP;
238         from_code = CODE_UTF8;
239     }
240     else if (from_code == CODE_UTF8 && to_code == CODE_SJIS) {
241         for (i = 0; i < len; i++)
242             /* FIXME: provisionally fix for the Mac OS CoreFoundation */
243             if ((unsigned char)name[i] == LHA_PATHSEP)  name[i] = '/';
244         utf8_to_sjis(tmp, name, sizeof(tmp));
245         strncpy(name, tmp, size);
246         name[size-1] = 0;
247         len = strlen(name);
248         for (i = 0; i < len; i++)
249             if (name[i] == '/')  name[i] = LHA_PATHSEP;
250         from_code = CODE_SJIS;
251     }
252 #endif
253
254     /* special case: if `name' has small lettter, not convert case. */
255     if (from_code == CODE_SJIS && case_to == TO_LOWER) {
256         for (i = 0; i < len; i++) {
257 #ifdef MULTIBYTE_FILENAME
258             if (SJIS_FIRST_P(name[i]) && SJIS_SECOND_P(name[i+1]))
259                 i++;
260             else
261 #endif
262             if (islower(name[i])) {
263                 case_to = NONE;
264                 break;
265             }
266         }
267     }
268
269     for (i = 0; i < len; i ++) {
270 #ifdef MULTIBYTE_FILENAME
271         if (from_code == CODE_EUC &&
272             (unsigned char)name[i] == 0x8e) {
273             if (to_code != CODE_SJIS) {
274                 i++;
275                 continue;
276             }
277
278             /* X0201 KANA */
279             memmove(name + i, name + i + 1, len - i);
280             len--;
281             continue;
282         }
283         if (from_code == CODE_SJIS && X0201_KANA_P(name[i])) {
284             if (to_code != CODE_EUC) {
285                 continue;
286             }
287
288             if (len == size - 1) /* check overflow */
289                 len--;
290             memmove(name+i+1, name+i, len-i);
291             name[i] = 0x8e;
292             i++;
293             len++;
294             continue;
295         }
296         if (from_code == CODE_EUC && (name[i] & 0x80) && (name[i+1] & 0x80)) {
297             int c1, c2;
298             if (to_code != CODE_SJIS) {
299                 i++;
300                 continue;
301             }
302
303             c1 = (unsigned char)name[i];
304             c2 = (unsigned char)name[i+1];
305             euc2sjis(&c1, &c2);
306             name[i] = c1;
307             name[i+1] = c2;
308             i++;
309             continue;
310         }
311         if (from_code == CODE_SJIS &&
312             SJIS_FIRST_P(name[i]) &&
313             SJIS_SECOND_P(name[i+1])) {
314             int c1, c2;
315
316             if (to_code != CODE_EUC) {
317                 i++;
318                 continue;
319             }
320
321             c1 = (unsigned char)name[i];
322             c2 = (unsigned char)name[i+1];
323             sjis2euc(&c1, &c2);
324             name[i] = c1;
325             name[i+1] = c2;
326             i++;
327             continue;
328         }
329 #endif /* MULTIBYTE_FILENAME */
330         {
331             char *ptr;
332
333             /* transpose from_delim to to_delim */
334
335             if ((ptr = strchr(from_delim, name[i])) != NULL) {
336                 name[i] = to_delim[ptr - from_delim];
337                 continue;
338             }
339         }
340
341         if (case_to == TO_UPPER && islower(name[i])) {
342             name[i] = toupper(name[i]);
343             continue;
344         }
345         if (case_to == TO_LOWER && isupper(name[i])) {
346             name[i] = tolower(name[i]);
347             continue;
348         }
349     }
350 }
351
352 /* ------------------------------------------------------------------------ */
353 /*                                                                          */
354 /* Generic stamp format:                                                    */
355 /*                                                                          */
356 /*  31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16                         */
357 /* |<------- year ----->|<- month ->|<--- day ---->|                        */
358 /*                                                                          */
359 /*  15 14 13 12 11 10  9  8  7  6  5  4  3  2  1  0                         */
360 /* |<--- hour --->|<---- minute --->|<- second*2 ->|                        */
361 /*                                                                          */
362 /* ------------------------------------------------------------------------ */
363
364 /*
365  * NOTE : If you don't have `gettimeofday(2)', or your gettimeofday(2)
366  * returns bogus timezone information, try FTIME, MKTIME, TIMELOCAL or TZSET.
367  */
368
369 #ifdef HAVE_FTIME
370 #include <sys/timeb.h>
371 #endif
372
373 #if !defined(HAVE_MKTIME) && !defined(HAVE_TIMELOCAL)
374 static long
375 gettz()
376 {
377 #ifdef HAVE_TZSET
378 #if defined(_MINIX)
379     extern long     timezone;           /* not defined in time.h */
380 #endif
381
382         tzset();
383         return timezone;
384 #elif HAVE_FTIME        
385         struct timeb    buf;
386
387         ftime(&buf);
388         return buf.timezone * 60L;
389 #elif HAVE_STRUCT_TM_TM_GMTOFF
390         time_t tt;
391
392         time(&tt);
393         return -localtime(&tt)->tm_gmtoff;
394 #elif GETTIMEOFDAY_HAS_2ND_ARG
395         struct timeval  tp;
396         struct timezone tzp;
397         gettimeofday(&tp, &tzp);/* specific to 4.3BSD */
398         /*
399          * return (tzp.tz_minuteswest * 60L + (tzp.tz_dsttime != 0 ? 60L *
400          * 60L : 0));
401          */
402         return (tzp.tz_minuteswest * 60L);
403 #else
404     /* Compile error will be caused */
405     CANNOT GET TIMEZONE INFORMATION ON YOUR SYSTEM.
406     TAKE THE ANOTHER WAY.
407 #endif
408 }
409 #endif
410
411 /* ------------------------------------------------------------------------ */
412 static          time_t
413 generic_to_unix_stamp(t)
414         long            t;
415 {
416 #if defined(HAVE_MKTIME) || defined(HAVE_TIMELOCAL)
417         struct tm       dostm;
418
419         /*
420          * special case:  if MSDOS format date and time were zero, then we
421          * set time to be zero here too.
422          */
423         if (t == 0)
424                 return (time_t) 0;
425
426         dostm.tm_sec = (t & 0x1f) * 2;
427         dostm.tm_min = t >> 5 & 0x3f;
428         dostm.tm_hour = t >> 11 & 0x1f;
429         dostm.tm_mday = t >> 16 & 0x1f;
430         dostm.tm_mon = (t >> (16+5) & 0x0f) - 1;        /* 0..11 */
431         dostm.tm_year = (t >> (16+9) & 0x7f) + 80;
432         dostm.tm_isdst = -1;
433
434 #if HAVE_MKTIME
435         return (time_t) mktime(&dostm);
436 #else /* HAVE_TIMELOCAL is defined */
437         return (time_t) timelocal(&dostm);
438 #endif
439
440 #else                           /* defined(HAVE_MKTIME) || defined(HAVE_TIMELOCAL) */
441         int             year, month, day, hour, min, sec;
442         long            longtime;
443         static unsigned int dsboy[12] = {0, 31, 59, 90, 120, 151,
444         181, 212, 243, 273, 304, 334};
445         unsigned int    days;
446
447         /*
448          * special case:  if MSDOS format date and time were zero, then we
449          * set time to be zero here too.
450          */
451         if (t == 0)
452                 return (time_t) 0;
453
454         year = ((int) (t >> 16 + 9) & 0x7f) + 1980;
455         month = (int) (t >> 16 + 5) & 0x0f;     /* 1..12 means Jan..Dec */
456         day = (int) (t >> 16) & 0x1f;   /* 1..31 means 1st,...31st */
457
458         hour = ((int) t >> 11) & 0x1f;
459         min = ((int) t >> 5) & 0x3f;
460         sec = ((int) t & 0x1f) * 2;
461
462         /* Calculate days since 1970.01.01 */
463         days = (365 * (year - 1970) +   /* days due to whole years */
464                 (year - 1970 + 1) / 4 + /* days due to leap years */
465                 dsboy[month - 1] +      /* days since beginning of this year */
466                 day - 1);       /* days since beginning of month */
467
468         if ((year % 4 == 0) &&
469                 (year % 100 != 0 || year % 400 == 0) &&         /* 1999.5.24 t.oka */
470             (month >= 3))       /* if this is a leap year and month */
471                 days++;         /* is March or later, add a day */
472
473         /* Knowing the days, we can find seconds */
474         longtime = (((days * 24) + hour) * 60 + min) * 60 + sec;
475         longtime += gettz();    /* adjust for timezone */
476
477         /* LONGTIME is now the time in seconds, since 1970/01/01 00:00:00.  */
478         return (time_t) longtime;
479 #endif                          /* defined(HAVE_MKTIME) || defined(HAVE_TIMELOCAL) */
480 }
481
482 /* ------------------------------------------------------------------------ */
483 static long
484 unix_to_generic_stamp(t)
485         time_t          t;
486 {
487         struct tm      *tm = localtime(&t);
488
489         return ((((long) (tm->tm_year - 80)) << 25) +
490                 (((long) (tm->tm_mon + 1)) << 21) +
491                 (((long) tm->tm_mday) << 16) +
492                 (long) ((tm->tm_hour << 11) +
493                         (tm->tm_min << 5) +
494                         (tm->tm_sec / 2)));
495 }
496
497 static unsigned long
498 wintime_to_unix_stamp()
499 {
500 #if HAVE_UINT64_T
501     uint64_t t;
502     uint64_t epoch = 0x019db1ded53e8000; /* 1970-01-01 00:00:00 (UTC) */
503
504     t = get_longword();
505     t += (uint64_t)get_longword() << 32;
506     t = (t - epoch) / 10000000;
507     return t;
508 #else
509     int i, borrow;
510     unsigned long t, q, x;
511     unsigned long wintime[8];
512     unsigned long epoch[8] = {0x01,0x9d,0xb1,0xde, 0xd5,0x3e,0x80,0x00};
513                                 /* 1970-01-01 00:00:00 (UTC) */
514     /* wintime -= epoch */
515     borrow = 0;
516     for (i = 7; i >= 0; i--) {
517         wintime[i] = (unsigned)get_byte() - epoch[i] - borrow;
518         borrow = (wintime[i] > 0xff) ? 1 : 0;
519         wintime[i] &= 0xff;
520     }
521
522     /* q = wintime / 10000000 */
523     t = q = 0;
524     x = 10000000;               /* x: 24bit */
525     for (i = 0; i < 8; i++) {
526         t = (t << 8) + wintime[i]; /* 24bit + 8bit. t must be 32bit variable */
527         q <<= 8;                   /* q must be 32bit (time_t) */
528         q += t / x;
529         t %= x;     /* 16bit */
530     }
531     return q;
532 #endif
533 }
534
535 /* ------------------------------------------------------------------------ */
536 /* build header functions                                                                                                       */
537 /* ------------------------------------------------------------------------ */
538
539 /*
540  * extended header
541  *
542  *             size  field name
543  *  --------------------------------
544  *  base header:         :
545  *           2 or 4  next-header size  [*1]
546  *  --------------------------------------
547  *  ext header:   1  ext-type            ^
548  *                ?  contents            | [*1] next-header size
549  *           2 or 4  next-header size    v
550  *  --------------------------------------
551  *
552  *  on level 1, 2 header:
553  *    size field is 2 bytes
554  *  on level 3 header:
555  *    size field is 4 bytes
556  */
557
558 static long
559 get_extended_header(fp, hdr, header_size, hcrc)
560     FILE *fp;
561     LzHeader *hdr;
562     long header_size;
563     unsigned int *hcrc;
564 {
565     char data[LZHEADER_STORAGE];
566     int name_length;
567     char dirname[FILENAME_LENGTH];
568     int dir_length = 0;
569     int i;
570     long whole_size = header_size;
571     int ext_type;
572     int n = 1 + hdr->size_field_length; /* `ext-type' + `next-header size' */
573
574     if (hdr->header_level == 0)
575         return 0;
576
577     name_length = strlen(hdr->name);
578
579     while (header_size) {
580         setup_get(data);
581         if (sizeof(data) < header_size) {
582             error("header size (%ld) too large.", header_size);
583             exit(1);
584         }
585
586         if (fread(data, header_size, 1, fp) == 0) {
587             error("Invalid header (LHa file ?)");
588             return -1;
589         }
590
591         ext_type = get_byte();
592         switch (ext_type) {
593         case 0:
594             /* header crc (CRC-16) */
595             hdr->header_crc = get_word();
596             /* clear buffer for CRC calculation. */
597             data[1] = data[2] = 0;
598             skip_bytes(header_size - n - 2);
599             break;
600         case 1:
601             /* filename */
602             name_length =
603                 get_bytes(hdr->name, header_size-n, sizeof(hdr->name)-1);
604             hdr->name[name_length] = 0;
605             break;
606         case 2:
607             /* directory */
608             dir_length = get_bytes(dirname, header_size-n, sizeof(dirname)-1);
609             dirname[dir_length] = 0;
610             break;
611         case 0x40:
612             /* MS-DOS attribute */
613             hdr->attribute = get_word();
614             break;
615         case 0x41:
616             /* Windows time stamp (FILETIME structure) */
617             /* it is time in 100 nano seconds since 1601-01-01 00:00:00 */
618
619             skip_bytes(8); /* create time is ignored */
620
621             /* set last modified time */
622             if (hdr->header_level >= 2)
623                 skip_bytes(8);  /* time_t has been already set */
624             else
625                 hdr->unix_last_modified_stamp = wintime_to_unix_stamp();
626
627             skip_bytes(8); /* last access time is ignored */
628
629             break;
630         case 0x50:
631             /* UNIX permission */
632             hdr->unix_mode = get_word();
633             break;
634         case 0x51:
635             /* UNIX gid and uid */
636             hdr->unix_gid = get_word();
637             hdr->unix_uid = get_word();
638             break;
639         case 0x52:
640             /* UNIX group name */
641             i = get_bytes(hdr->group, header_size-n, sizeof(hdr->group)-1);
642             hdr->group[i] = '\0';
643             break;
644         case 0x53:
645             /* UNIX user name */
646             i = get_bytes(hdr->user, header_size-n, sizeof(hdr->user)-1);
647             hdr->user[i] = '\0';
648             break;
649         case 0x54:
650             /* UNIX last modified time */
651             hdr->unix_last_modified_stamp = (time_t) get_longword();
652             break;
653         default:
654             /* other headers */
655             /* 0x39: multi-disk header
656                0x3f: uncompressed comment
657                0x42: 64bit large file size
658                0x48-0x4f(?): reserved for authenticity verification
659                0x7d: encapsulation
660                0x7e: extended attribute - platform information
661                0x7f: extended attribute - permission, owner-id and timestamp
662                      (level 3 on OS/2)
663                0xc4: compressed comment (dict size: 4096)
664                0xc5: compressed comment (dict size: 8192)
665                0xc6: compressed comment (dict size: 16384)
666                0xc7: compressed comment (dict size: 32768)
667                0xc8: compressed comment (dict size: 65536)
668                0xd0-0xdf(?): operating systemm specific information
669                0xfc: encapsulation (another opinion)
670                0xfe: extended attribute - platform information(another opinion)
671                0xff: extended attribute - permission, owner-id and timestamp
672                      (level 3 on UNLHA32) */
673             if (verbose)
674                 warning("unknown extended header 0x%02x", ext_type);
675             skip_bytes(header_size - n);
676             break;
677         }
678
679         if (hcrc)
680             *hcrc = calccrc(*hcrc, data, header_size);
681
682         if (hdr->size_field_length == 2)
683             whole_size += header_size = get_word();
684         else
685             whole_size += header_size = get_longword();
686     }
687
688     /* concatenate dirname and filename */
689     if (dir_length) {
690         if (name_length + dir_length >= sizeof(hdr->name)) {
691             warning("the length of pathname \"%s%s\" is too long.",
692                     dirname, hdr->name);
693             name_length = sizeof(hdr->name) - dir_length - 1;
694             hdr->name[name_length] = 0;
695         }
696         strcat(dirname, hdr->name);
697         strcpy(hdr->name, dirname);
698         name_length += dir_length;
699     }
700
701     return whole_size;
702 }
703
704 /*
705  * level 0 header
706  *
707  *
708  * offset  size  field name
709  * ----------------------------------
710  *     0      1  header size    [*1]
711  *     1      1  header sum
712  *            ---------------------------------------
713  *     2      5  method ID                         ^
714  *     7      4  packed size    [*2]               |
715  *    11      4  original size                     |
716  *    15      2  time                              |
717  *    17      2  date                              |
718  *    19      1  attribute                         | [*1] header size (X+Y+22)
719  *    20      1  level (0x00 fixed)                |
720  *    21      1  name length                       |
721  *    22      X  pathname                          |
722  * X +22      2  file crc (CRC-16)                 |
723  * X +24      Y  ext-header(old style)             v
724  * -------------------------------------------------
725  * X+Y+24        data                              ^
726  *                 :                               | [*2] packed size
727  *                 :                               v
728  * -------------------------------------------------
729  *
730  * ext-header(old style)
731  *     0      1  ext-type ('U')
732  *     1      1  minor version
733  *     2      4  UNIX time
734  *     6      2  mode
735  *     8      2  uid
736  *    10      2  gid
737  *
738  * attribute (MS-DOS)
739  *    bit1  read only
740  *    bit2  hidden
741  *    bit3  system
742  *    bit4  volume label
743  *    bit5  directory
744  *    bit6  archive bit (need to backup)
745  *
746  */
747 static int
748 get_header_level0(fp, hdr, data)
749     FILE *fp;
750     LzHeader *hdr;
751     char *data;
752 {
753     int header_size;
754     int checksum;
755     int name_length;
756     int i;
757     int extend_size;
758
759     hdr->size_field_length = 2; /* in bytes */
760     hdr->header_size = header_size = get_byte();
761     checksum = get_byte();
762
763     if (fread(data+I_NAME_LENGTH, header_size+2-I_NAME_LENGTH, 1, fp) == 0) {
764         error("Invalid header (LHarc file ?)");
765         return FALSE;   /* finish */
766     }
767
768     if (calc_sum(data + I_METHOD, header_size) != checksum) {
769         error("Checksum error (LHarc file?)");
770         return FALSE;
771     }
772
773     get_bytes(hdr->method, 5, sizeof(hdr->method));
774     hdr->packed_size = get_longword();
775     hdr->original_size = get_longword();
776     hdr->unix_last_modified_stamp = generic_to_unix_stamp(get_longword());
777     hdr->attribute = get_byte(); /* MS-DOS attribute */
778     hdr->header_level = get_byte();
779     name_length = get_byte();
780     i = get_bytes(hdr->name, name_length, sizeof(hdr->name)-1);
781     hdr->name[i] = '\0';
782
783     /* defaults for other type */
784     hdr->unix_mode = UNIX_FILE_REGULAR | UNIX_RW_RW_RW;
785     hdr->unix_gid = 0;
786     hdr->unix_uid = 0;
787
788     extend_size = header_size+2 - name_length - 24;
789
790     if (extend_size < 0) {
791         if (extend_size == -2) {
792             /* CRC field is not given */
793             hdr->extend_type = EXTEND_GENERIC;
794             hdr->has_crc = FALSE;
795
796             return TRUE;
797         } 
798
799         error("Unkonwn header (lha file?)");
800         exit(1);
801     }
802
803     hdr->has_crc = TRUE;
804     hdr->crc = get_word();
805
806     if (extend_size == 0)
807         return TRUE;
808
809     hdr->extend_type = get_byte();
810     extend_size--;
811
812     if (hdr->extend_type == EXTEND_UNIX) {
813         if (extend_size >= 11) {
814             hdr->minor_version = get_byte();
815             hdr->unix_last_modified_stamp = (time_t) get_longword();
816             hdr->unix_mode = get_word();
817             hdr->unix_uid = get_word();
818             hdr->unix_gid = get_word();
819             extend_size -= 11;
820         } else {
821             hdr->extend_type = EXTEND_GENERIC;
822         }
823     }
824     if (extend_size > 0)
825         skip_bytes(extend_size);
826
827     hdr->header_size += 2;
828     return TRUE;
829 }
830
831 /*
832  * level 1 header
833  *
834  *
835  * offset   size  field name
836  * -----------------------------------
837  *     0       1  header size   [*1]
838  *     1       1  header sum
839  *             -------------------------------------
840  *     2       5  method ID                        ^
841  *     7       4  skip size     [*2]               |
842  *    11       4  original size                    |
843  *    15       2  time                             |
844  *    17       2  date                             |
845  *    19       1  attribute (0x20 fixed)           | [*1] header size (X+Y+25)
846  *    20       1  level (0x01 fixed)               |
847  *    21       1  name length                      |
848  *    22       X  filename                         |
849  * X+ 22       2  file crc (CRC-16)                |
850  * X+ 24       1  OS ID                            |
851  * X +25       Y  ???                              |
852  * X+Y+25      2  next-header size                 v
853  * -------------------------------------------------
854  * X+Y+27      Z  ext-header                       ^
855  *                 :                               |
856  * -----------------------------------             | [*2] skip size
857  * X+Y+Z+27       data                             |
858  *                 :                               v
859  * -------------------------------------------------
860  *
861  */
862 static int
863 get_header_level1(fp, hdr, data)
864     FILE *fp;
865     LzHeader *hdr;
866     char *data;
867 {
868     int header_size, extend_size;
869     int checksum;
870     int name_length;
871     int i, dummy;
872
873     hdr->size_field_length = 2; /* in bytes */
874     hdr->header_size = header_size = get_byte();
875     checksum = get_byte();
876
877     if (fread(data+I_NAME_LENGTH, header_size+2-I_NAME_LENGTH, 1, fp) == 0) {
878         error("Invalid header (LHarc file ?)");
879         return FALSE;   /* finish */
880     }
881
882     if (calc_sum(data + I_METHOD, header_size) != checksum) {
883         error("Checksum error (LHarc file?)");
884         return FALSE;
885     }
886
887     get_bytes(hdr->method, 5, sizeof(hdr->method));
888     hdr->packed_size = get_longword(); /* skip size */
889     hdr->original_size = get_longword();
890     hdr->unix_last_modified_stamp = generic_to_unix_stamp(get_longword());
891     hdr->attribute = get_byte(); /* 0x20 fixed */
892     hdr->header_level = get_byte();
893
894     name_length = get_byte();
895     i = get_bytes(hdr->name, name_length, sizeof(hdr->name)-1);
896     hdr->name[i] = '\0';
897
898     /* defaults for other type */
899     hdr->unix_mode = UNIX_FILE_REGULAR | UNIX_RW_RW_RW;
900     hdr->unix_gid = 0;
901     hdr->unix_uid = 0;
902
903     hdr->has_crc = TRUE;
904     hdr->crc = get_word();
905     hdr->extend_type = get_byte();
906
907     dummy = header_size+2 - name_length - 27;
908     if (dummy > 0)
909         skip_bytes(dummy); /* skip old style extend header */
910
911     extend_size = get_word();
912     extend_size = get_extended_header(fp, hdr, extend_size, 0);
913     if (extend_size == -1)
914         return FALSE;
915
916     /* On level 1 header, size fields should be adjusted. */
917     /* the `packed_size' field contains the extended header size. */
918     /* the `header_size' field does not. */
919     hdr->packed_size -= extend_size;
920     hdr->header_size += extend_size + 2;
921
922     return TRUE;
923 }
924
925 /*
926  * level 2 header
927  *
928  *
929  * offset   size  field name
930  * --------------------------------------------------
931  *     0       2  total header size [*1]           ^
932  *             -----------------------             |
933  *     2       5  method ID                        |
934  *     7       4  packed size       [*2]           |
935  *    11       4  original size                    |
936  *    15       4  time                             |
937  *    19       1  RESERVED (0x20 fixed)            | [*1] total header size
938  *    20       1  level (0x02 fixed)               |      (X+26+(1))
939  *    21       2  file crc (CRC-16)                |
940  *    23       1  OS ID                            |
941  *    24       2  next-header size                 |
942  * -----------------------------------             |
943  *    26       X  ext-header                       |
944  *                 :                               |
945  * -----------------------------------             |
946  * X +26      (1) padding                          v
947  * -------------------------------------------------
948  * X +26+(1)      data                             ^
949  *                 :                               | [*2] packed size
950  *                 :                               v
951  * -------------------------------------------------
952  *
953  */
954 static int
955 get_header_level2(fp, hdr, data)
956     FILE *fp;
957     LzHeader *hdr;
958     char *data;
959 {
960     int header_size, extend_size;
961     int padding;
962     unsigned int hcrc;
963
964     hdr->size_field_length = 2; /* in bytes */
965     hdr->header_size = header_size = get_word();
966
967     if (fread(data + I_NAME_LENGTH, 26 - I_NAME_LENGTH, 1, fp) == 0) {
968         error("Invalid header (LHarc file ?)");
969         return FALSE;   /* finish */
970     }
971
972     get_bytes(hdr->method, 5, sizeof(hdr->method));
973     hdr->packed_size = get_longword();
974     hdr->original_size = get_longword();
975     hdr->unix_last_modified_stamp = get_longword();
976     hdr->attribute = get_byte(); /* reserved */
977     hdr->header_level = get_byte();
978
979     /* defaults for other type */
980     hdr->unix_mode = UNIX_FILE_REGULAR | UNIX_RW_RW_RW;
981     hdr->unix_gid = 0;
982     hdr->unix_uid = 0;
983
984     hdr->has_crc = TRUE;
985     hdr->crc = get_word();
986     hdr->extend_type = get_byte();
987     extend_size = get_word();
988
989     INITIALIZE_CRC(hcrc);
990     hcrc = calccrc(hcrc, data, get_ptr - data);
991
992     extend_size = get_extended_header(fp, hdr, extend_size, &hcrc);
993     if (extend_size == -1)
994         return FALSE;
995
996     padding = header_size - 26 - extend_size;
997     while (padding--)           /* padding should be 0 or 1 */
998         hcrc = UPDATE_CRC(hcrc, fgetc(fp));
999
1000     if (hdr->header_crc != hcrc)
1001         error("header CRC error");
1002
1003     return TRUE;
1004 }
1005
1006 /*
1007  * level 3 header
1008  *
1009  *
1010  * offset   size  field name
1011  * --------------------------------------------------
1012  *     0       2  size field length (4 fixed)      ^
1013  *     2       5  method ID                        |
1014  *     7       4  packed size       [*2]           |
1015  *    11       4  original size                    |
1016  *    15       4  time                             |
1017  *    19       1  RESERVED (0x20 fixed)            | [*1] total header size
1018  *    20       1  level (0x03 fixed)               |      (X+32)
1019  *    21       2  file crc (CRC-16)                |
1020  *    23       1  OS ID                            |
1021  *    24       4  total header size [*1]           |
1022  *    28       4  next-header size                 |
1023  * -----------------------------------             |
1024  *    32       X  ext-header                       |
1025  *                 :                               v
1026  * -------------------------------------------------
1027  * X +32          data                             ^
1028  *                 :                               | [*2] packed size
1029  *                 :                               v
1030  * -------------------------------------------------
1031  *
1032  */
1033 static int
1034 get_header_level3(fp, hdr, data)
1035     FILE *fp;
1036     LzHeader *hdr;
1037     char *data;
1038 {
1039     long header_size, extend_size;
1040     int padding;
1041     unsigned int hcrc;
1042
1043     hdr->size_field_length = get_word();
1044
1045     if (fread(data + I_NAME_LENGTH, 32 - I_NAME_LENGTH, 1, fp) == 0) {
1046         error("Invalid header (LHarc file ?)");
1047         return FALSE;   /* finish */
1048     }
1049
1050     get_bytes(hdr->method, 5, sizeof(hdr->method));
1051     hdr->packed_size = get_longword();
1052     hdr->original_size = get_longword();
1053     hdr->unix_last_modified_stamp = get_longword();
1054     hdr->attribute = get_byte(); /* reserved */
1055     hdr->header_level = get_byte();
1056
1057     /* defaults for other type */
1058     hdr->unix_mode = UNIX_FILE_REGULAR | UNIX_RW_RW_RW;
1059     hdr->unix_gid = 0;
1060     hdr->unix_uid = 0;
1061
1062     hdr->has_crc = TRUE;
1063     hdr->crc = get_word();
1064     hdr->extend_type = get_byte();
1065     hdr->header_size = header_size = get_longword();
1066     extend_size = get_longword();
1067
1068     INITIALIZE_CRC(hcrc);
1069     hcrc = calccrc(hcrc, data, get_ptr - data);
1070
1071     extend_size = get_extended_header(fp, hdr, extend_size, &hcrc);
1072     if (extend_size == -1)
1073         return FALSE;
1074
1075     padding = header_size - 32 - extend_size;
1076     while (padding--)           /* padding should be 0 */
1077         hcrc = UPDATE_CRC(hcrc, fgetc(fp));
1078
1079     if (hdr->header_crc != hcrc)
1080         error("header CRC error");
1081
1082     return TRUE;
1083 }
1084
1085 boolean
1086 get_header(fp, hdr)
1087     FILE *fp;
1088     LzHeader *hdr;
1089 {
1090     char data[LZHEADER_STORAGE];
1091
1092     int archive_kanji_code = CODE_SJIS;
1093     int system_kanji_code = default_system_kanji_code;
1094     char *archive_delim = "\377\\"; /* `\' is for level 0 header and
1095                                        broken archive. */
1096     char *system_delim = "//";
1097     int filename_case = NONE;
1098     int end_mark;
1099
1100     memset(hdr, 0, sizeof(LzHeader));
1101
1102     setup_get(data);
1103
1104     if ((end_mark = getc(fp)) == EOF || end_mark == 0) {
1105         return FALSE;           /* finish */
1106     }
1107     data[0] = end_mark;
1108
1109     if (fread(data + 1, I_NAME_LENGTH - 1, 1, fp) == 0) {
1110         error("Invalid header (LHarc file ?)");
1111         return FALSE;           /* finish */
1112     }
1113
1114     switch (data[I_HEADER_LEVEL]) {
1115     case 0:
1116         if (get_header_level0(fp, hdr, data) == FALSE)
1117             return FALSE;
1118         break;
1119     case 1:
1120         if (get_header_level1(fp, hdr, data) == FALSE)
1121             return FALSE;
1122         break;
1123     case 2:
1124         if (get_header_level2(fp, hdr, data) == FALSE)
1125             return FALSE;
1126         break;
1127     case 3:
1128         if (get_header_level3(fp, hdr, data) == FALSE)
1129             return FALSE;
1130         break;
1131     default:
1132         error("Unknown level header (level %d)", data[I_HEADER_LEVEL]);
1133         return FALSE;
1134     }
1135
1136     /* filename conversion */
1137     switch (hdr->extend_type) {
1138     case EXTEND_MSDOS:
1139         filename_case = noconvertcase ? NONE : TO_LOWER;
1140         break;
1141     case EXTEND_HUMAN:
1142     case EXTEND_OS68K:
1143     case EXTEND_XOSK:
1144     case EXTEND_UNIX:
1145     case EXTEND_JAVA:
1146         filename_case = NONE;
1147         break;
1148
1149     case EXTEND_MACOS:
1150         archive_delim = "\377/:\\";
1151                           /* `\' is for level 0 header and broken archive. */
1152         system_delim = "/://";
1153         filename_case = NONE;
1154         break;
1155
1156     default:
1157         filename_case = noconvertcase ? NONE : TO_LOWER;
1158         break;
1159     }
1160
1161     if (optional_archive_kanji_code)
1162         archive_kanji_code = optional_archive_kanji_code;
1163     if (optional_system_kanji_code)
1164         system_kanji_code = optional_system_kanji_code;
1165     if (optional_archive_delim)
1166         archive_delim = optional_archive_delim;
1167     if (optional_system_delim)
1168         system_delim = optional_system_delim;
1169     if (optional_filename_case)
1170         filename_case = optional_filename_case;
1171
1172     /* kanji code and delimiter conversion */
1173     convert_filename(hdr->name, strlen(hdr->name), sizeof(hdr->name),
1174                      archive_kanji_code,
1175                      system_kanji_code,
1176                      archive_delim, system_delim, filename_case);
1177
1178         if ((hdr->unix_mode & UNIX_FILE_SYMLINK) == UNIX_FILE_SYMLINK) {
1179         char *p;
1180         /* split symbolic link */
1181         p = strchr(hdr->name, '|');
1182         if (p) {
1183             /* hdr->name is symbolic link name */
1184             /* hdr->realname is real name */
1185             *p = 0;
1186             strncpy(hdr->realname, p+1, sizeof(hdr->realname));
1187         }
1188         else
1189             error("unknown symlink name \"%s\"", hdr->name);
1190     }
1191
1192     return TRUE;
1193 }
1194
1195 /* ------------------------------------------------------------------------ */
1196 void
1197 init_header(name, v_stat, hdr)
1198         char           *name;
1199         struct stat    *v_stat;
1200         LzHeader       *hdr;
1201 {
1202         int             len;
1203
1204     memset(hdr, 0, sizeof(LzHeader));
1205
1206     /* the `method' member is rewrote by the encoding function.
1207        but need set for empty files */
1208     memcpy(hdr->method, LZHUFF0_METHOD, METHOD_TYPE_STORAGE);
1209
1210         hdr->packed_size = 0;
1211         hdr->original_size = v_stat->st_size;
1212         hdr->attribute = GENERIC_ATTRIBUTE;
1213         hdr->header_level = header_level;
1214         strcpy(hdr->name, name);
1215         len = strlen(name);
1216         hdr->crc = 0x0000;
1217         hdr->extend_type = EXTEND_UNIX;
1218         hdr->unix_last_modified_stamp = v_stat->st_mtime;
1219         /* since 00:00:00 JAN.1.1970 */
1220 #ifdef NOT_COMPATIBLE_MODE
1221         /* Please need your modification in this space. */
1222 #else
1223         hdr->unix_mode = v_stat->st_mode;
1224 #endif
1225
1226         hdr->unix_uid = v_stat->st_uid;
1227         hdr->unix_gid = v_stat->st_gid;
1228
1229 #if INCLUDE_OWNER_NAME_IN_HEADER
1230 #if HAVE_GETPWUID
1231     {
1232         struct passwd *ent = getpwuid(hdr->unix_uid);
1233
1234         if (ent) {
1235             strncpy(hdr->user, ent->pw_name, sizeof(hdr->user));
1236             if (hdr->user[sizeof(hdr->user)-1])
1237                 hdr->user[sizeof(hdr->user)-1] = 0;
1238         }
1239     }
1240 #endif
1241 #if HAVE_GETGRGID
1242     {
1243         struct group *ent = getgrgid(hdr->unix_gid);
1244
1245         if (ent) {
1246             strncpy(hdr->group, ent->gr_name, sizeof(hdr->group));
1247             if (hdr->group[sizeof(hdr->group)-1])
1248                 hdr->group[sizeof(hdr->group)-1] = 0;
1249         }
1250     }
1251 #endif
1252 #endif /* INCLUDE_OWNER_NAME_IN_HEADER */
1253         if (is_directory(v_stat)) {
1254                 memcpy(hdr->method, LZHDIRS_METHOD, METHOD_TYPE_STORAGE);
1255                 hdr->attribute = GENERIC_DIRECTORY_ATTRIBUTE;
1256                 hdr->original_size = 0;
1257                 if (len > 0 && hdr->name[len - 1] != '/')
1258                         strcpy(&hdr->name[len++], "/");
1259         }
1260
1261 #ifdef S_IFLNK
1262         if (is_symlink(v_stat)) {
1263                 memcpy(hdr->method, LZHDIRS_METHOD, METHOD_TYPE_STORAGE);
1264                 hdr->attribute = GENERIC_DIRECTORY_ATTRIBUTE;
1265                 hdr->original_size = 0;
1266                 readlink(name, hdr->realname, sizeof(hdr->realname));
1267         }
1268 #endif
1269 }
1270
1271 static void
1272 write_unix_info(hdr)
1273     LzHeader *hdr;
1274 {
1275     /* UNIX specific informations */
1276
1277     put_word(5);            /* size */
1278     put_byte(0x50);         /* permission */
1279     put_word(hdr->unix_mode);
1280
1281     put_word(7);            /* size */
1282     put_byte(0x51);         /* gid and uid */
1283     put_word(hdr->unix_gid);
1284     put_word(hdr->unix_uid);
1285
1286     if (hdr->group[0]) {
1287         int len = strlen(hdr->group);
1288         put_word(len + 3);  /* size */
1289         put_byte(0x52);     /* group name */
1290         put_bytes(hdr->group, len);
1291     }
1292
1293     if (hdr->user[0]) {
1294         int len = strlen(hdr->user);
1295         put_word(len + 3);  /* size */
1296         put_byte(0x53);     /* user name */
1297         put_bytes(hdr->user, len);
1298     }
1299
1300     if (hdr->header_level == 1) {
1301         put_word(7);        /* size */
1302         put_byte(0x54);     /* time stamp */
1303         put_longword(hdr->unix_last_modified_stamp);
1304     }
1305 }
1306
1307 /* ------------------------------------------------------------------------ */
1308 /* Write unix extended header or generic header. */
1309
1310 static int
1311 write_header_level0(data, hdr, pathname)
1312     LzHeader *hdr;
1313     char *data, *pathname;
1314 {
1315     int limit;
1316     int name_length;
1317     int header_size;
1318
1319     setup_put(data);
1320     memset(data, 0, LZHEADER_STORAGE);
1321
1322     put_byte(0x00);             /* header size */
1323     put_byte(0x00);             /* check sum */
1324     put_bytes(hdr->method, 5);
1325     put_longword(hdr->packed_size);
1326     put_longword(hdr->original_size);
1327     put_longword(unix_to_generic_stamp(hdr->unix_last_modified_stamp));
1328     put_byte(hdr->attribute);
1329     put_byte(hdr->header_level); /* level 0 */
1330
1331     /* write pathname (level 0 header contains the directory part) */
1332     name_length = strlen(pathname);
1333     if (generic_format)
1334         limit = 255 - I_GENERIC_HEADER_BOTTOM + 2;
1335     else
1336         limit = 255 - I_UNIX_EXTEND_BOTTOM + 2;
1337
1338     if (name_length > limit) {
1339         warning("the length of pathname \"%s\" is too long.", pathname);
1340         name_length = limit;
1341     }
1342     put_byte(name_length);
1343     put_bytes(pathname, name_length);
1344     put_word(hdr->crc);
1345
1346     if (generic_format) {
1347         header_size = I_GENERIC_HEADER_BOTTOM + name_length - 2;
1348         data[I_HEADER_SIZE] = header_size;
1349         data[I_HEADER_CHECKSUM] = calc_sum(data + I_METHOD, header_size);
1350     } else {
1351         /* write old-style extend header */
1352         put_byte(EXTEND_UNIX);
1353         put_byte(CURRENT_UNIX_MINOR_VERSION);
1354         put_longword(hdr->unix_last_modified_stamp);
1355         put_word(hdr->unix_mode);
1356         put_word(hdr->unix_uid);
1357         put_word(hdr->unix_gid);
1358
1359         /* size of extended header is 12 */
1360         header_size = I_UNIX_EXTEND_BOTTOM + name_length - 2;
1361         data[I_HEADER_SIZE] = header_size;
1362         data[I_HEADER_CHECKSUM] = calc_sum(data + I_METHOD, header_size);
1363     }
1364
1365     return header_size + 2;
1366 }
1367
1368 static int
1369 write_header_level1(data, hdr, pathname)
1370     LzHeader *hdr;
1371     char *data, *pathname;
1372 {
1373     int name_length, dir_length, limit;
1374     char *basename, *dirname;
1375     int header_size;
1376     char *extend_header_top;
1377     int extend_header_size;
1378
1379     basename = strrchr(pathname, LHA_PATHSEP);
1380     if (basename) {
1381         basename++;
1382         name_length = strlen(basename);
1383         dirname = pathname;
1384         dir_length = basename - dirname;
1385     }
1386     else {
1387         basename = pathname;
1388         name_length = strlen(basename);
1389         dirname = "";
1390         dir_length = 0;
1391     }
1392
1393     setup_put(data);
1394     memset(data, 0, LZHEADER_STORAGE);
1395
1396     put_byte(0x00);             /* header size */
1397     put_byte(0x00);             /* check sum */
1398     put_bytes(hdr->method, 5);
1399     put_longword(hdr->packed_size);
1400     put_longword(hdr->original_size);
1401     put_longword(unix_to_generic_stamp(hdr->unix_last_modified_stamp));
1402     put_byte(0x20);
1403     put_byte(hdr->header_level); /* level 1 */
1404
1405     /* level 1 header: write filename (basename only) */
1406     limit = 255 - 27 + 2;
1407     if (name_length > limit) {
1408         put_byte(0);            /* name length */
1409     }
1410     else {
1411         put_byte(name_length);
1412         put_bytes(basename, name_length);
1413     }
1414
1415     put_word(hdr->crc);
1416
1417     if (generic_format)
1418         put_byte(0x00);
1419     else
1420         put_byte(EXTEND_UNIX);
1421
1422     /* write extend header from here. */
1423
1424     extend_header_top = put_ptr+2; /* +2 for the field `next header size' */
1425     header_size = extend_header_top - data - 2;
1426
1427     /* write filename and dirname */
1428
1429     if (name_length > limit) {
1430         put_word(name_length + 3); /* size */
1431         put_byte(0x01);         /* filename */
1432         put_bytes(basename, name_length);
1433     }
1434
1435     if (dir_length > 0) {
1436         put_word(dir_length + 3); /* size */
1437         put_byte(0x02);         /* dirname */
1438         put_bytes(dirname, dir_length);
1439     }
1440
1441     if (!generic_format)
1442         write_unix_info(hdr);
1443
1444     put_word(0x0000);           /* next header size */
1445
1446     extend_header_size = put_ptr - extend_header_top;
1447     /* On level 1 header, the packed size field is contains the ext-header */
1448     hdr->packed_size += put_ptr - extend_header_top;
1449
1450     /* put `skip size' */
1451     setup_put(data + I_PACKED_SIZE);
1452     put_longword(hdr->packed_size);
1453
1454     data[I_HEADER_SIZE] = header_size;
1455     data[I_HEADER_CHECKSUM] = calc_sum(data + I_METHOD, header_size);
1456
1457     return header_size + extend_header_size + 2;
1458 }
1459
1460 static int
1461 write_header_level2(data, hdr, pathname)
1462     LzHeader *hdr;
1463     char *data, *pathname;
1464 {
1465     int name_length, dir_length;
1466     char *basename, *dirname;
1467     int header_size;
1468     char *extend_header_top;
1469     char *headercrc_ptr;
1470     unsigned int hcrc;
1471
1472     basename = strrchr(pathname, LHA_PATHSEP);
1473     if (basename) {
1474         basename++;
1475         name_length = strlen(basename);
1476         dirname = pathname;
1477         dir_length = basename - dirname;
1478     }
1479     else {
1480         basename = pathname;
1481         name_length = strlen(basename);
1482         dirname = "";
1483         dir_length = 0;
1484     }
1485
1486     setup_put(data);
1487     memset(data, 0, LZHEADER_STORAGE);
1488
1489     put_word(0x0000);           /* header size */
1490     put_bytes(hdr->method, 5);
1491     put_longword(hdr->packed_size);
1492     put_longword(hdr->original_size);
1493     put_longword(hdr->unix_last_modified_stamp);
1494     put_byte(0x20);
1495     put_byte(hdr->header_level); /* level 2 */
1496
1497     put_word(hdr->crc);
1498
1499     if (generic_format)
1500         put_byte(0x00);
1501     else
1502         put_byte(EXTEND_UNIX);
1503
1504     /* write extend header from here. */
1505
1506     extend_header_top = put_ptr+2; /* +2 for the field `next header size' */
1507
1508     /* write common header */
1509     put_word(5);
1510     put_byte(0x00);
1511     headercrc_ptr = put_ptr;
1512     put_word(0x0000);           /* header CRC */
1513
1514     /* write filename and dirname */
1515     /* must have this header, even if the name_length is 0. */
1516     put_word(name_length + 3);  /* size */
1517     put_byte(0x01);             /* filename */
1518     put_bytes(basename, name_length);
1519
1520     if (dir_length > 0) {
1521         put_word(dir_length + 3); /* size */
1522         put_byte(0x02);         /* dirname */
1523         put_bytes(dirname, dir_length);
1524     }
1525
1526     if (!generic_format)
1527         write_unix_info(hdr);
1528
1529     put_word(0x0000);           /* next header size */
1530
1531     header_size = put_ptr - data;
1532     if ((header_size & 0xff) == 0) {
1533         /* cannot put zero at the first byte on level 2 header. */
1534         /* adjust header size. */
1535         put_byte(0);            /* padding */
1536         header_size++;
1537     }
1538
1539     /* put hader size */
1540     setup_put(data + I_HEADER_SIZE);
1541     put_word(header_size);
1542
1543     /* put hader CRC in extended header */
1544     INITIALIZE_CRC(hcrc);
1545     hcrc = calccrc(hcrc, data, (unsigned int) header_size);
1546     setup_put(headercrc_ptr);
1547     put_word(hcrc);
1548
1549     return header_size;
1550 }
1551
1552 void
1553 write_header(fp, hdr)
1554     FILE           *fp;
1555     LzHeader       *hdr;
1556 {
1557     int header_size;
1558     char data[LZHEADER_STORAGE];
1559
1560     int archive_kanji_code = CODE_SJIS;
1561     int system_kanji_code = default_system_kanji_code;
1562     char *archive_delim = "\377";
1563     char *system_delim = "/";
1564     int filename_case = NONE;
1565     char pathname[FILENAME_LENGTH];
1566
1567     if (optional_archive_kanji_code)
1568         archive_kanji_code = optional_archive_kanji_code;
1569     if (optional_system_kanji_code)
1570         system_kanji_code = optional_system_kanji_code;
1571
1572     if (generic_format)
1573         filename_case = TO_UPPER;
1574
1575     if (hdr->header_level == HEADER_LEVEL0) {
1576         archive_delim = "\\";
1577     }
1578
1579         if ((hdr->unix_mode & UNIX_FILE_SYMLINK) == UNIX_FILE_SYMLINK) {
1580         char *p;
1581         p = strchr(hdr->name, '|');
1582         if (p) {
1583             error("symlink name \"%s\" contains '|' char. change it into '_'",
1584                   hdr->name);
1585             *p = '_';
1586         }
1587         if (xsnprintf(pathname, sizeof(pathname),
1588                       "%s|%s", hdr->name, hdr->realname) == -1)
1589             error("file name is too long (%s -> %s)", hdr->name, hdr->realname);
1590     }
1591     else {
1592         strncpy(pathname, hdr->name, sizeof(pathname));
1593         pathname[sizeof(pathname)-1] = 0;
1594     }
1595
1596     convert_filename(pathname, strlen(pathname), sizeof(pathname),
1597                      system_kanji_code,
1598                      archive_kanji_code,
1599                      system_delim, archive_delim, filename_case);
1600
1601     switch (hdr->header_level) {
1602     case 0:
1603         header_size = write_header_level0(data, hdr, pathname);
1604         break;
1605     case 1:
1606         header_size = write_header_level1(data, hdr, pathname);
1607         break;
1608     case 2:
1609         header_size = write_header_level2(data, hdr, pathname);
1610         break;
1611     default:
1612         error("Unknown level header (level %d)", hdr->header_level);
1613         exit(1);
1614     }
1615
1616     if (fwrite(data, header_size, 1, fp) == 0)
1617         fatal_error("Cannot write to temporary file");
1618 }
1619
1620 #if MULTIBYTE_FILENAME
1621
1622 #if defined(__APPLE__)
1623
1624 #include <CoreFoundation/CFString.h>
1625 #include <CoreFoundation/CFStringEncodingExt.h>
1626
1627 /* this is not need for Mac OS X v 10.2 later */
1628 enum {
1629   kCFStringEncodingAllowLossyConversion = 1,
1630   kCFStringEncodingBasicDirectionLeftToRight = (1 << 1),
1631   kCFStringEncodingBasicDirectionRightToLeft = (1 << 2),
1632   kCFStringEncodingSubstituteCombinings = (1 << 3),
1633   kCFStringEncodingComposeCombinings = (1 << 4),
1634   kCFStringEncodingIgnoreCombinings = (1 << 5),
1635   kCFStringEncodingUseCanonical = (1 << 6),
1636   kCFStringEncodingUseHFSPlusCanonical = (1 << 7),
1637   kCFStringEncodingPrependBOM = (1 << 8),
1638   kCFStringEncodingDisableCorporateArea = (1 << 9),
1639   kCFStringEncodingASCIICompatibleConversion = (1 << 10),
1640 };
1641
1642 static int
1643 ConvertEncodingToUTF8(const char* inCStr,
1644                       char* outUTF8Buffer,
1645                       int outUTF8BufferLength,
1646                       unsigned long scriptEncoding,
1647                       unsigned long flags)
1648 {
1649     unsigned long unicodeChars;
1650     unsigned long srcCharsUsed;
1651     unsigned long usedByteLen = 0;
1652     UniChar uniStr[512];
1653     unsigned long cfResult;
1654
1655     cfResult = CFStringEncodingBytesToUnicode(scriptEncoding,
1656                                               flags,
1657                                               (char *)inCStr,
1658                                               strlen(inCStr),
1659                                               &srcCharsUsed,
1660                                               uniStr,
1661                                               512,
1662                                               &unicodeChars);
1663     if (cfResult == 0) {
1664         cfResult = CFStringEncodingUnicodeToBytes(kCFStringEncodingUTF8,
1665                                                   flags,
1666                                                   uniStr,
1667                                                   unicodeChars,
1668                                                   &srcCharsUsed,
1669                                                   (char*)outUTF8Buffer,
1670                                                   outUTF8BufferLength - 1,
1671                                                   &usedByteLen);
1672         outUTF8Buffer[usedByteLen] = '\0';
1673     }
1674
1675     return cfResult;
1676 }
1677
1678 static int
1679 ConvertUTF8ToEncoding(const char* inUTF8Buf,
1680                       int inUTF8BufLength,
1681                       char* outCStrBuffer,
1682                       int outCStrBufferLength,
1683                       unsigned long scriptEncoding,
1684                       unsigned long flags)
1685 {
1686     unsigned long unicodeChars;
1687     unsigned long srcCharsUsed;
1688     unsigned long usedByteLen = 0;
1689     UniChar uniStr[256];
1690     unsigned long cfResult;
1691
1692     cfResult = CFStringEncodingBytesToUnicode(kCFStringEncodingUTF8,
1693                                               flags,
1694                                               (char*)inUTF8Buf,
1695                                               inUTF8BufLength,
1696                                               &srcCharsUsed,
1697                                               uniStr,
1698                                               255,
1699                                               &unicodeChars);
1700     if (cfResult == 0) {
1701         cfResult = CFStringEncodingUnicodeToBytes(scriptEncoding,
1702                                                   flags,
1703                                                   uniStr,
1704                                                   unicodeChars,
1705                                                   &srcCharsUsed,
1706                                                   (char*)outCStrBuffer,
1707                                                   outCStrBufferLength - 1,
1708                                                   &usedByteLen);
1709         outCStrBuffer[usedByteLen] = '\0';
1710     }
1711
1712     return cfResult;
1713 }
1714
1715 #elif HAVE_ICONV
1716 #include <iconv.h>
1717
1718 static int
1719 ConvertEncodingByIconv(const char *src, char *dst, int dstsize,
1720                        const char *srcEnc, const char *dstEnc)
1721 {
1722     iconv_t ic;
1723     static char szTmpBuf[2048];
1724     char *src_p;
1725     char *dst_p;
1726     size_t sLen;
1727     size_t iLen;
1728
1729     dst_p = &szTmpBuf[0];
1730     iLen = (size_t)sizeof(szTmpBuf)-1;
1731     src_p = (char *)src;
1732     sLen = (size_t)strlen(src);
1733     memset(szTmpBuf, 0, sizeof(szTmpBuf));
1734     memset(dst, 0, dstsize);
1735
1736     ic = iconv_open(dstEnc, srcEnc);
1737     if (ic == (iconv_t)-1) {
1738         error("iconv_open() failure: %s", strerror(errno));
1739         return -1;
1740     }
1741
1742     if (iconv(ic, &src_p, &sLen, &dst_p, &iLen) == (size_t)-1) {
1743         error("iconv() failure: %s", strerror(errno));
1744         iconv_close(ic);
1745         return -1;
1746     }
1747
1748     strncpy(dst, szTmpBuf, dstsize);
1749
1750     iconv_close(ic);
1751
1752     return 0;
1753 }
1754 #endif /* defined(__APPLE__) */
1755
1756 char *
1757 sjis_to_utf8(char *dst, const char *src, size_t dstsize)
1758 {
1759 #if defined(__APPLE__)
1760   dst[0] = '\0';
1761   if (ConvertEncodingToUTF8(src, dst, dstsize,
1762                             kCFStringEncodingDOSJapanese,
1763                             kCFStringEncodingUseHFSPlusCanonical) == 0)
1764       return dst;
1765 #elif HAVE_ICONV
1766   if (ConvertEncodingByIconv(src, dst, dstsize, "SJIS", "UTF-8") != -1)
1767       return dst;
1768 #else
1769   error("not support utf-8 conversion");
1770 #endif
1771
1772   if (dstsize < 1) return dst;
1773   dst[dstsize-1] = 0;
1774   return strncpy(dst, src, dstsize-1);
1775 }
1776
1777 char *
1778 utf8_to_sjis(char *dst, const char *src, size_t dstsize)
1779 {
1780 #if defined(__APPLE__)
1781   int srclen;
1782
1783   dst[0] = '\0';
1784   srclen = strlen(src);
1785   if (ConvertUTF8ToEncoding(src, srclen, dst, dstsize,
1786                             kCFStringEncodingDOSJapanese,
1787                             kCFStringEncodingUseHFSPlusCanonical) == 0)
1788       return dst;
1789 #elif HAVE_ICONV
1790   if (ConvertEncodingByIconv(src, dst, dstsize, "UTF-8", "SJIS") != -1)
1791       return dst;
1792 #else
1793   error("not support utf-8 conversion");
1794 #endif
1795
1796   if (dstsize < 1) return dst;
1797   dst[dstsize-1] = 0;
1798   return strncpy(dst, src, dstsize-1);
1799 }
1800
1801 /*
1802  * SJIS <-> EUC ÊÑ´¹´Ø¿ô
1803  * ¡ÖÆüËܸì¾ðÊó½èÍý¡×   ¥½¥Õ¥È¥Ð¥ó¥¯(³ô)
1804  *      ¤è¤êÈ´¿è(by Koji Arai)
1805  */
1806 void
1807 euc2sjis(int *p1, int *p2)
1808 {
1809     unsigned char c1 = *p1 & 0x7f;
1810     unsigned char c2 = *p2 & 0x7f;
1811     int rowoff = c1 < 0x5f ? 0x70 : 0xb0;
1812     int celoff = c1 % 2 ? (c2 > 0x5f ? 0x20 : 0x1f) : 0x7e;
1813     *p1 = ((c1 + 1) >> 1) + rowoff;
1814     *p2 += celoff - 0x80;
1815 }
1816
1817 void
1818 sjis2euc(int *p1, int *p2)
1819 {
1820     unsigned char c1 = *p1;
1821     unsigned char c2 = *p2;
1822     int adjust = c2 < 0x9f;
1823     int rowoff = c1 < 0xa0 ? 0x70 : 0xb0;
1824     int celoff = adjust ? (c2 > 0x7f ? 0x20 : 0x1f) : 0x7e;
1825     *p1 = ((c1 - rowoff) << 1) - adjust;
1826     *p2 -= celoff;
1827
1828     *p1 |= 0x80;
1829     *p2 |= 0x80;
1830 }
1831 #endif /* MULTIBYTE_FILENAME */
1832
1833 /* Local Variables: */
1834 /* mode:c */
1835 /* tab-width:4 */
1836 /* compile-command:"gcc -c header.c" */
1837 /* End: */
1838 /* vi: set tabstop=4: */