Decode and apply MSDOS file timestamps
[installshield_z.git] / installshield_main.c
1 /*
2   InstallShield Z file format
3   Copyright 2015 <hacker@iam.tj>
4   Licenced on the terms of then GNU General Public Licence version 3
5
6   Read and extract InstallShield .Z archive files
7  */
8
9 #include <stdio.h>
10 #include <sys/types.h>
11 #include <sys/stat.h>
12 #include <inttypes.h>
13 #include <fcntl.h>
14 #include <stdlib.h>
15 #include <unistd.h>
16 #include <errno.h>
17 #include <string.h>
18 #include <time.h>
19 #include <utime.h>
20
21 #include "implode.h"
22 #include "installshield_z.h"
23
24 static const size_t BUFFER_SIZE = 0x4000;
25 static bool debug = 0;
26 static bool extract = 0;
27
28 void
29 usage(const char *name)
30 {
31         printf("usage: %s %s\n\n", name,
32                 " FILENAME\n"
33                 " [-x|--extract]"
34         );
35 }
36
37 time_t msdos2unixtime(uint16_t time, uint16_t date)
38 {
39         if (debug) printf("Date: %04x Time %04x\n", date, time);
40         struct tm dt;
41         dt.tm_year              =((date & 0xFE00) >>  9) + 80;
42         dt.tm_mon               = (date & 0x01E0) >>  5;
43         dt.tm_mday              = (date & 0x001F) >>  0;
44         dt.tm_hour              = (time & 0xF800) >> 11;
45         dt.tm_min               = (time & 0x07E0) >>  5;
46         dt.tm_sec               = (time & 0x001F) >>  0;
47
48         return mktime(&dt);
49 }
50
51 int
52 headers_decode(int z_fd)
53 {
54         int result = -1;
55         struct archive_header *header = NULL;
56         off_t offset = 0;
57         ssize_t qty = 0;
58
59         if (z_fd != -1 && (header = calloc(BUFFER_SIZE, 1))) {
60                 offset = lseek(z_fd, offset, SEEK_SET);
61                 if ((qty = read(z_fd, header, Z_FILE_HEADER_BYTES))< Z_FILE_HEADER_BYTES)
62                         fprintf(stderr, "Warning: Tried to read %ld header bytes but only got %ld. Will do my best\n", Z_FILE_HEADER_BYTES, qty);
63                 printf("Magic               %08x\n", header->magic);
64                 printf("CRC32               %08x\n", header->__crc32);
65                 printf("File size           %08x\n", header->file_bytes);
66                 printf("Payload size        %08x\n", header->payload_bytes);
67                 printf("Directories offset  %08x\n", header->directories_offset);
68                 printf("Directories size    %08x\n", header->directories_bytes);
69                 printf("Directories entries     %04x\n", header->directories_entries);
70                 printf("Files offset        %08x\n", header->files_offset);
71                 printf("Files size          %08x\n", header->files_bytes);
72                 printf("Files entries           %04x\n", header->files_entries);
73
74                 offset = lseek(z_fd, header->directories_offset, SEEK_SET);
75                 struct dirent_prefix *dirent, *p;
76
77                 if (offset == header->directories_offset && ((dirent = p = calloc(header->directories_bytes, 1)))) {
78
79                         if ((qty = read(z_fd, dirent, header->directories_bytes)) != header->directories_bytes)
80                                 fprintf(stderr, "Warning: Tried to read %d directory bytes but only got %ld. Will do my best\n", header->directories_bytes, qty);
81
82                         printf("Directory entries: %d ( %08x bytes @ 0x%08x)\n", header->directories_entries, header->directories_bytes, header->directories_offset);
83
84                         struct dirent dirents[header->directories_entries];
85                         for (int i = 0; i < header->directories_entries; ++i) {
86                                 printf(" Entry %4d Size %x @ %08x    \"%s\"\n", i, p->entry_bytes, header->directories_offset + (uint32_t)((void *)p - (void *)dirent), p->name);
87                                 dirents[i].entry = p;
88                                 p = (void *)p + p->entry_bytes;
89                         }
90
91                         offset = lseek(z_fd, header->files_offset, SEEK_SET);
92                         struct fileent_prefix *fileent, *q;
93                         if (offset == header->files_offset && ((fileent = q = calloc(header->files_bytes, 1)))) {
94                                 if ((qty = read(z_fd, fileent, header->files_bytes)) != header->files_bytes)
95                                         fprintf(stderr, "Warning: Tried to read %d file entry bytes but only got %ld. Will do my best\n", header->files_bytes, qty);
96
97                                 printf("File entries: %d ( %08x bytes @ 0x%08x)\n", header->files_entries, header->files_bytes, header->files_offset);
98
99                                 for (int i = 0; i < header->files_entries; ++i) {
100                                         time_t timestamp = msdos2unixtime(q->timestamp, q->datestamp);
101                                         char *datetime = ctime(&timestamp);
102                                         printf(" Entry %4d uses %06x bytes @ %08x. Date %s File-size %08x (payload %08x @ %08x)", i, q->entry_bytes, header->files_offset +(uint32_t)((void *)q - (void *)fileent), datetime, q->file_bytes, q->payload_bytes, q->payload_offset);
103
104                                         if (debug) {
105                                                 printf(" next @ %08x", q->payload_offset + q->payload_bytes);
106                                                 for (int r = 0; r < 0x1E; ++r)
107                                                 printf(" %02x", *(unsigned char *)(r + (void *)q));
108                                         }
109
110                                         printf(" \"%s\\%s\"\n", dirents[q->dir_index].entry->name, q->name);
111
112                                         char *dir_name = strdup(dirents[q->dir_index].entry->name);
113                                         for (char *p = dir_name; *p; ++p)
114                                                 if (*p == '\\') *p = '/';
115                                          if (debug) printf("Parsing '%s' (%ld bytes)\n", dir_name, strlen(dir_name));
116
117                                         int dir_fd = AT_FDCWD;
118                                         int dir_fd_last = dir_fd;
119                                         if (extract) {
120                                                 if (!dirents[q->dir_index].created) {
121                                                         char *component = dir_name;
122                                                         bool last_component = false;
123                                                         for (char *sep = dir_name;; ++sep) {
124                                                                 if (*sep == '/' || *sep == 0) {
125                                                                         if (*sep == 0)
126                                                                                 last_component = true;
127                                                                         char temp = *sep;
128                                                                         *sep = 0;
129                                                                         if (strlen(component) > 0) {
130                                                                                 if (debug) printf("Component: '%s' %ld bytes @ %p\n", component, strlen(component), component);
131                                                                                 int ret = mkdirat(dir_fd, component, 0755);
132                                                                                 if (ret == 0 || (ret == -1 && errno == EEXIST)) {
133                                                                                         if (debug)
134                                                                                                 printf("Directory '%s' %s\n", component, ret == 0 ? "created" : "already exists");
135                                                                                         dir_fd_last = dir_fd;
136                                                                                         dir_fd = openat(dir_fd_last, component, O_DIRECTORY);
137                                                                                         close(dir_fd_last);
138                                                                                         if (dir_fd == -1) {
139                                                                                                 fprintf(stderr, "Error %d: cannot open directory '%s': ", errno, component);
140                                                                                                 perror(NULL);
141                                                                                                 *sep = temp;
142                                                                                                 break; // cannot continue if unable to open a path component
143                                                                                         } else if (last_component == true) {
144                                                                                                 dirents[q->dir_index].created = true;
145                                                                                         }
146                                                                                 } else {
147                                                                                         fprintf(stderr, "Error %d: cannot create directory '%s': ", errno, component);
148                                                                                         perror(NULL);
149                                                                                         *sep = temp;
150                                                                                         break; // leave the for() loop immediately
151                                                                                 }
152                                                                         } // strlen()
153                                                                         *sep = temp;
154                                                                         component = sep + 1;
155                                                                         if (last_component) break;
156                                                                 } // separator
157                                                         } // for()
158                                                         if (dir_fd < 0)
159                                                                 dir_fd = AT_FDCWD;
160                                                 } // .created == false
161                                         }
162                                         if ((dir_fd = openat(AT_FDCWD, dir_name, O_DIRECTORY)) != -1) {
163
164                                                 unsigned int z_filename_len = strlen(q->name) + 4;
165                                                 char z_filename[z_filename_len];
166                                                 strncpy(z_filename, q->name, z_filename_len);
167                                                 strncat(z_filename, ".z", 3);
168
169                                                 char filepath[strlen(dir_name) + z_filename_len];
170                                                 strncpy(filepath, dir_name, strlen(dir_name) + 1);
171                                                 strncat(filepath, "/", 2);
172                                                 strncat(filepath, z_filename, z_filename_len);
173
174                                                 if (debug)
175                                                         printf(" Creating payload file '%s/%s'\n", dir_name,  z_filename);
176
177                                                 if ((offset = lseek(z_fd, q->payload_offset, SEEK_SET)) == q->payload_offset) {
178                                                         void *buffer;
179                                                         if ((buffer = calloc(q->payload_bytes, 1)) != 0) {
180                                                                 struct utimbuf filetime;
181                                                                 filetime.actime  = timestamp;
182                                                                 filetime.modtime = timestamp;
183                                                                 int pay_fd;
184                                                                 if ((pay_fd = openat(dir_fd, z_filename, O_WRONLY | O_CREAT | O_TRUNC, 0644))) {
185                                                                         ssize_t z_qty, pay_qty;
186                                                                         if ((z_qty = read(z_fd, buffer, q->payload_bytes)) == q->payload_bytes) {
187                                                                                 if (debug) {
188                                                                                         unsigned int checksum = 0x0;
189                                                                                         for (int i = 0; i < q->payload_bytes / sizeof(unsigned int); ++i) {
190                                                                                                 checksum ^= ((unsigned int *)buffer)[i];
191                                                                                         }
192                                                                                         printf("Checksum: %08x\n", checksum);
193                                                                                 }
194                                                                                 if ((pay_qty = write(pay_fd, buffer, q->payload_bytes)) != q->payload_bytes)
195                                                                                         fprintf(stderr, "Error: whilst writing payload expected %d bytes but wrote %ld\n", q->payload_bytes, pay_qty);
196                                                                         } else
197                                                                                 fprintf(stderr, "Error: whilst reading payload expected %d bytes but read %ld\n", q->payload_bytes, z_qty);
198                                                                         close(pay_fd);
199                                                                         if(utime(filepath, &filetime) == -1) {
200                                                                                 fprintf(stderr, "Error: unable to set timestamp on '%s' (%d) ", filepath, errno);
201                                                                                 perror(NULL);
202                                                                         }
203                                                                 }
204                                                                 if (q->payload_bytes >= 4) {
205                                                                         uint8_t comp_type = *(uint8_t *)buffer;
206                                                                         uint8_t dict_size = *(uint8_t *)(buffer + 1);
207                                                                         if (comp_type >= IMPLODE_BINARY && comp_type <= IMPLODE_ASCII && dict_size >= IMPLODE_DICT_1K && dict_size <= IMPLODE_DICT_4K) {
208                                                                                 void * buffer_decomp;
209                                                                                 if ((buffer_decomp = calloc(q->file_bytes, 1)) != 0) {
210                                                                                         uint32_t decomp_bytes = q->file_bytes;
211                                                                                         if (explode(buffer, q->payload_bytes, buffer_decomp, &decomp_bytes)) {
212                                                                                                 if (decomp_bytes > q->file_bytes) {
213                                                                                                         fprintf(stderr, "Expected %d uncompressed bytes but got %d\n", q->file_bytes, decomp_bytes);
214                                                                                                 }
215                                                                                                 int decomp_fd;
216                                                                                                 if ((decomp_fd = openat(dir_fd, q->name, O_WRONLY | O_CREAT | O_TRUNC, 0644))) {
217                                                                                                         ssize_t decomp_qty;
218                                                                                                         if (debug)
219                                                                                                                 printf("Creating uncompressed file '%s/%s'\n",dir_name,  q->name);
220                                                                                                         if ((decomp_qty = write(decomp_fd, buffer_decomp, q->file_bytes)) != q->file_bytes)
221                                                                                                                 fprintf(stderr, "Error: whilst writing decompressed data expected %d bytes but wrote %ld\n", q->file_bytes, decomp_qty);
222                                                                                                         close(decomp_fd);
223                                                                                                         filepath[strlen(filepath) - 2] = 0;
224                                                                                                         if(utime(filepath, &filetime) == -1) {
225                                                                                                                 fprintf(stderr, "Error: unable to set timestamp on '%s' (%d) ", filepath, errno);
226                                                                                                                 perror(NULL);
227                                                                                                         }
228                                                                                                 }
229                                                                                         } else {
230                                                                                                 fprintf(stderr, "Error: failed to decompress '%s', payload: %d decompressed: %d\n", q->name, q->payload_bytes, decomp_bytes);
231                                                                                         }
232                                                                                         free(buffer_decomp);
233                                                                                 } else {
234                                                                                         fprintf(stderr, "Error: unable to allocate %d bytes for decompression buffer\n", q->file_bytes);
235                                                                                 }
236                                                                         } else {
237                                                                                 fprintf(stderr, "Does not look like TTComp compressed data. header: %04x\n", *(uint16_t *)buffer);
238                                                                         }
239                                                                 } else {
240                                                                         fprintf(stderr, "Error: payload %d bytes smaller than minimum allowed TTComp of 4\n", q->payload_bytes);
241                                                                 }
242                                                                 free(buffer);
243                                                         }
244                                                 } else {
245                                                         fprintf(stderr, "Error %d: failed to create %s\n", errno, z_filename);
246                                                 }
247                                                 close(dir_fd);
248                                         } else {
249                                                 fprintf(stderr, "Error %d: cannot open directory at (%d) '%s': ", errno, dir_fd, dir_name);
250                                                 perror(NULL);
251                                         }
252                                         free(dir_name);
253                                         q = (void *)q + q->entry_bytes;
254                                 }
255                                 free(fileent);
256                         }
257                         free(dirent);
258                 } else 
259                         fprintf(stderr, "Error: %s\n", "failed to seek or couldn't allocate memory for directories");
260  
261                 free(header);
262                 result = 0;
263         }
264         return result;
265 }
266
267 int
268 main(int argc, char **argv, char **env)
269 {
270         int result = -1;
271         int fd = 0;
272
273         if (argc < 2 ) {
274                 usage(argv[0]);
275                 return 0;
276         }
277
278         for (char **e = env; *e; ++e) {
279                 if (strncmp("DEBUG", *e, 5) == 0)
280                         debug = true;
281         }
282         for (char **a = argv; *a; ++a) {
283                 if (debug) printf("Arg: %s\n", *a);
284                 if (strncmp("-x", *a, 2) == 0 || strncmp("--extract", *a, 9) == 0)
285                         extract = true;
286         }
287
288         if ((fd = open(argv[1], O_RDONLY)) != -1) {
289                 result = headers_decode(fd);
290                 close(fd);
291         } else {
292                 fprintf(stderr, "Error: could not open %s\n", argv[0]);
293                 return errno;
294         }
295
296
297         return result;
298 }
299