OSDN Git Service

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