1 /*-
2  * Copyright (c) 2003-2010 Tim Kientzle
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
15  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
18  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25 
26 #include "archive_platform.h"
27 __FBSDID("$FreeBSD: head/lib/libarchive/archive_read_open_filename.c 201093 2009-12-28 02:28:44Z kientzle $");
28 
29 #ifdef HAVE_SYS_IOCTL_H
30 #include <sys/ioctl.h>
31 #endif
32 #ifdef HAVE_SYS_STAT_H
33 #include <sys/stat.h>
34 #endif
35 #ifdef HAVE_ERRNO_H
36 #include <errno.h>
37 #endif
38 #ifdef HAVE_FCNTL_H
39 #include <fcntl.h>
40 #endif
41 #ifdef HAVE_IO_H
42 #include <io.h>
43 #endif
44 #ifdef HAVE_STDLIB_H
45 #include <stdlib.h>
46 #endif
47 #ifdef HAVE_STRING_H
48 #include <string.h>
49 #endif
50 #ifdef HAVE_UNISTD_H
51 #include <unistd.h>
52 #endif
53 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
54 #include <sys/disk.h>
55 #elif defined(__NetBSD__) || defined(__OpenBSD__)
56 #include <sys/disklabel.h>
57 #include <sys/dkio.h>
58 #elif defined(__DragonFly__)
59 #include <sys/diskslice.h>
60 #endif
61 
62 #include "archive.h"
63 #include "archive_string.h"
64 
65 #ifndef O_BINARY
66 #define O_BINARY 0
67 #endif
68 
69 struct read_file_data {
70 	int	 fd;
71 	size_t	 block_size;
72 	void	*buffer;
73 	mode_t	 st_mode;  /* Mode bits for opened file. */
74 	char	 use_lseek;
75 	enum fnt_e { FNT_STDIN, FNT_MBS, FNT_WCS } filename_type;
76 	union {
77 		char	 m[1];/* MBS filename. */
78 		wchar_t	 w[1];/* WCS filename. */
79 	} filename; /* Must be last! */
80 };
81 
82 static int	file_close(struct archive *, void *);
83 static int	file_open_filename(struct archive *, enum fnt_e, const void *,
84 		    size_t);
85 static ssize_t	file_read(struct archive *, void *, const void **buff);
86 static int64_t	file_seek(struct archive *, void *, int64_t request, int);
87 static int64_t	file_skip(struct archive *, void *, int64_t request);
88 static int64_t	file_skip_lseek(struct archive *, void *, int64_t request);
89 
90 int
91 archive_read_open_file(struct archive *a, const char *filename,
92     size_t block_size)
93 {
94 	return (archive_read_open_filename(a, filename, block_size));
95 }
96 
97 int
98 archive_read_open_filename(struct archive *a, const char *filename,
99     size_t block_size)
100 {
101 	enum fnt_e filename_type;
102 
103 	if (filename == NULL || filename[0] == '\0') {
104 		filename_type = FNT_STDIN;
105 	} else
106 		filename_type = FNT_MBS;
107 	return (file_open_filename(a, filename_type, filename, block_size));
108 }
109 
110 int
111 archive_read_open_filename_w(struct archive *a, const wchar_t *wfilename,
112     size_t block_size)
113 {
114 	enum fnt_e filename_type;
115 
116 	if (wfilename == NULL || wfilename[0] == L'\0') {
117 		filename_type = FNT_STDIN;
118 	} else {
119 #if defined(_WIN32) && !defined(__CYGWIN__)
120 		filename_type = FNT_WCS;
121 #else
122 		/*
123 		 * POSIX system does not support a wchar_t interface for
124 		 * open() system call, so we have to translate a whcar_t
125 		 * filename to multi-byte one and use it.
126 		 */
127 		struct archive_string fn;
128 		int r;
129 
130 		archive_string_init(&fn);
131 		if (archive_string_append_from_wcs(&fn, wfilename,
132 		    wcslen(wfilename)) != 0) {
133 			archive_set_error(a, EINVAL,
134 			    "Failed to convert a wide-character filename to"
135 			    " a multi-byte filename");
136 			archive_string_free(&fn);
137 			return (ARCHIVE_FATAL);
138 		}
139 		r = file_open_filename(a, FNT_MBS, fn.s, block_size);
140 		archive_string_free(&fn);
141 		return (r);
142 #endif
143 	}
144 	return (file_open_filename(a, filename_type, wfilename, block_size));
145 }
146 
147 static int
148 file_open_filename(struct archive *a, enum fnt_e filename_type,
149     const void *_filename, size_t block_size)
150 {
151 	struct stat st;
152 	struct read_file_data *mine;
153 	void *buffer;
154 	const char *filename = NULL;
155 	const wchar_t *wfilename = NULL;
156 	int fd;
157 	int is_disk_like = 0;
158 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
159 	off_t mediasize = 0; /* FreeBSD-specific, so off_t okay here. */
160 #elif defined(__NetBSD__) || defined(__OpenBSD__)
161 	struct disklabel dl;
162 #elif defined(__DragonFly__)
163 	struct partinfo pi;
164 #endif
165 
166 	archive_clear_error(a);
167 	if (filename_type == FNT_STDIN) {
168 		/* We used to delegate stdin support by
169 		 * directly calling archive_read_open_fd(a,0,block_size)
170 		 * here, but that doesn't (and shouldn't) handle the
171 		 * end-of-file flush when reading stdout from a pipe.
172 		 * Basically, read_open_fd() is intended for folks who
173 		 * are willing to handle such details themselves.  This
174 		 * API is intended to be a little smarter for folks who
175 		 * want easy handling of the common case.
176 		 */
177 		fd = 0;
178 #if defined(__CYGWIN__) || defined(_WIN32)
179 		setmode(0, O_BINARY);
180 #endif
181 		filename = "";
182 	} else if (filename_type == FNT_MBS) {
183 		filename = (const char *)_filename;
184 		fd = open(filename, O_RDONLY | O_BINARY);
185 		if (fd < 0) {
186 			archive_set_error(a, errno,
187 			    "Failed to open '%s'", filename);
188 			return (ARCHIVE_FATAL);
189 		}
190 	} else {
191 #if defined(_WIN32) && !defined(__CYGWIN__)
192 		wfilename = (const wchar_t *)_filename;
193 		fd = _wopen(wfilename, O_RDONLY | O_BINARY);
194 		if (fd < 0 && errno == ENOENT) {
195 			wchar_t *fullpath;
196 			fullpath = __la_win_permissive_name_w(wfilename);
197 			if (fullpath != NULL) {
198 				fd = _wopen(fullpath, O_RDONLY | O_BINARY);
199 				free(fullpath);
200 			}
201 		}
202 		if (fd < 0) {
203 			archive_set_error(a, errno,
204 			    "Failed to open '%S'", wfilename);
205 			return (ARCHIVE_FATAL);
206 		}
207 #else
208 		archive_set_error(a, ARCHIVE_ERRNO_MISC,
209 		    "Unexpedted operation in archive_read_open_filename");
210 		return (ARCHIVE_FATAL);
211 #endif
212 	}
213 	if (fstat(fd, &st) != 0) {
214 		if (filename_type == FNT_WCS)
215 			archive_set_error(a, errno, "Can't stat '%S'",
216 			    wfilename);
217 		else
218 			archive_set_error(a, errno, "Can't stat '%s'",
219 			    filename);
220 		return (ARCHIVE_FATAL);
221 	}
222 
223 	/*
224 	 * Determine whether the input looks like a disk device or a
225 	 * tape device.  The results are used below to select an I/O
226 	 * strategy:
227 	 *  = "disk-like" devices support arbitrary lseek() and will
228 	 *    support I/O requests of any size.  So we get easy skipping
229 	 *    and can cheat on block sizes to get better performance.
230 	 *  = "tape-like" devices require strict blocking and use
231 	 *    specialized ioctls for seeking.
232 	 *  = "socket-like" devices cannot seek at all but can improve
233 	 *    performance by using nonblocking I/O to read "whatever is
234 	 *    available right now".
235 	 *
236 	 * Right now, we only specially recognize disk-like devices,
237 	 * but it should be straightforward to add probes and strategy
238 	 * here for tape-like and socket-like devices.
239 	 */
240 	if (S_ISREG(st.st_mode)) {
241 		/* Safety:  Tell the extractor not to overwrite the input. */
242 		archive_read_extract_set_skip_file(a, st.st_dev, st.st_ino);
243 		/* Regular files act like disks. */
244 		is_disk_like = 1;
245 	}
246 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
247 	/* FreeBSD: if it supports DIOCGMEDIASIZE ioctl, it's disk-like. */
248 	else if (S_ISCHR(st.st_mode) &&
249 	    ioctl(fd, DIOCGMEDIASIZE, &mediasize) == 0 &&
250 	    mediasize > 0) {
251 		is_disk_like = 1;
252 	}
253 #elif defined(__NetBSD__) || defined(__OpenBSD__)
254 	/* Net/OpenBSD: if it supports DIOCGDINFO ioctl, it's disk-like. */
255 	else if ((S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) &&
256 	    ioctl(fd, DIOCGDINFO, &dl) == 0 &&
257 	    dl.d_partitions[DISKPART(st.st_rdev)].p_size > 0) {
258 		is_disk_like = 1;
259 	}
260 #elif defined(__DragonFly__)
261 	/* DragonFly BSD:  if it supports DIOCGPART ioctl, it's disk-like. */
262 	else if (S_ISCHR(st.st_mode) &&
263 	    ioctl(fd, DIOCGPART, &pi) == 0 &&
264 	    pi.media_size > 0) {
265 		is_disk_like = 1;
266 	}
267 #elif defined(__linux__)
268 	/* Linux:  All block devices are disk-like. */
269 	else if (S_ISBLK(st.st_mode) &&
270 	    lseek(fd, 0, SEEK_CUR) == 0 &&
271 	    lseek(fd, 0, SEEK_SET) == 0 &&
272 	    lseek(fd, 0, SEEK_END) > 0 &&
273 	    lseek(fd, 0, SEEK_SET) == 0) {
274 		is_disk_like = 1;
275 	}
276 #endif
277 	/* TODO: Add an "is_tape_like" variable and appropriate tests. */
278 
279 	if (filename_type == FNT_WCS)
280 		mine = (struct read_file_data *)calloc(1,
281 		    sizeof(*mine) + wcslen(wfilename) * sizeof(wchar_t));
282 	else
283 		mine = (struct read_file_data *)calloc(1,
284 		    sizeof(*mine) + strlen(filename));
285 	/* Disk-like devices prefer power-of-two block sizes.  */
286 	/* Use provided block_size as a guide so users have some control. */
287 	if (is_disk_like) {
288 		size_t new_block_size = 64 * 1024;
289 		while (new_block_size < block_size
290 		    && new_block_size < 64 * 1024 * 1024)
291 			new_block_size *= 2;
292 		block_size = new_block_size;
293 	}
294 	buffer = malloc(block_size);
295 	if (mine == NULL || buffer == NULL) {
296 		archive_set_error(a, ENOMEM, "No memory");
297 		free(mine);
298 		free(buffer);
299 		return (ARCHIVE_FATAL);
300 	}
301 	if (filename_type == FNT_WCS)
302 		wcscpy(mine->filename.w, wfilename);
303 	else
304 		strcpy(mine->filename.m, filename);
305 	mine->filename_type = filename_type;
306 	mine->block_size = block_size;
307 	mine->buffer = buffer;
308 	mine->fd = fd;
309 	/* Remember mode so close can decide whether to flush. */
310 	mine->st_mode = st.st_mode;
311 
312 	/* Disk-like inputs can use lseek(). */
313 	if (is_disk_like) {
314 		archive_read_set_seek_callback(a, file_seek);
315 		mine->use_lseek = 1;
316 	}
317 
318 	archive_read_set_read_callback(a, file_read);
319 	archive_read_set_skip_callback(a, file_skip);
320 	archive_read_set_close_callback(a, file_close);
321 	archive_read_set_callback_data(a, mine);
322 	return (archive_read_open1(a));
323 }
324 
325 static ssize_t
326 file_read(struct archive *a, void *client_data, const void **buff)
327 {
328 	struct read_file_data *mine = (struct read_file_data *)client_data;
329 	ssize_t bytes_read;
330 
331 	/* TODO: If a recent lseek() operation has left us
332 	 * mis-aligned, read and return a short block to try to get
333 	 * us back in alignment. */
334 
335 	/* TODO: Someday, try mmap() here; if that succeeds, give
336 	 * the entire file to libarchive as a single block.  That
337 	 * could be a lot faster than block-by-block manual I/O. */
338 
339 	/* TODO: We might be able to improve performance on pipes and
340 	 * sockets by setting non-blocking I/O and just accepting
341 	 * whatever we get here instead of waiting for a full block
342 	 * worth of data. */
343 
344 	*buff = mine->buffer;
345 	for (;;) {
346 		bytes_read = read(mine->fd, mine->buffer, mine->block_size);
347 		if (bytes_read < 0) {
348 			if (errno == EINTR)
349 				continue;
350 			else if (mine->filename_type == FNT_STDIN)
351 				archive_set_error(a, errno,
352 				    "Error reading stdin");
353 			else if (mine->filename_type == FNT_MBS)
354 				archive_set_error(a, errno,
355 				    "Error reading '%s'", mine->filename.m);
356 			else
357 				archive_set_error(a, errno,
358 				    "Error reading '%S'", mine->filename.w);
359 		}
360 		return (bytes_read);
361 	}
362 }
363 
364 /*
365  * Regular files and disk-like block devices can use simple lseek
366  * without needing to round the request to the block size.
367  *
368  * TODO: This can leave future reads mis-aligned.  Since we know the
369  * offset here, we should store it and use it in file_read() above
370  * to determine whether we should perform a short read to get back
371  * into alignment.  Long series of mis-aligned reads can negatively
372  * impact disk throughput.  (Of course, the performance impact should
373  * be carefully tested; extra code complexity is only worthwhile if
374  * it does provide measurable improvement.)
375  *
376  * TODO: Be lazy about the actual seek.  There are a few pathological
377  * cases where libarchive makes a bunch of seek requests in a row
378  * without any intervening reads.  This isn't a huge performance
379  * problem, since the kernel handles seeks lazily already, but
380  * it would be very slightly faster if we simply remembered the
381  * seek request here and then actually performed the seek at the
382  * top of the read callback above.
383  */
384 static int64_t
385 file_skip_lseek(struct archive *a, void *client_data, int64_t request)
386 {
387 	struct read_file_data *mine = (struct read_file_data *)client_data;
388 #if defined(_WIN32) && !defined(__CYGWIN__)
389 	/* We use _lseeki64() on Windows. */
390 	int64_t old_offset, new_offset;
391 #else
392 	off_t old_offset, new_offset;
393 #endif
394 
395 	/* We use off_t here because lseek() is declared that way. */
396 
397 	/* TODO: Deal with case where off_t isn't 64 bits.
398 	 * This shouldn't be a problem on Linux or other POSIX
399 	 * systems, since the configuration logic for libarchive
400 	 * tries to obtain a 64-bit off_t.  It's still an issue
401 	 * on Windows, though, so it might suffice to just use
402 	 * _lseeki64() on Windows.
403 	 */
404 	if ((old_offset = lseek(mine->fd, 0, SEEK_CUR)) >= 0 &&
405 	    (new_offset = lseek(mine->fd, request, SEEK_CUR)) >= 0)
406 		return (new_offset - old_offset);
407 
408 	/* If lseek() fails, don't bother trying again. */
409 	mine->use_lseek = 0;
410 
411 	/* Let libarchive recover with read+discard */
412 	if (errno == ESPIPE)
413 		return (0);
414 
415 	/* If the input is corrupted or truncated, fail. */
416 	if (mine->filename_type == FNT_STDIN)
417 		archive_set_error(a, errno, "Error seeking in stdin");
418 	else if (mine->filename_type == FNT_MBS)
419 		archive_set_error(a, errno, "Error seeking in '%s'",
420 		    mine->filename.m);
421 	else
422 		archive_set_error(a, errno, "Error seeking in '%S'",
423 		    mine->filename.w);
424 	return (-1);
425 }
426 
427 
428 /*
429  * TODO: Implement another file_skip_XXXX that uses MTIO ioctls to
430  * accelerate operation on tape drives.
431  */
432 
433 static int64_t
434 file_skip(struct archive *a, void *client_data, int64_t request)
435 {
436 	struct read_file_data *mine = (struct read_file_data *)client_data;
437 
438 	/* Delegate skip requests. */
439 	if (mine->use_lseek)
440 		return (file_skip_lseek(a, client_data, request));
441 
442 	/* If we can't skip, return 0; libarchive will read+discard instead. */
443 	return (0);
444 }
445 
446 /*
447  * TODO: Store the offset and use it in the read callback.
448  */
449 static int64_t
450 file_seek(struct archive *a, void *client_data, int64_t request, int whence)
451 {
452 	struct read_file_data *mine = (struct read_file_data *)client_data;
453 	off_t r;
454 
455 	/* We use off_t here because lseek() is declared that way. */
456 	/* See above for notes about when off_t is less than 64 bits. */
457 	r = lseek(mine->fd, request, whence);
458 	if (r >= 0)
459 		return r;
460 
461 	/* If the input is corrupted or truncated, fail. */
462 	if (mine->filename_type == FNT_STDIN)
463 		archive_set_error(a, errno, "Error seeking in stdin");
464 	else if (mine->filename_type == FNT_MBS)
465 		archive_set_error(a, errno, "Error seeking in '%s'",
466 		    mine->filename.m);
467 	else
468 		archive_set_error(a, errno, "Error seeking in '%S'",
469 		    mine->filename.w);
470 	return (ARCHIVE_FATAL);
471 }
472 
473 static int
474 file_close(struct archive *a, void *client_data)
475 {
476 	struct read_file_data *mine = (struct read_file_data *)client_data;
477 
478 	(void)a; /* UNUSED */
479 
480 	/* Only flush and close if open succeeded. */
481 	if (mine->fd >= 0) {
482 		/*
483 		 * Sometimes, we should flush the input before closing.
484 		 *   Regular files: faster to just close without flush.
485 		 *   Disk-like devices:  Ditto.
486 		 *   Tapes: must not flush (user might need to
487 		 *      read the "next" item on a non-rewind device).
488 		 *   Pipes and sockets:  must flush (otherwise, the
489 		 *      program feeding the pipe or socket may complain).
490 		 * Here, I flush everything except for regular files and
491 		 * device nodes.
492 		 */
493 		if (!S_ISREG(mine->st_mode)
494 		    && !S_ISCHR(mine->st_mode)
495 		    && !S_ISBLK(mine->st_mode)) {
496 			ssize_t bytesRead;
497 			do {
498 				bytesRead = read(mine->fd, mine->buffer,
499 				    mine->block_size);
500 			} while (bytesRead > 0);
501 		}
502 		/* If a named file was opened, then it needs to be closed. */
503 		if (mine->filename_type != FNT_STDIN)
504 			close(mine->fd);
505 	}
506 	free(mine->buffer);
507 	free(mine);
508 	return (ARCHIVE_OK);
509 }
510