OSDN Git Service

applied the patch for the DJGPP.
[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 (!(S_ISLNK(hdr->unix_mode)))
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 (!(S_ISLNK(hdr->unix_mode)))
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 (S_ISREG(hdr->unix_mode)
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 defined(__MINGW32__) || defined(__DJGPP__)
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 defined(__MINGW32__) || defined(__DJGPP__)
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 (S_ISDIR(hdr->unix_mode)
439              || S_ISLNK(hdr->unix_mode)
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 (S_ISLNK(hdr->unix_mode)) {
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             }
486             else { /* make directory */
487                 if (!output_to_stdout && !make_parent_path(name))
488                     return read_size;
489                 /* save directory information */
490                 add_dirinfo(name, hdr);
491             }
492         }
493     }
494     else {
495         if (force)              /* force extract */
496             goto extract_regular;
497         else
498             error("Unknown file type: \"%s\". use `f' option to force extract.", name);
499     }
500
501     if (!output_to_stdout)
502         adjust_info(name, hdr);
503
504     return read_size;
505 }
506
507 /* ------------------------------------------------------------------------ */
508 /* EXTRACT COMMAND MAIN                                                     */
509 /* ------------------------------------------------------------------------ */
510 void
511 cmd_extract()
512 {
513     LzHeader        hdr;
514     off_t           pos;
515     FILE           *afp;
516     size_t read_size;
517
518     /* open archive file */
519     if ((afp = open_old_archive()) == NULL)
520         fatal_error("Cannot open archive file \"%s\"", archive_name);
521
522     if (archive_is_msdos_sfx1(archive_name))
523         seek_lha_header(afp);
524
525     /* extract each files */
526     while (get_header(afp, &hdr)) {
527         if (need_file(hdr.name)) {
528             pos = ftello(afp);
529             read_size = extract_one(afp, &hdr);
530             if (read_size != hdr.packed_size) {
531                 /* when error occurred in extract_one(), should adjust
532                    point of file stream */
533                 if (pos != -1 && afp != stdin)
534                     fseeko(afp, pos + hdr.packed_size - read_size, SEEK_SET);
535                 else {
536                     size_t i = hdr.packed_size - read_size;
537                     while (i--) fgetc(afp);
538                 }
539             }
540         } else {
541             if (afp != stdin)
542                 fseeko(afp, hdr.packed_size, SEEK_CUR);
543             else {
544                 size_t i = hdr.packed_size;
545                 while (i--) fgetc(afp);
546             }
547         }
548     }
549
550     /* close archive file */
551     fclose(afp);
552
553     /* adjust directory information */
554     adjust_dirinfo();
555
556     return;
557 }
558
559 int
560 is_directory_traversal(char *path)
561 {
562     int state = 0;
563
564     for (; *path; path++) {
565         switch (state) {
566         case 0:
567             if (*path == '.') state = 1;
568             else state = 3;
569             break;
570         case 1:
571             if (*path == '.') state = 2;
572             else if (*path == '/') state = 0;
573             else state = 3;
574             break;
575         case 2:
576             if (*path == '/') return 1;
577             else state = 3;
578             break;
579         case 3:
580             if (*path == '/') state = 0;
581             break;
582         }
583     }
584
585     return state == 2;
586 }
587
588 /*
589  * restore directory information (time stamp).
590  * added by A.Iriyama  2003.12.12
591  */
592
593 typedef struct lhdDirectoryInfo_t {
594     struct lhdDirectoryInfo_t *next;
595     LzHeader hdr;
596 } LzHeaderList;
597
598 static LzHeaderList *dirinfo;
599
600 static void add_dirinfo(char *name, LzHeader *hdr)
601 {
602     LzHeaderList *p;
603
604     if (memcmp(hdr->method, LZHDIRS_METHOD, 5) != 0)
605         return;
606
607     p = xmalloc(sizeof(LzHeaderList));
608
609     memcpy(&p->hdr, hdr, sizeof(LzHeader));
610     strncpy(p->hdr.name, name, sizeof(p->hdr.name));
611     p->hdr.name[sizeof(p->hdr.name)-1] = 0;
612
613     {
614         LzHeaderList *tmp = dirinfo;
615         dirinfo = p;
616         dirinfo->next = tmp;
617     }
618 }
619
620 static void adjust_dirinfo()
621 {
622     while (dirinfo) {
623         adjust_info(dirinfo->hdr.name, &dirinfo->hdr);
624
625         {
626             LzHeaderList *tmp = dirinfo;
627             dirinfo = dirinfo->next;
628             free(tmp);
629         }
630     }
631 }
632
633 #if HAVE_LIBAPPLEFILE
634 static boolean
635 decode_macbinary(ofp, size, outPath)
636     FILE *ofp;
637     size_t size;
638     const char *outPath;
639 {
640     af_file_t *afp = NULL;
641     FILE *ifp = NULL;
642     unsigned char *datap;
643     size_t dlen;
644
645     if ((afp = af_open(temporary_name)) != NULL) {
646         /* fetch datafork */
647         datap = af_data(afp, &dlen);
648         fwrite(datap, sizeof(unsigned char), dlen, ofp);
649         af_close(afp);
650         return TRUE;
651     } else { /* it may be not encoded in MacBinary */
652         /* try to copy */
653         if ((ifp = fopen(temporary_name, READ_BINARY)) == NULL) {
654             error("Cannot open a temporary file \"%s\"", temporary_name);
655             return FALSE;
656         }
657         copyfile(ifp, ofp, size, 0, 0);
658         fclose(ifp);
659         return TRUE;
660     }
661
662     return FALSE;
663 }
664 #endif /* HAVE_LIBAPPLEFILE */