Fix the build process so it does not do the evil #ifdef BB_FOO stuff.
[oweals/busybox.git] / libbb / unarchive.c
1 /*
2  *  Copyright (C) 2000 by Glenn McGrath
3  *  Copyright (C) 2001 by Laurence Anderson
4  *      
5  *  Based on previous work by busybox developers and others.
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License as published by
9  *  the Free Software Foundation; either version 2 of the License, or
10  *  (at your option) any later version.
11  *
12  *  This program is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *  GNU Library General Public License for more details.
16  *
17  *  You should have received a copy of the GNU General Public License
18  *  along with this program; if not, write to the Free Software
19  *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20  */
21
22 #include <stdio.h>
23 #include <errno.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <utime.h>
28 #include "libbb.h"
29
30 typedef struct file_headers_s {
31         char *name;
32         char *link_name;
33         off_t size;
34         uid_t uid;
35         gid_t gid;
36         mode_t mode;
37         time_t mtime;
38         dev_t device;
39 } file_header_t;
40
41
42 extern void seek_sub_file(FILE *src_stream, const int count);
43 extern char *extract_archive(FILE *src_stream, FILE *out_stream, const file_header_t *file_entry,
44  const int function, const char *prefix);
45
46
47 #ifdef L_archive_offset
48 off_t archive_offset;
49 #else
50 extern off_t archive_offset;
51 #endif  
52
53 #ifdef L_seek_sub_file
54 void seek_sub_file(FILE *src_stream, const int count)
55 {
56         int i;
57         /* Try to fseek as faster */
58         archive_offset += count;
59         if (fseek(src_stream, count, SEEK_CUR) != 0 && errno == ESPIPE) {
60         for (i = 0; i < count; i++) {
61                 fgetc(src_stream);
62                 }
63         }
64         return;
65 }
66 #endif  
67
68
69
70 #ifdef L_extract_archive
71 /* Extract the data postioned at src_stream to either filesystem, stdout or 
72  * buffer depending on the value of 'function' which is defined in libbb.h 
73  *
74  * prefix doesnt have to be just a directory, it may prefix the filename as well.
75  *
76  * e.g. '/var/lib/dpkg/info/dpkg.' will extract all files to the base bath 
77  * '/var/lib/dpkg/info/' and all files/dirs created in that dir will have 
78  * 'dpkg.' as their prefix
79  *
80  * For this reason if prefix does point to a dir then it must end with a
81  * trailing '/' or else the last dir will be assumed to be the file prefix 
82  */
83 char *extract_archive(FILE *src_stream, FILE *out_stream, const file_header_t *file_entry,
84  const int function, const char *prefix)
85 {
86         FILE *dst_stream = NULL;
87         char *full_name = NULL;
88         char *buffer = NULL;
89         struct utimbuf t;
90
91         /* prefix doesnt have to be a proper path it may prepend 
92          * the filename as well */
93         if (prefix != NULL) {
94                 /* strip leading '/' in filename to extract as prefix may not be dir */
95                 /* Cant use concat_path_file here as prefix might not be a directory */
96                 char *path = file_entry->name;
97                 if (*path == '/') {
98                         path++;
99                 }
100                 full_name = xmalloc(strlen(prefix) + strlen(path) + 1);
101                 strcpy(full_name, prefix);
102                 strcat(full_name, path);
103         } else {
104                 full_name = file_entry->name;
105         }
106
107         if (function & extract_to_stdout) {
108                 if (S_ISREG(file_entry->mode)) {
109                         copy_file_chunk(src_stream, out_stream, file_entry->size);                      
110                         archive_offset += file_entry->size;
111                 }
112         }
113         else if (function & extract_one_to_buffer) { 
114                 if (S_ISREG(file_entry->mode)) {
115                         buffer = (char *) xmalloc(file_entry->size + 1);
116                         fread(buffer, 1, file_entry->size, src_stream);
117                         archive_offset += file_entry->size;
118                         return(buffer);
119                 }
120         }
121         else if (function & extract_all_to_fs) {
122 #if 0
123                 struct stat oldfile;
124                 if ( (S_ISLNK(file_entry->mode) ? lstat (full_name, &oldfile) : stat (full_name, &oldfile)) == 0) { /* The file already exists */
125                         if (function & extract_unconditional || oldfile.st_mtime < file_entry->mtime) {
126                                 if (!S_ISDIR(oldfile.st_mode)) {
127                                         unlink(full_name); /* Directories might not be empty etc */
128                                 }
129                         } else {
130                                 error_msg("%s not created: newer or same age file exists", file_entry->name);
131                                 if (S_ISREG(file_entry->mode)) {
132                                         seek_sub_file(src_stream, file_entry->size);
133                                 }
134                                 return (NULL);
135                         }
136                 }
137 #endif
138                 switch(file_entry->mode & S_IFMT) {
139                         case S_IFREG:
140                                 if (file_entry->link_name) { /* Found a cpio hard link */
141                                         if (link(file_entry->link_name, full_name) != 0) {
142                                                 perror_msg("Cannot link from %s to '%s'",
143                                                         file_entry->name, file_entry->link_name);
144                                         }
145                                 } else {
146                                         if ((dst_stream = wfopen(full_name, "w")) == NULL) {
147                                                 seek_sub_file(src_stream, file_entry->size);
148                                                 return NULL;
149                                         }
150                                         archive_offset += file_entry->size;
151                                         copy_file_chunk(src_stream, dst_stream, file_entry->size);                      
152                                         fclose(dst_stream);
153                                 }
154                                 break;
155                         case S_IFDIR:
156                                 /* Use make_directory instead of mkdir in case prefix path hasn't been created */
157                                 if (function & extract_create_dirs) {
158                                         if (make_directory(full_name, file_entry->mode, FILEUTILS_RECUR) < 0) {
159                                                 return NULL;
160                                         }
161                                 }
162                                 break;
163                         case S_IFLNK:
164                                 if (symlink(file_entry->link_name, full_name) < 0) {
165                                         perror_msg("Cannot create symlink from %s to '%s'", file_entry->name, file_entry->link_name); 
166                                         return NULL;
167                                 }
168                                 break;
169                         case S_IFSOCK:
170                         case S_IFBLK:
171                         case S_IFCHR:
172                         case S_IFIFO:
173                                 if (mknod(full_name, file_entry->mode, file_entry->device) == -1) {
174                                         perror_msg("Cannot create node %s", file_entry->name);
175                                         return NULL;
176                                 }
177                                 break;
178                 }
179
180                 /* Changing a symlink's properties normally changes the properties of the 
181                  * file pointed to, so dont try and change the date or mode, lchown does
182                  * does the right thing, but isnt available in older versions of libc */
183                 if (S_ISLNK(file_entry->mode)) {
184 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
185                         lchown(full_name, file_entry->uid, file_entry->gid);
186 #endif
187                 } else {
188                         if (function & extract_preserve_date) {
189                                 t.actime = file_entry->mtime;
190                                 t.modtime = file_entry->mtime;
191                                 utime(full_name, &t);
192                         }
193                         chmod(full_name, file_entry->mode);
194                         chown(full_name, file_entry->uid, file_entry->gid);
195                 }
196         } else {
197                 /* If we arent extracting data we have to skip it, 
198                  * if data size is 0 then then just do it anyway
199                  * (saves testing for it) */
200                 seek_sub_file(src_stream, file_entry->size);
201         }
202
203         /* extract_list and extract_verbose_list can be used in conjunction
204          * with one of the above four extraction functions, so do this seperately */
205         if (function & extract_verbose_list) {
206                 fprintf(out_stream, "%s %d/%d %8d %s ", mode_string(file_entry->mode), 
207                         file_entry->uid, file_entry->gid,
208                         (int) file_entry->size, time_string(file_entry->mtime));
209         }
210         if ((function & extract_list) || (function & extract_verbose_list)){
211                 /* fputs doesnt add a trailing \n, so use fprintf */
212                 fprintf(out_stream, "%s\n", file_entry->name);
213         }
214
215         free(full_name);
216
217         return(NULL); /* Maybe we should say if failed */
218 }
219 #endif
220
221 #ifdef L_unarchive
222 char *unarchive(FILE *src_stream, void *(*get_headers)(FILE *),
223         const int extract_function, const char *prefix, char **extract_names)
224 {
225         file_header_t *file_entry;
226         int found;
227         int i;
228         char *buffer = NULL;
229
230         archive_offset = 0;
231         while ((file_entry = (file_header_t *) get_headers(src_stream)) != NULL) {
232                 found = FALSE;
233                 if (extract_names[0] != NULL) {
234                         for(i = 0; extract_names[i] != 0; i++) {
235                                 if (strcmp(extract_names[i], file_entry->name) == 0) {
236                                         found = TRUE;
237                                 }
238                         }
239                         if (!found) {
240                                 /* seek past the data entry */
241                                 if (!S_ISLNK(file_entry->mode) && file_entry->link_name && file_entry->size == 0) {
242                                         error_msg("You should extract %s as other files are hardlinked to it", file_entry->name);
243                                 }
244                                 seek_sub_file(src_stream, file_entry->size);
245                                 continue;
246                         }
247                 }
248                 buffer = extract_archive(src_stream, stdout, file_entry, extract_function, prefix);
249         }
250         return(buffer);
251 }
252 #endif
253
254 #ifdef L_get_header_ar
255 void *get_header_ar(FILE *src_stream)
256 {
257         file_header_t *typed;
258         union {
259                 char raw[60];
260                 struct {
261                         char name[16];
262                         char date[12];
263                         char uid[6];
264                         char gid[6];
265                         char mode[8];
266                         char size[10];
267                         char magic[2];
268                 } formated;
269         } ar;
270         static char *ar_long_names;
271
272         if (fread(ar.raw, 1, 60, src_stream) != 60) {
273                 return(NULL);
274         }
275         archive_offset += 60;
276         /* align the headers based on the header magic */
277         if ((ar.formated.magic[0] != '`') || (ar.formated.magic[1] != '\n')) {
278                 /* some version of ar, have an extra '\n' after each data entry,
279                  * this puts the next header out by 1 */
280                 if (ar.formated.magic[1] != '`') {
281                         error_msg("Invalid magic");
282                         return(NULL);
283                 }
284                 /* read the next char out of what would be the data section,
285                  * if its a '\n' then it is a valid header offset by 1*/
286                 archive_offset++;
287                 if (fgetc(src_stream) != '\n') {
288                         error_msg("Invalid magic");
289                         return(NULL);
290                 }
291                 /* fix up the header, we started reading 1 byte too early */
292                 /* raw_header[60] wont be '\n' as it should, but it doesnt matter */
293                 memmove(ar.raw, &ar.raw[1], 59);
294         }
295                 
296         typed = (file_header_t *) xcalloc(1, sizeof(file_header_t));
297
298         typed->size = (size_t) atoi(ar.formated.size);
299         /* long filenames have '/' as the first character */
300         if (ar.formated.name[0] == '/') {
301                 if (ar.formated.name[1] == '/') {
302                         /* If the second char is a '/' then this entries data section
303                          * stores long filename for multiple entries, they are stored
304                          * in static variable long_names for use in future entries */
305                         ar_long_names = (char *) xrealloc(ar_long_names, typed->size);
306                         fread(ar_long_names, 1, typed->size, src_stream);
307                         archive_offset += typed->size;
308                         /* This ar entries data section only contained filenames for other records
309                          * they are stored in the static ar_long_names for future reference */
310                         return(NULL);
311                 } else {
312                         /* The number after the '/' indicates the offset in the ar data section
313                         (saved in variable long_name) that conatains the real filename */
314                         if (!ar_long_names) {
315                                 error_msg("Cannot resolve long file name");
316                                 return (NULL);
317                         }
318                         typed->name = xstrdup(ar_long_names + atoi(&ar.formated.name[1]));
319                 }
320         } else {
321                 /* short filenames */
322                 typed->name = xcalloc(1, 16);
323                 strncpy(typed->name, ar.formated.name, 16);
324         }
325         typed->name[strcspn(typed->name, " /")]='\0';
326
327         /* convert the rest of the now valid char header to its typed struct */ 
328         parse_mode(ar.formated.mode, &typed->mode);
329         typed->mtime = atoi(ar.formated.date);
330         typed->uid = atoi(ar.formated.uid);
331         typed->gid = atoi(ar.formated.gid);
332
333         return(typed);
334 }
335 #endif
336
337 #ifdef L_get_header_cpio
338 void *get_header_cpio(FILE *src_stream)
339 {
340         file_header_t *cpio_entry = NULL;
341         char cpio_header[110];
342         char dummy[14];
343         int namesize;
344         int major, minor, nlink;
345
346         /* There can be padding before archive header */
347         seek_sub_file(src_stream, (4 - (archive_offset % 4)) % 4);
348         if (fread(cpio_header, 1, 110, src_stream) == 110) {
349                 archive_offset += 110;
350                 if (strncmp(cpio_header, "07070", 5) != 0) {
351                         error_msg("Unsupported format or invalid magic");
352                         return(NULL);
353                 }
354                 switch (cpio_header[5]) {
355                         case '2': /* "crc" header format */
356                                 /* Doesnt do the crc check yet */
357                         case '1': /* "newc" header format */
358                                 cpio_entry = (file_header_t *) xcalloc(1, sizeof(file_header_t));
359                                 sscanf(cpio_header, "%14c%8x%8x%8x%8x%8lx%8lx%16c%8x%8x%8x%8c",
360                                         dummy, &cpio_entry->mode, &cpio_entry->uid, &cpio_entry->gid,
361                                         &nlink, &cpio_entry->mtime, &cpio_entry->size,
362                                         dummy, &major, &minor, &namesize, dummy);
363
364                                 cpio_entry->name = (char *) xcalloc(1, namesize);
365                                 fread(cpio_entry->name, 1, namesize, src_stream); /* Read in filename */
366                                 archive_offset += namesize;
367                                 /* Skip padding before file contents */
368                                 seek_sub_file(src_stream, (4 - (archive_offset % 4)) % 4);
369                                 if (strcmp(cpio_entry->name, "TRAILER!!!") == 0) {
370                                         printf("%d blocks\n", (int) (archive_offset % 512 ? (archive_offset / 512) + 1 : archive_offset / 512)); /* Always round up */
371                                         return(NULL);
372                                 }
373
374                                 if (S_ISLNK(cpio_entry->mode)) {
375                                         cpio_entry->link_name = (char *) xcalloc(1, cpio_entry->size + 1);
376                                         fread(cpio_entry->link_name, 1, cpio_entry->size, src_stream);
377                                         archive_offset += cpio_entry->size;
378                                 }
379                                 if (nlink > 1 && !S_ISDIR(cpio_entry->mode) && cpio_entry->size == 0) {
380                                         error_msg("%s not extracted: Cannot handle hard links yet", cpio_entry->name);
381                                         return(get_header_cpio(src_stream)); /* Recurse to next file */
382                                 }
383                                 cpio_entry->device = (major << 8) | minor;
384                                 break;
385                         default:
386                                 error_msg("Unsupported format");
387                                 return(NULL);
388                 }
389                 if (ferror(src_stream) || feof(src_stream)) {
390                         perror_msg("Stream error");
391                         return(NULL);
392                 }
393         }
394         return(cpio_entry);
395 }
396 #endif
397
398 #ifdef L_get_header_tar
399 void *get_header_tar(FILE *tar_stream)
400 {
401         union {
402                 unsigned char raw[512];
403                 struct {
404                         char name[100];         /*   0-99 */
405                         char mode[8];           /* 100-107 */
406                         char uid[8];            /* 108-115 */
407                         char gid[8];            /* 116-123 */
408                         char size[12];          /* 124-135 */
409                         char mtime[12];         /* 136-147 */
410                         char chksum[8];         /* 148-155 */
411                         char typeflag;          /* 156-156 */
412                         char linkname[100];     /* 157-256 */
413                         char magic[6];          /* 257-262 */
414                         char version[2];        /* 263-264 */
415                         char uname[32];         /* 265-296 */
416                         char gname[32];         /* 297-328 */
417                         char devmajor[8];       /* 329-336 */
418                         char devminor[8];       /* 337-344 */
419                         char prefix[155];       /* 345-499 */
420                         char padding[12];       /* 500-512 */
421                 } formated;
422         } tar;
423         file_header_t *tar_entry = NULL;
424         long i;
425         long sum = 0;
426
427         if (archive_offset % 512 != 0) {
428                 seek_sub_file(tar_stream, 512 - (archive_offset % 512));
429         }
430
431         if (fread(tar.raw, 1, 512, tar_stream) != 512) {
432                 error_msg("Couldnt read header");
433                 return(NULL);
434         }
435         archive_offset += 512;
436
437         /* Check header has valid magic, unfortunately some tar files
438          * have empty (0'ed) tar entries at the end, which will
439          * cause this to fail, so fail silently for now
440          */
441         if (strncmp(tar.formated.magic, "ustar", 5) != 0) {
442                 return(NULL);
443         }
444
445         /* Do checksum on headers */
446         for (i =  0; i < 148 ; i++) {
447                 sum += tar.raw[i];
448         }
449         sum += ' ' * 8;
450         for (i =  156; i < 512 ; i++) {
451                 sum += tar.raw[i];
452         }
453         if (sum != strtol(tar.formated.chksum, NULL, 8)) {
454                 error_msg("Invalid tar header checksum");
455                 return(NULL);
456         }
457
458         /* convert to type'ed variables */
459         tar_entry = xcalloc(1, sizeof(file_header_t));
460         tar_entry->name = xstrdup(tar.formated.name);
461
462         parse_mode(tar.formated.mode, &tar_entry->mode);
463         tar_entry->uid   = strtol(tar.formated.uid, NULL, 8);
464         tar_entry->gid   = strtol(tar.formated.gid, NULL, 8);
465         tar_entry->size  = strtol(tar.formated.size, NULL, 8);
466         tar_entry->mtime = strtol(tar.formated.mtime, NULL, 8);
467         tar_entry->link_name  = strlen(tar.formated.linkname) ? xstrdup(tar.formated.linkname) : NULL;
468         tar_entry->device = (strtol(tar.formated.devmajor, NULL, 8) << 8) +
469                 strtol(tar.formated.devminor, NULL, 8);
470
471         return(tar_entry);
472 }
473 #endif
474
475 #ifdef L_deb_extract
476 char *deb_extract(const char *package_filename, FILE *out_stream, const int extract_function,
477         const char *prefix, const char *filename)
478 {
479         FILE *deb_stream;
480         FILE *uncompressed_stream = NULL;
481         file_header_t *ar_header = NULL;
482         char *output_buffer = NULL;
483         char *ared_file = NULL;
484         char ar_magic[8];
485         char **file_list;
486         int gunzip_pid;
487
488         file_list = malloc(sizeof(char *));
489         file_list[0] = xstrdup(filename);
490         file_list[1] = NULL;
491
492         if (extract_function & extract_control_tar_gz) {
493                 ared_file = xstrdup("control.tar.gz");
494         }
495         else if (extract_function & extract_data_tar_gz) {              
496                 ared_file = xstrdup("data.tar.gz");
497         }
498
499         /* open the debian package to be worked on */
500         deb_stream = wfopen(package_filename, "r");
501
502         /* check ar magic */
503         fread(ar_magic, 1, 8, deb_stream);
504         if (strncmp(ar_magic,"!<arch>",7) != 0) {
505                 error_msg_and_die("invalid magic");
506         }
507         archive_offset = 8;
508
509         while ((ar_header = get_header_ar(deb_stream)) != NULL) {
510                 if (strcmp(ared_file, ar_header->name) == 0) {
511                         /* open a stream of decompressed data */
512                         uncompressed_stream = gz_open(deb_stream, &gunzip_pid);
513                         archive_offset = 0;
514                         output_buffer = unarchive(uncompressed_stream, get_header_tar, extract_function, prefix, file_list);
515                 }
516                 seek_sub_file(deb_stream, ar_header->size);
517         }
518         gz_close(gunzip_pid);
519         fclose(deb_stream);
520         fclose(uncompressed_stream);
521         free(ared_file);
522         return(output_buffer);
523 }
524 #endif