OSDN Git Service

* config.h.in (HAVE_LIBAPPLEFILE): added `b' option which extract the MacBinary....
[lha/lha.git] / src / lhext.c
1 /* ------------------------------------------------------------------------ */
2 /* LHa for UNIX                                                             */
3 /*              lhext.c -- LHarc extract                                    */
4 /*                                                                          */
5 /*      Copyright (C) MCMLXXXIX Yooichi.Tagawa                              */
6 /*      Modified                Nobutaka Watazaki                           */
7 /*                                                                          */
8 /*  Ver. 0.00  Original                             1988.05.23  Y.Tagawa    */
9 /*  Ver. 1.00  Fixed                                1989.09.22  Y.Tagawa    */
10 /*  Ver. 0.03  LHa for UNIX                         1991.12.17  M.Oki       */
11 /*  Ver. 1.12  LHa for UNIX                         1993.10.01  N.Watazaki  */
12 /*  Ver. 1.13b Symbolic Link Update Bug Fix         1994.06.21  N.Watazaki  */
13 /*  Ver. 1.14  Source All chagned                   1995.01.14  N.Watazaki  */
14 /*  Ver. 1.14e bugfix                               1999.04.30  T.Okamoto   */
15 /* ------------------------------------------------------------------------ */
16 #include "lha.h"
17 /* ------------------------------------------------------------------------ */
18 static int      skip_flg = FALSE;   /* FALSE..No Skip , TRUE..Skip */
19 static char    *methods[] =
20 {
21     LZHUFF0_METHOD, LZHUFF1_METHOD, LZHUFF2_METHOD, LZHUFF3_METHOD,
22     LZHUFF4_METHOD, LZHUFF5_METHOD, LZHUFF6_METHOD, LZHUFF7_METHOD,
23     LARC_METHOD, LARC5_METHOD, LARC4_METHOD,
24     LZHDIRS_METHOD,
25     NULL
26 };
27
28 static void add_dirinfo(char* name, LzHeader* hdr);
29 static void adjust_dirinfo();
30
31 #ifdef HAVE_LIBAPPLEFILE
32 static boolean decode_macbinary(FILE *ofp, size_t size, const char *outPath);
33 #endif
34
35 /* ------------------------------------------------------------------------ */
36 static          boolean
37 inquire_extract(name)
38     char           *name;
39 {
40     struct stat     stbuf;
41
42     skip_flg = FALSE;
43     if (stat(name, &stbuf) >= 0) {
44         if (!is_regularfile(&stbuf)) {
45             error("\"%s\" already exists (not a file)", name);
46             return FALSE;
47         }
48
49         if (noexec) {
50             printf("EXTRACT %s but file is exist.\n", name);
51             return FALSE;
52         }
53         else if (!force) {
54             if (!isatty(0)) {
55                 warning("skip to extract %s.", name);
56                 return FALSE;
57             }
58
59             switch (inquire("OverWrite ?(Yes/[No]/All/Skip)", name, "YyNnAaSs\n")) {
60             case 0:
61             case 1:/* Y/y */
62                 break;
63             case 2:
64             case 3:/* N/n */
65             case 8:/* Return */
66                 return FALSE;
67             case 4:
68             case 5:/* A/a */
69                 force = TRUE;
70                 break;
71             case 6:
72             case 7:/* S/s */
73                 skip_flg = TRUE;
74                 break;
75             }
76         }
77     }
78
79     if (noexec)
80         printf("EXTRACT %s\n", name);
81
82     return TRUE;
83 }
84
85 /* ------------------------------------------------------------------------ */
86 static          boolean
87 make_parent_path(name)
88     char           *name;
89 {
90     char            path[FILENAME_LENGTH];
91     struct stat     stbuf;
92     register char  *p;
93
94     /* make parent directory name into PATH for recursive call */
95     str_safe_copy(path, name, sizeof(path));
96     for (p = path + strlen(path); p > path; p--)
97         if (p[-1] == '/') {
98             *--p = '\0';
99             break;
100         }
101
102     if (p == path) {
103         message("invalid path name \"%s\"", name);
104         return FALSE;   /* no more parent. */
105     }
106
107     if (GETSTAT(path, &stbuf) >= 0) {
108         if (is_directory(&stbuf))
109             return TRUE;
110     }
111
112     if (verbose)
113         message("Making directory \"%s\".", path);
114
115 #if defined __MINGW32__
116     if (mkdir(path) >= 0)
117         return TRUE;
118 #else
119     if (mkdir(path, 0777) >= 0) /* try */
120         return TRUE;    /* successful done. */
121 #endif
122
123     if (!make_parent_path(path))
124         return FALSE;
125
126 #if defined __MINGW32__
127     if (mkdir(path) < 0) {      /* try again */
128         error("Cannot make directory \"%s\"", path);
129         return FALSE;
130     }
131 #else
132     if (mkdir(path, 0777) < 0) {    /* try again */
133         error("Cannot make directory \"%s\"", path);
134         return FALSE;
135     }
136 #endif
137
138     return TRUE;
139 }
140
141 /* ------------------------------------------------------------------------ */
142 static FILE    *
143 open_with_make_path(name)
144     char           *name;
145 {
146     FILE           *fp;
147
148     if ((fp = fopen(name, WRITE_BINARY)) == NULL) {
149         if (!make_parent_path(name) ||
150             (fp = fopen(name, WRITE_BINARY)) == NULL)
151             error("Cannot extract a file \"%s\"", name);
152     }
153     return fp;
154 }
155
156 /* ------------------------------------------------------------------------ */
157 static void
158 adjust_info(name, hdr)
159     char           *name;
160     LzHeader       *hdr;
161 {
162     struct utimbuf utimebuf;
163
164     /* adjust file stamp */
165     utimebuf.actime = utimebuf.modtime = hdr->unix_last_modified_stamp;
166
167     if ((hdr->unix_mode & UNIX_FILE_TYPEMASK) != UNIX_FILE_SYMLINK)
168         utime(name, &utimebuf);
169
170     if (hdr->extend_type == EXTEND_UNIX
171         || hdr->extend_type == EXTEND_OS68K
172         || hdr->extend_type == EXTEND_XOSK) {
173 #ifdef NOT_COMPATIBLE_MODE
174         Please need your modification in this space.
175 #else
176         if ((hdr->unix_mode & UNIX_FILE_TYPEMASK) != UNIX_FILE_SYMLINK)
177             chmod(name, hdr->unix_mode);
178 #endif
179         if (!getuid()){
180             uid_t uid = hdr->unix_uid;
181             gid_t gid = hdr->unix_gid;
182
183 #if HAVE_GETPWNAM && HAVE_GETGRNAM
184             if (hdr->user[0]) {
185                 struct passwd *ent = getpwnam(hdr->user);
186                 if (ent) uid = ent->pw_uid;
187             }
188             if (hdr->group[0]) {
189                 struct group *ent = getgrnam(hdr->group);
190                 if (ent) gid = ent->gr_gid;
191             }
192 #endif
193
194 #if HAVE_LCHOWN
195             if ((hdr->unix_mode & UNIX_FILE_TYPEMASK) == UNIX_FILE_SYMLINK)
196                 lchown(name, uid, gid);
197             else
198 #endif /* HAVE_LCHWON */
199                 chown(name, uid, gid);
200         }
201     }
202 #if __CYGWIN__
203     else {
204         /* On Cygwin, execute permission should be set for .exe or .dll. */
205         mode_t m;
206
207         umask(m = umask(0));    /* get current umask */
208         chmod(name, 0777 & ~m);
209     }
210 #endif
211 }
212
213 /* ------------------------------------------------------------------------ */
214 static size_t
215 extract_one(afp, hdr)
216     FILE           *afp;    /* archive file */
217     LzHeader       *hdr;
218 {
219     FILE           *fp; /* output file */
220 #if HAVE_LIBAPPLEFILE
221     FILE           *tfp; /* temporary output file */
222 #endif
223     struct stat     stbuf;
224     char            name[FILENAME_LENGTH];
225     unsigned int crc;
226     int             method;
227     boolean         save_quiet, save_verbose, up_flag;
228     char           *q = hdr->name, c;
229     size_t read_size = 0;
230
231     if (ignore_directory && strrchr(hdr->name, '/')) {
232         q = (char *) strrchr(hdr->name, '/') + 1;
233     }
234     else {
235         if (is_directory_traversal(q)) {
236             fprintf(stderr, "Possible directory traversal hack attempt in %s\n", q);
237             exit(111);
238         }
239
240         if (*q == '/') {
241             while (*q == '/') { q++; }
242
243             /*
244              * if OSK then strip device name
245              */
246             if (hdr->extend_type == EXTEND_OS68K
247                 || hdr->extend_type == EXTEND_XOSK) {
248                 do
249                     c = (*q++);
250                 while (c && c != '/');
251                 if (!c || !*q)
252                     q = ".";    /* if device name only */
253             }
254         }
255     }
256
257     if (extract_directory)
258         xsnprintf(name, sizeof(name), "%s/%s", extract_directory, q);
259     else
260         str_safe_copy(name, q, sizeof(name));
261
262     /* LZHDIRS_METHOD¤ò»ý¤Ä¥Ø¥Ã¥À¤ò¥Á¥§¥Ã¥¯¤¹¤ë */
263     /* 1999.4.30 t.okamoto */
264     for (method = 0;; method++) {
265         if (methods[method] == NULL) {
266             error("Unknown method \"%.*s\"; \"%s\" will be skiped ...",
267                   5, hdr->method, name);
268             return read_size;
269         }
270         if (memcmp(hdr->method, methods[method], 5) == 0)
271             break;
272     }
273
274     if ((hdr->unix_mode & UNIX_FILE_TYPEMASK) == UNIX_FILE_REGULAR
275         && method != LZHDIRS_METHOD_NUM) {
276     extract_regular:
277 #if 0
278         for (method = 0;; method++) {
279             if (methods[method] == NULL) {
280                 error("Unknown method \"%.*s\"; \"%s\" will be skiped ...",
281                       5, hdr->method, name);
282                 return read_size;
283             }
284             if (memcmp(hdr->method, methods[method], 5) == 0)
285                 break;
286         }
287 #endif
288
289         reading_filename = archive_name;
290         writing_filename = name;
291         if (output_to_stdout || verify_mode) {
292             /* "Icon\r" should be a resource fork file encoded in MacBinary
293                format, so that it should be skipped. */
294             if (hdr->extend_type == EXTEND_MACOS
295                 && strcmp(basename(name), "Icon\r") == 0
296                 && decode_macbinary_contents) {
297                 return read_size;
298             }
299
300             if (noexec) {
301                 printf("%s %s\n", verify_mode ? "VERIFY" : "EXTRACT", name);
302                 return read_size;
303             }
304
305             save_quiet = quiet;
306             save_verbose = verbose;
307             if (!quiet && output_to_stdout) {
308                 printf("::::::::\n%s\n::::::::\n", name);
309                 quiet = TRUE;
310                 verbose = FALSE;
311             }
312             else if (verify_mode) {
313                 quiet = FALSE;
314                 verbose = TRUE;
315             }
316
317 #if __MINGW32__
318             {
319                 int old_mode;
320                 fflush(stdout);
321                 old_mode = setmode(fileno(stdout), O_BINARY);
322 #endif
323
324 #if HAVE_LIBAPPLEFILE
325             /* On default, MacLHA encodes into MacBinary. */
326             if (hdr->extend_type == EXTEND_MACOS && !verify_mode && decode_macbinary_contents) {
327                 /* build temporary file */
328                 tfp = NULL; /* avoid compiler warnings `uninitialized' */
329                 tfp = build_temporary_file();
330
331                 crc = decode_lzhuf(afp, tfp,
332                                    hdr->original_size, hdr->packed_size,
333                                    name, method, &read_size);
334                 fclose(tfp);
335                 decode_macbinary(stdout, hdr->original_size, name);
336                 unlink(temporary_name);
337             } else {
338                 crc = decode_lzhuf(afp, stdout,
339                                    hdr->original_size, hdr->packed_size,
340                                    name, method, &read_size);
341             }
342 #else
343             crc = decode_lzhuf(afp, stdout,
344                                hdr->original_size, hdr->packed_size,
345                                name, method, &read_size);
346 #endif /* HAVE_LIBAPPLEFILE */
347 #if __MINGW32__
348                 fflush(stdout);
349                 setmode(fileno(stdout), old_mode);
350             }
351 #endif
352             quiet = save_quiet;
353             verbose = save_verbose;
354         }
355         else {
356 #ifndef __APPLE__
357             /* "Icon\r" should be a resource fork of parent folder's icon,
358                so that it can be skipped when system is not Mac OS X. */
359             if (hdr->extend_type == EXTEND_MACOS
360                 && strcmp(basename(name), "Icon\r") == 0
361                 && decode_macbinary_contents) {
362                 make_parent_path(name); /* create directory only */
363                 return read_size;
364             }
365 #endif /* __APPLE__ */
366             if (skip_flg == FALSE)  {
367                 up_flag = inquire_extract(name);
368                 if (up_flag == FALSE && force == FALSE) {
369                     return read_size;
370                 }
371             }
372
373             if (skip_flg == TRUE) { /* if skip_flg */
374                 if (stat(name, &stbuf) == 0 && force != TRUE) {
375                     if (stbuf.st_mtime >= hdr->unix_last_modified_stamp) {
376                         if (quiet != TRUE)
377                             printf("%s : Skipped...\n", name);
378                         return read_size;
379                     }
380                 }
381             }
382             if (noexec) {
383                 return read_size;
384             }
385
386             signal(SIGINT, interrupt);
387 #ifdef SIGHUP
388             signal(SIGHUP, interrupt);
389 #endif
390
391             unlink(name);
392             remove_extracting_file_when_interrupt = TRUE;
393
394             if ((fp = open_with_make_path(name)) != NULL) {
395 #if HAVE_LIBAPPLEFILE
396                 if (hdr->extend_type == EXTEND_MACOS && !verify_mode && decode_macbinary_contents) {
397                     /* build temporary file */
398                     tfp = NULL; /* avoid compiler warnings `uninitialized' */
399                     tfp = build_temporary_file();
400
401                     crc = decode_lzhuf(afp, tfp,
402                                        hdr->original_size, hdr->packed_size,
403                                        name, method, &read_size);
404                     fclose(tfp);
405                     decode_macbinary(fp, hdr->original_size, name);
406 #ifdef __APPLE__
407                     /* TODO: set resource fork */
408                     /* after processing, "Icon\r" is not needed. */
409                     if (strcmp(basename(name), "Icon\r") == 0) {
410                         unlink(name);
411                     }
412 #endif /* __APPLE__ */
413                     unlink(temporary_name);
414                 } else {
415                     crc = decode_lzhuf(afp, fp,
416                                        hdr->original_size, hdr->packed_size,
417                                        name, method, &read_size);
418                 }
419 #else /* HAVE_LIBAPPLEFILE */
420                 crc = decode_lzhuf(afp, fp,
421                                    hdr->original_size, hdr->packed_size,
422                                    name, method, &read_size);
423 #endif /* HAVE_LIBAPPLEFILE */
424                 fclose(fp);
425             }
426             remove_extracting_file_when_interrupt = FALSE;
427             signal(SIGINT, SIG_DFL);
428 #ifdef SIGHUP
429             signal(SIGHUP, SIG_DFL);
430 #endif
431             if (!fp)
432                 return read_size;
433         }
434
435         if (hdr->has_crc && crc != hdr->crc)
436             error("CRC error: \"%s\"", name);
437     }
438     else if ((hdr->unix_mode & UNIX_FILE_TYPEMASK) == UNIX_FILE_DIRECTORY
439              || (hdr->unix_mode & UNIX_FILE_TYPEMASK) == UNIX_FILE_SYMLINK
440              || method == LZHDIRS_METHOD_NUM) {
441         /* ¢¬¤³¤ì¤Ç¡¢Symbolic Link ¤Ï¡¢Âç¾æÉפ«¡© */
442         if (!ignore_directory && !verify_mode) {
443             if (noexec) {
444                 if (quiet != TRUE)
445                     printf("EXTRACT %s (directory)\n", name);
446                 return read_size;
447             }
448             /* NAME has trailing SLASH '/', (^_^) */
449             if ((hdr->unix_mode & UNIX_FILE_TYPEMASK) == UNIX_FILE_SYMLINK) {
450                 int             l_code;
451
452 #ifdef S_IFLNK
453                 if (skip_flg == FALSE)  {
454                     up_flag = inquire_extract(name);
455                     if (up_flag == FALSE && force == FALSE) {
456                         return read_size;
457                     }
458                 } else {
459                     if (GETSTAT(name, &stbuf) == 0 && force != TRUE) {
460                         if (stbuf.st_mtime >= hdr->unix_last_modified_stamp) {
461                             if (quiet != TRUE)
462                                 printf("%s : Skipped...\n", name);
463                             return read_size;
464                         }
465                     }
466                 }
467
468                 unlink(name);
469                 make_parent_path(name);
470                 l_code = symlink(hdr->realname, name);
471                 if (l_code < 0) {
472                     if (quiet != TRUE)
473                         warning("Can't make Symbolic Link \"%s\" -> \"%s\"",
474                                 name, hdr->realname);
475                 }
476                 if (quiet != TRUE) {
477                     message("Symbolic Link %s -> %s",
478                             name, hdr->realname);
479                 }
480 #else
481                 warning("Can't make Symbolic Link %s -> %s",
482                         name, hdr->realname);
483                 return read_size;
484 #endif
485             } else { /* make directory */
486                 if (!output_to_stdout && !make_parent_path(name))
487                     return read_size;
488                 /* save directory information */
489                 add_dirinfo(name, hdr);
490             }
491         }
492     }
493     else {
494         if (force)              /* force extract */
495             goto extract_regular;
496         else
497             error("Unknown file type: \"%s\". use `f' option to force extract.", name);
498     }
499
500     if (!output_to_stdout)
501         adjust_info(name, hdr);
502
503     return read_size;
504 }
505
506 /* ------------------------------------------------------------------------ */
507 /* EXTRACT COMMAND MAIN                                                     */
508 /* ------------------------------------------------------------------------ */
509 void
510 cmd_extract()
511 {
512     LzHeader        hdr;
513     off_t           pos;
514     FILE           *afp;
515     size_t read_size;
516
517     /* open archive file */
518     if ((afp = open_old_archive()) == NULL)
519         fatal_error("Cannot open archive file \"%s\"", archive_name);
520
521     if (archive_is_msdos_sfx1(archive_name))
522         seek_lha_header(afp);
523
524     /* extract each files */
525     while (get_header(afp, &hdr)) {
526         if (need_file(hdr.name)) {
527             pos = ftello(afp);
528             read_size = extract_one(afp, &hdr);
529             if (read_size != hdr.packed_size) {
530                 /* when error occurred in extract_one(), should adjust
531                    point of file stream */
532                 if (pos != -1 && afp != stdin)
533                     fseeko(afp, pos + hdr.packed_size - read_size, SEEK_SET);
534                 else {
535                     size_t i = hdr.packed_size - read_size;
536                     while (i--) fgetc(afp);
537                 }
538             }
539         } else {
540             if (afp != stdin)
541                 fseeko(afp, hdr.packed_size, SEEK_CUR);
542             else {
543                 size_t i = hdr.packed_size;
544                 while (i--) fgetc(afp);
545             }
546         }
547     }
548
549     /* close archive file */
550     fclose(afp);
551
552     /* adjust directory information */
553     adjust_dirinfo();
554
555     return;
556 }
557
558 int
559 is_directory_traversal(char *path)
560 {
561     int state = 0;
562
563     for (; *path; path++) {
564         switch (state) {
565         case 0:
566             if (*path == '.') state = 1;
567             else state = 3;
568             break;
569         case 1:
570             if (*path == '.') state = 2;
571             else if (*path == '/') state = 0;
572             else state = 3;
573             break;
574         case 2:
575             if (*path == '/') return 1;
576             else state = 3;
577             break;
578         case 3:
579             if (*path == '/') state = 0;
580             break;
581         }
582     }
583
584     return state == 2;
585 }
586
587 /*
588  * restore directory information (time stamp).
589  * added by A.Iriyama  2003.12.12
590  */
591
592 typedef struct lhdDirectoryInfo_t {
593     struct lhdDirectoryInfo_t *next;
594     LzHeader hdr;
595 } LzHeaderList;
596
597 static LzHeaderList *dirinfo;
598
599 static void add_dirinfo(char *name, LzHeader *hdr)
600 {
601     LzHeaderList *p;
602
603     if (memcmp(hdr->method, LZHDIRS_METHOD, 5) != 0)
604         return;
605
606     p = xmalloc(sizeof(LzHeaderList));
607
608     memcpy(&p->hdr, hdr, sizeof(LzHeader));
609     strncpy(p->hdr.name, name, sizeof(p->hdr.name));
610     p->hdr.name[sizeof(p->hdr.name)-1] = 0;
611
612     {
613         LzHeaderList *tmp = dirinfo;
614         dirinfo = p;
615         dirinfo->next = tmp;
616     }
617 }
618
619 static void adjust_dirinfo()
620 {
621     while (dirinfo) {
622         adjust_info(dirinfo->hdr.name, &dirinfo->hdr);
623
624         {
625             LzHeaderList *tmp = dirinfo;
626             dirinfo = dirinfo->next;
627             free(tmp);
628         }
629     }
630 }
631
632 #if HAVE_LIBAPPLEFILE
633 static boolean
634 decode_macbinary(ofp, size, outPath)
635     FILE *ofp;
636     size_t size;
637     const char *outPath;
638 {
639     af_file_t *afp = NULL;
640     FILE *ifp = NULL;
641     unsigned char *datap;
642     size_t dlen;
643
644     if ((afp = af_open(temporary_name)) != NULL) {
645         /* fetch datafork */
646         datap = af_data(afp, &dlen);
647         fwrite(datap, sizeof(unsigned char), dlen, ofp);
648         af_close(afp);
649         return TRUE;
650     } else { /* it may be not encoded in MacBinary */
651         /* try to copy */
652         if ((ifp = fopen(temporary_name, READ_BINARY)) == NULL) {
653             error("Cannot open a temporary file \"%s\"", temporary_name);
654             return FALSE;
655         }
656         copyfile(ifp, ofp, size, 0, 0);
657         fclose(ifp);
658         return TRUE;
659     }
660
661     return FALSE;
662 }
663 #endif /* HAVE_LIBAPPLEFILE */