1 /*
2  *  be_package.c : backend for packages
3  *
4  *  Copyright (c) 2006-2018 Pacman Development Team <pacman-dev@archlinux.org>
5  *  Copyright (c) 2002-2006 by Judd Vinet <jvinet@zeroflux.org>
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 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, see <http://www.gnu.org/licenses/>.
19  */
20 
21 #include <stdlib.h>
22 #include <string.h>
23 #include <errno.h>
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <fcntl.h>
27 #include <limits.h>
28 
29 /* libarchive */
30 #include <archive.h>
31 #include <archive_entry.h>
32 
33 /* libalpm */
34 #include "alpm_list.h"
35 #include "alpm.h"
36 #include "libarchive-compat.h"
37 #include "util.h"
38 #include "log.h"
39 #include "handle.h"
40 #include "package.h"
41 #include "deps.h"
42 #include "filelist.h"
43 #include "util.h"
44 
45 struct package_changelog {
46 	struct archive *archive;
47 	int fd;
48 };
49 
50 /**
51  * Open a package changelog for reading. Similar to fopen in functionality,
52  * except that the returned 'file stream' is from an archive.
53  * @param pkg the package (file) to read the changelog
54  * @return a 'file stream' to the package changelog
55  */
_package_changelog_open(alpm_pkg_t * pkg)56 static void *_package_changelog_open(alpm_pkg_t *pkg)
57 {
58 	ASSERT(pkg != NULL, return NULL);
59 
60 	struct package_changelog *changelog;
61 	struct archive *archive;
62 	struct archive_entry *entry;
63 	const char *pkgfile = pkg->origin_data.file;
64 	struct stat buf;
65 	int fd;
66 
67 	fd = _alpm_open_archive(pkg->handle, pkgfile, &buf,
68 			&archive, ALPM_ERR_PKG_OPEN);
69 	if(fd < 0) {
70 		return NULL;
71 	}
72 
73 	while(archive_read_next_header(archive, &entry) == ARCHIVE_OK) {
74 		const char *entry_name = archive_entry_pathname(entry);
75 
76 		if(strcmp(entry_name, ".CHANGELOG") == 0) {
77 			changelog = malloc(sizeof(struct package_changelog));
78 			if(!changelog) {
79 				pkg->handle->pm_errno = ALPM_ERR_MEMORY;
80 				_alpm_archive_read_free(archive);
81 				close(fd);
82 				return NULL;
83 			}
84 			changelog->archive = archive;
85 			changelog->fd = fd;
86 			return changelog;
87 		}
88 	}
89 	/* we didn't find a changelog */
90 	_alpm_archive_read_free(archive);
91 	close(fd);
92 	errno = ENOENT;
93 
94 	return NULL;
95 }
96 
97 /**
98  * Read data from an open changelog 'file stream'. Similar to fread in
99  * functionality, this function takes a buffer and amount of data to read.
100  * @param ptr a buffer to fill with raw changelog data
101  * @param size the size of the buffer
102  * @param pkg the package that the changelog is being read from
103  * @param fp a 'file stream' to the package changelog
104  * @return the number of characters read, or 0 if there is no more data
105  */
_package_changelog_read(void * ptr,size_t size,const alpm_pkg_t UNUSED * pkg,void * fp)106 static size_t _package_changelog_read(void *ptr, size_t size,
107 		const alpm_pkg_t UNUSED *pkg, void *fp)
108 {
109 	struct package_changelog *changelog = fp;
110 	ssize_t sret = archive_read_data(changelog->archive, ptr, size);
111 	/* Report error (negative values) */
112 	if(sret < 0) {
113 		RET_ERR(pkg->handle, ALPM_ERR_LIBARCHIVE, 0);
114 	} else {
115 		return (size_t)sret;
116 	}
117 }
118 
119 /**
120  * Close a package changelog for reading. Similar to fclose in functionality,
121  * except that the 'file stream' is from an archive.
122  * @param pkg the package (file) that the changelog was read from
123  * @param fp a 'file stream' to the package changelog
124  * @return whether closing the package changelog stream was successful
125  */
_package_changelog_close(const alpm_pkg_t UNUSED * pkg,void * fp)126 static int _package_changelog_close(const alpm_pkg_t UNUSED *pkg, void *fp)
127 {
128 	int ret;
129 	struct package_changelog *changelog = fp;
130 	ret = _alpm_archive_read_free(changelog->archive);
131 	close(changelog->fd);
132 	free(changelog);
133 	return ret;
134 }
135 
136 /** Package file operations struct accessor. We implement this as a method
137  * rather than a static struct as in be_files because we want to reuse the
138  * majority of the default_pkg_ops struct and add only a few operations of
139  * our own on top.
140  */
get_file_pkg_ops(void)141 static struct pkg_operations *get_file_pkg_ops(void)
142 {
143 	static struct pkg_operations file_pkg_ops;
144 	static int file_pkg_ops_initialized = 0;
145 	if(!file_pkg_ops_initialized) {
146 		file_pkg_ops = default_pkg_ops;
147 		file_pkg_ops.changelog_open  = _package_changelog_open;
148 		file_pkg_ops.changelog_read  = _package_changelog_read;
149 		file_pkg_ops.changelog_close = _package_changelog_close;
150 		file_pkg_ops_initialized = 1;
151 	}
152 	return &file_pkg_ops;
153 }
154 
155 /**
156  * Parses the package description file for a package into a alpm_pkg_t struct.
157  * @param archive the archive to read from, pointed at the .PKGINFO entry
158  * @param newpkg an empty alpm_pkg_t struct to fill with package info
159  *
160  * @return 0 on success, -1 on error
161  */
parse_descfile(alpm_handle_t * handle,struct archive * a,alpm_pkg_t * newpkg)162 static int parse_descfile(alpm_handle_t *handle, struct archive *a, alpm_pkg_t *newpkg)
163 {
164 	char *ptr = NULL;
165 	char *key = NULL;
166 	int ret, linenum = 0;
167 	struct archive_read_buffer buf;
168 
169 	memset(&buf, 0, sizeof(buf));
170 	/* 512K for a line length seems reasonable */
171 	buf.max_line_size = 512 * 1024;
172 
173 	/* loop until we reach EOF or other error */
174 	while((ret = _alpm_archive_fgets(a, &buf)) == ARCHIVE_OK) {
175 		size_t len = _alpm_strip_newline(buf.line, buf.real_line_size);
176 
177 		linenum++;
178 		key = buf.line;
179 		if(len == 0 || key[0] == '#') {
180 			continue;
181 		}
182 		/* line is always in this format: "key = value"
183 		 * we can be sure the " = " exists, so look for that */
184 		ptr = memchr(key, ' ', len);
185 		if(!ptr || (size_t)(ptr - key + 2) > len || memcmp(ptr, " = ", 3) != 0) {
186 			_alpm_log(handle, ALPM_LOG_DEBUG,
187 					"%s: syntax error in description file line %d\n",
188 					newpkg->name ? newpkg->name : "error", linenum);
189 		} else {
190 			/* NULL the end of the key portion, move ptr to start of value */
191 			*ptr = '\0';
192 			ptr += 3;
193 			if(strcmp(key, "pkgname") == 0) {
194 				STRDUP(newpkg->name, ptr, return -1);
195 				newpkg->name_hash = _alpm_hash_sdbm(newpkg->name);
196 			} else if(strcmp(key, "pkgbase") == 0) {
197 				STRDUP(newpkg->base, ptr, return -1);
198 			} else if(strcmp(key, "pkgver") == 0) {
199 				STRDUP(newpkg->version, ptr, return -1);
200 			} else if(strcmp(key, "basever") == 0) {
201 				/* not used atm */
202 			} else if(strcmp(key, "pkgdesc") == 0) {
203 				STRDUP(newpkg->desc, ptr, return -1);
204 			} else if(strcmp(key, "group") == 0) {
205 				newpkg->groups = alpm_list_add(newpkg->groups, strdup(ptr));
206 			} else if(strcmp(key, "url") == 0) {
207 				STRDUP(newpkg->url, ptr, return -1);
208 			} else if(strcmp(key, "license") == 0) {
209 				newpkg->licenses = alpm_list_add(newpkg->licenses, strdup(ptr));
210 			} else if(strcmp(key, "builddate") == 0) {
211 				newpkg->builddate = _alpm_parsedate(ptr);
212 			} else if(strcmp(key, "packager") == 0) {
213 				STRDUP(newpkg->packager, ptr, return -1);
214 			} else if(strcmp(key, "arch") == 0) {
215 				STRDUP(newpkg->arch, ptr, return -1);
216 			} else if(strcmp(key, "size") == 0) {
217 				/* size in the raw package is uncompressed (installed) size */
218 				newpkg->isize = _alpm_strtoofft(ptr);
219 			} else if(strcmp(key, "depend") == 0) {
220 				alpm_depend_t *dep = alpm_dep_from_string(ptr);
221 				newpkg->depends = alpm_list_add(newpkg->depends, dep);
222 			} else if(strcmp(key, "optdepend") == 0) {
223 				alpm_depend_t *optdep = alpm_dep_from_string(ptr);
224 				newpkg->optdepends = alpm_list_add(newpkg->optdepends, optdep);
225 			} else if(strcmp(key, "makedepend") == 0) {
226 				alpm_depend_t *makedep = alpm_dep_from_string(ptr);
227 				newpkg->makedepends = alpm_list_add(newpkg->makedepends, makedep);
228 			} else if(strcmp(key, "checkdepend") == 0) {
229 				alpm_depend_t *checkdep = alpm_dep_from_string(ptr);
230 				newpkg->checkdepends = alpm_list_add(newpkg->checkdepends, checkdep);
231 			} else if(strcmp(key, "conflict") == 0) {
232 				alpm_depend_t *conflict = alpm_dep_from_string(ptr);
233 				newpkg->conflicts = alpm_list_add(newpkg->conflicts, conflict);
234 			} else if(strcmp(key, "replaces") == 0) {
235 				alpm_depend_t *replace = alpm_dep_from_string(ptr);
236 				newpkg->replaces = alpm_list_add(newpkg->replaces, replace);
237 			} else if(strcmp(key, "provides") == 0) {
238 				alpm_depend_t *provide = alpm_dep_from_string(ptr);
239 				newpkg->provides = alpm_list_add(newpkg->provides, provide);
240 			} else if(strcmp(key, "backup") == 0) {
241 				alpm_backup_t *backup;
242 				CALLOC(backup, 1, sizeof(alpm_backup_t), return -1);
243 				STRDUP(backup->name, ptr, FREE(backup); return -1);
244 				newpkg->backup = alpm_list_add(newpkg->backup, backup);
245 			} else if(strcmp(key, "force") == 0) {
246 				/* deprecated, skip it */
247 			} else if(strcmp(key, "makepkgopt") == 0) {
248 				/* not used atm */
249 			} else {
250 				_alpm_log(handle, ALPM_LOG_DEBUG, "%s: unknown key '%s' in description file line %d\n",
251 									newpkg->name ? newpkg->name : "error", key, linenum);
252 			}
253 		}
254 	}
255 	if(ret != ARCHIVE_EOF) {
256 		_alpm_log(handle, ALPM_LOG_DEBUG, "error parsing package descfile\n");
257 		return -1;
258 	}
259 
260 	return 0;
261 }
262 
263 /**
264  * Validate a package.
265  * @param handle the context handle
266  * @param pkgfile path to the package file
267  * @param syncpkg package object to load verification data from (md5sum,
268  * sha256sum, and/or base64 signature)
269  * @param level the required level of signature verification
270  * @param sigdata signature data from the package to pass back
271  * @param validation successful validations performed on the package file
272  * @return 0 if package is fully valid, -1 and pm_errno otherwise
273  */
_alpm_pkg_validate_internal(alpm_handle_t * handle,const char * pkgfile,alpm_pkg_t * syncpkg,int level,alpm_siglist_t ** sigdata,int * validation)274 int _alpm_pkg_validate_internal(alpm_handle_t *handle,
275 		const char *pkgfile, alpm_pkg_t *syncpkg, int level,
276 		alpm_siglist_t **sigdata, int *validation)
277 {
278 	int has_sig;
279 	handle->pm_errno = ALPM_ERR_OK;
280 
281 	if(pkgfile == NULL || strlen(pkgfile) == 0) {
282 		RET_ERR(handle, ALPM_ERR_WRONG_ARGS, -1);
283 	}
284 
285 	/* attempt to access the package file, ensure it exists */
286 	if(_alpm_access(handle, NULL, pkgfile, R_OK) != 0) {
287 		if(errno == ENOENT) {
288 			handle->pm_errno = ALPM_ERR_PKG_NOT_FOUND;
289 		} else if(errno == EACCES) {
290 			handle->pm_errno = ALPM_ERR_BADPERMS;
291 		} else {
292 			handle->pm_errno = ALPM_ERR_PKG_OPEN;
293 		}
294 		return -1;
295 	}
296 
297 	/* can we get away with skipping checksums? */
298 	has_sig = 0;
299 	if(level & ALPM_SIG_PACKAGE) {
300 		if(syncpkg && syncpkg->base64_sig) {
301 			has_sig = 1;
302 		} else {
303 			char *sigpath = _alpm_sigpath(handle, pkgfile);
304 			if(sigpath && !_alpm_access(handle, NULL, sigpath, R_OK)) {
305 				has_sig = 1;
306 			}
307 			free(sigpath);
308 		}
309 	}
310 
311 	if(syncpkg && !has_sig) {
312 		if(syncpkg->md5sum && !syncpkg->sha256sum) {
313 			_alpm_log(handle, ALPM_LOG_DEBUG, "md5sum: %s\n", syncpkg->md5sum);
314 			_alpm_log(handle, ALPM_LOG_DEBUG, "checking md5sum for %s\n", pkgfile);
315 			if(_alpm_test_checksum(pkgfile, syncpkg->md5sum, ALPM_PKG_VALIDATION_MD5SUM) != 0) {
316 				RET_ERR(handle, ALPM_ERR_PKG_INVALID_CHECKSUM, -1);
317 			}
318 			if(validation) {
319 				*validation |= ALPM_PKG_VALIDATION_MD5SUM;
320 			}
321 		}
322 
323 		if(syncpkg->sha256sum) {
324 			_alpm_log(handle, ALPM_LOG_DEBUG, "sha256sum: %s\n", syncpkg->sha256sum);
325 			_alpm_log(handle, ALPM_LOG_DEBUG, "checking sha256sum for %s\n", pkgfile);
326 			if(_alpm_test_checksum(pkgfile, syncpkg->sha256sum, ALPM_PKG_VALIDATION_SHA256SUM) != 0) {
327 				RET_ERR(handle, ALPM_ERR_PKG_INVALID_CHECKSUM, -1);
328 			}
329 			if(validation) {
330 				*validation |= ALPM_PKG_VALIDATION_SHA256SUM;
331 			}
332 		}
333 	}
334 
335 	/* even if we don't have a sig, run the check code if level tells us to */
336 	if(level & ALPM_SIG_PACKAGE) {
337 		const char *sig = syncpkg ? syncpkg->base64_sig : NULL;
338 		_alpm_log(handle, ALPM_LOG_DEBUG, "sig data: %s\n", sig ? sig : "<from .sig>");
339 		if(!has_sig && !(level & ALPM_SIG_PACKAGE_OPTIONAL)) {
340 			handle->pm_errno = ALPM_ERR_PKG_MISSING_SIG;
341 			return -1;
342 		}
343 		if(_alpm_check_pgp_helper(handle, pkgfile, sig,
344 					level & ALPM_SIG_PACKAGE_OPTIONAL, level & ALPM_SIG_PACKAGE_MARGINAL_OK,
345 					level & ALPM_SIG_PACKAGE_UNKNOWN_OK, sigdata)) {
346 			handle->pm_errno = ALPM_ERR_PKG_INVALID_SIG;
347 			return -1;
348 		}
349 		if(validation && has_sig) {
350 			*validation |= ALPM_PKG_VALIDATION_SIGNATURE;
351 		}
352 	}
353 
354 	if(validation && !*validation) {
355 		*validation = ALPM_PKG_VALIDATION_NONE;
356 	}
357 
358 	return 0;
359 }
360 
361 /**
362  * Handle the existence of simple paths for _alpm_load_pkg_internal()
363  * @param pkg package to change
364  * @param path path to examine
365  * @return 0 if path doesn't match any rule, 1 if it has been handled
366  */
handle_simple_path(alpm_pkg_t * pkg,const char * path)367 static int handle_simple_path(alpm_pkg_t *pkg, const char *path)
368 {
369 	if(strcmp(path, ".INSTALL") == 0) {
370 		pkg->scriptlet = 1;
371 		return 1;
372 	} else if(*path == '.') {
373 		/* for now, ignore all files starting with '.' that haven't
374 		 * already been handled (for future possibilities) */
375 		return 1;
376 	}
377 
378 	return 0;
379 }
380 
381 /**
382  * Add a file to the files list for pkg.
383  *
384  * @param pkg package to add the file to
385  * @param files_size size of pkg->files.files
386  * @param entry archive entry of the file to add to the list
387  * @param path path of the file to be added
388  * @return <0 on error, 0 on success
389  */
add_entry_to_files_list(alpm_filelist_t * filelist,size_t * files_size,struct archive_entry * entry,const char * path)390 static int add_entry_to_files_list(alpm_filelist_t *filelist,
391 		size_t *files_size, struct archive_entry *entry, const char *path)
392 {
393 	const size_t files_count = filelist->count;
394 	alpm_file_t *current_file;
395 	mode_t type;
396 	size_t pathlen;
397 
398 	if(!_alpm_greedy_grow((void **)&filelist->files,
399 				files_size, (files_count + 1) * sizeof(alpm_file_t))) {
400 		return -1;
401 	}
402 
403 	type = archive_entry_filetype(entry);
404 
405 	pathlen = strlen(path);
406 
407 	current_file = filelist->files + files_count;
408 
409 	/* mtree paths don't contain a tailing slash, those we get from
410 	 * the archive directly do (expensive way)
411 	 * Other code relies on it to detect directories so add it here.*/
412 	if(type == AE_IFDIR && path[pathlen - 1] != '/') {
413 		/* 2 = 1 for / + 1 for \0 */
414 		char *newpath;
415 		MALLOC(newpath, pathlen + 2, return -1);
416 		strcpy(newpath, path);
417 		newpath[pathlen] = '/';
418 		newpath[pathlen + 1] = '\0';
419 		current_file->name = newpath;
420 	} else {
421 		STRDUP(current_file->name, path, return -1);
422 	}
423 	current_file->size = archive_entry_size(entry);
424 	current_file->mode = archive_entry_mode(entry);
425 	filelist->count++;
426 	return 0;
427 }
428 
429 /**
430  * Generate a new file list from an mtree file and add it to the package.
431  * An existing file list will be free()d first.
432  *
433  * archive should point to an archive struct which is already at the
434  * position of the mtree's header.
435  *
436  * @param handle
437  * @param pkg package to add the file list to
438  * @param archive archive containing the mtree
439  * @return 0 on success, <0 on error
440  */
build_filelist_from_mtree(alpm_handle_t * handle,alpm_pkg_t * pkg,struct archive * archive)441 static int build_filelist_from_mtree(alpm_handle_t *handle, alpm_pkg_t *pkg, struct archive *archive)
442 {
443 	int ret = 0;
444 	size_t i;
445 	size_t mtree_maxsize = 0;
446 	size_t mtree_cursize = 0;
447 	size_t files_size = 0; /* we clean up the existing array so this is fine */
448 	char *mtree_data = NULL;
449 	struct archive *mtree;
450 	struct archive_entry *mtree_entry = NULL;
451 	alpm_filelist_t filelist;
452 
453 	_alpm_log(handle, ALPM_LOG_DEBUG,
454 			"found mtree for package %s, getting file list\n", pkg->filename);
455 
456 	memset(&filelist, 0, sizeof(alpm_filelist_t));
457 
458 	/* create a new archive to parse the mtree and load it from archive into memory */
459 	/* TODO: split this into a function */
460 	if((mtree = archive_read_new()) == NULL) {
461 		handle->pm_errno = ALPM_ERR_LIBARCHIVE;
462 		goto error;
463 	}
464 
465 	_alpm_archive_read_support_filter_all(mtree);
466 	archive_read_support_format_mtree(mtree);
467 
468 	/* TODO: split this into a function */
469 	while(1) {
470 		ssize_t size;
471 
472 		if(!_alpm_greedy_grow((void **)&mtree_data, &mtree_maxsize, mtree_cursize + ALPM_BUFFER_SIZE)) {
473 			goto error;
474 		}
475 
476 		size = archive_read_data(archive, mtree_data + mtree_cursize, ALPM_BUFFER_SIZE);
477 
478 		if(size < 0) {
479 			_alpm_log(handle, ALPM_LOG_DEBUG, _("error while reading package %s: %s\n"),
480 					pkg->filename, archive_error_string(archive));
481 			handle->pm_errno = ALPM_ERR_LIBARCHIVE;
482 			goto error;
483 		}
484 		if(size == 0) {
485 			break;
486 		}
487 
488 		mtree_cursize += size;
489 	}
490 
491 	if(archive_read_open_memory(mtree, mtree_data, mtree_cursize)) {
492 		_alpm_log(handle, ALPM_LOG_DEBUG,
493 				_("error while reading mtree of package %s: %s\n"),
494 				pkg->filename, archive_error_string(mtree));
495 		handle->pm_errno = ALPM_ERR_LIBARCHIVE;
496 		goto error;
497 	}
498 
499 	while((ret = archive_read_next_header(mtree, &mtree_entry)) == ARCHIVE_OK) {
500 		const char *path = archive_entry_pathname(mtree_entry);
501 
502 		/* strip leading "./" from path entries */
503 		if(path[0] == '.' && path[1] == '/') {
504 			path += 2;
505 		}
506 
507 		if(handle_simple_path(pkg, path)) {
508 			continue;
509 		}
510 
511 		if(add_entry_to_files_list(&filelist, &files_size, mtree_entry, path) < 0) {
512 			goto error;
513 		}
514 	}
515 
516 	if(ret != ARCHIVE_EOF && ret != ARCHIVE_OK) { /* An error occurred */
517 		_alpm_log(handle, ALPM_LOG_DEBUG, _("error while reading mtree of package %s: %s\n"),
518 				pkg->filename, archive_error_string(mtree));
519 		handle->pm_errno = ALPM_ERR_LIBARCHIVE;
520 		goto error;
521 	}
522 
523 	/* throw away any files we loaded directly from the archive */
524 	for(i = 0; i < pkg->files.count; i++) {
525 		free(pkg->files.files[i].name);
526 	}
527 	free(pkg->files.files);
528 
529 	/* copy over new filelist */
530 	memcpy(&pkg->files, &filelist, sizeof(alpm_filelist_t));
531 
532 	free(mtree_data);
533 	_alpm_archive_read_free(mtree);
534 	_alpm_log(handle, ALPM_LOG_DEBUG, "finished mtree reading for %s\n", pkg->filename);
535 	return 0;
536 error:
537 	/* throw away any files we loaded from the mtree */
538 	for(i = 0; i < filelist.count; i++) {
539 		free(filelist.files[i].name);
540 	}
541 	free(filelist.files);
542 
543 	free(mtree_data);
544 	_alpm_archive_read_free(mtree);
545 	return -1;
546 }
547 
548 /**
549  * Load a package and create the corresponding alpm_pkg_t struct.
550  * @param handle the context handle
551  * @param pkgfile path to the package file
552  * @param full whether to stop the load after metadata is read or continue
553  * through the full archive
554  */
_alpm_pkg_load_internal(alpm_handle_t * handle,const char * pkgfile,int full)555 alpm_pkg_t *_alpm_pkg_load_internal(alpm_handle_t *handle,
556 		const char *pkgfile, int full)
557 {
558 	int ret, fd;
559 	int config = 0;
560 	int hit_mtree = 0;
561 	struct archive *archive;
562 	struct archive_entry *entry;
563 	alpm_pkg_t *newpkg;
564 	struct stat st;
565 	size_t files_size = 0;
566 
567 	if(pkgfile == NULL || strlen(pkgfile) == 0) {
568 		RET_ERR(handle, ALPM_ERR_WRONG_ARGS, NULL);
569 	}
570 
571 	fd = _alpm_open_archive(handle, pkgfile, &st, &archive, ALPM_ERR_PKG_OPEN);
572 	if(fd < 0) {
573 		if(errno == ENOENT) {
574 			handle->pm_errno = ALPM_ERR_PKG_NOT_FOUND;
575 		} else if(errno == EACCES) {
576 			handle->pm_errno = ALPM_ERR_BADPERMS;
577 		} else {
578 			handle->pm_errno = ALPM_ERR_PKG_OPEN;
579 		}
580 		return NULL;
581 	}
582 
583 	newpkg = _alpm_pkg_new();
584 	if(newpkg == NULL) {
585 		handle->pm_errno = ALPM_ERR_MEMORY;
586 		goto error;
587 	}
588 	STRDUP(newpkg->filename, pkgfile,
589 			handle->pm_errno = ALPM_ERR_MEMORY; goto error);
590 	newpkg->size = st.st_size;
591 
592 	_alpm_log(handle, ALPM_LOG_DEBUG, "starting package load for %s\n", pkgfile);
593 
594 	/* If full is false, only read through the archive until we find our needed
595 	 * metadata. If it is true, read through the entire archive, which serves
596 	 * as a verification of integrity and allows us to create the filelist. */
597 	while((ret = archive_read_next_header(archive, &entry)) == ARCHIVE_OK) {
598 		const char *entry_name = archive_entry_pathname(entry);
599 
600 		if(strcmp(entry_name, ".PKGINFO") == 0) {
601 			/* parse the info file */
602 			if(parse_descfile(handle, archive, newpkg) != 0) {
603 				_alpm_log(handle, ALPM_LOG_ERROR, _("could not parse package description file in %s\n"),
604 						pkgfile);
605 				goto pkg_invalid;
606 			}
607 			if(newpkg->name == NULL || strlen(newpkg->name) == 0) {
608 				_alpm_log(handle, ALPM_LOG_ERROR, _("missing package name in %s\n"), pkgfile);
609 				goto pkg_invalid;
610 			}
611 			if(newpkg->version == NULL || strlen(newpkg->version) == 0) {
612 				_alpm_log(handle, ALPM_LOG_ERROR, _("missing package version in %s\n"), pkgfile);
613 				goto pkg_invalid;
614 			}
615 			if(strchr(newpkg->version, '-') == NULL) {
616 				_alpm_log(handle, ALPM_LOG_ERROR, _("invalid package version in %s\n"), pkgfile);
617 				goto pkg_invalid;
618 			}
619 			config = 1;
620 			continue;
621 		} else if(full && strcmp(entry_name, ".MTREE") == 0) {
622 			/* building the file list: cheap way
623 			 * get the filelist from the mtree file rather than scanning
624 			 * the whole archive  */
625 			hit_mtree = build_filelist_from_mtree(handle, newpkg, archive) == 0;
626 			continue;
627 		} else if(handle_simple_path(newpkg, entry_name)) {
628 			continue;
629 		} else if(full && !hit_mtree) {
630 			/* building the file list: expensive way */
631 			if(add_entry_to_files_list(&newpkg->files, &files_size, entry, entry_name) < 0) {
632 				goto error;
633 			}
634 		}
635 
636 		if(archive_read_data_skip(archive)) {
637 			_alpm_log(handle, ALPM_LOG_ERROR, _("error while reading package %s: %s\n"),
638 					pkgfile, archive_error_string(archive));
639 			handle->pm_errno = ALPM_ERR_LIBARCHIVE;
640 			goto error;
641 		}
642 
643 		/* if we are not doing a full read, see if we have all we need */
644 		if((!full || hit_mtree) && config) {
645 			break;
646 		}
647 	}
648 
649 	if(ret != ARCHIVE_EOF && ret != ARCHIVE_OK) { /* An error occurred */
650 		_alpm_log(handle, ALPM_LOG_ERROR, _("error while reading package %s: %s\n"),
651 				pkgfile, archive_error_string(archive));
652 		handle->pm_errno = ALPM_ERR_LIBARCHIVE;
653 		goto error;
654 	}
655 
656 	if(!config) {
657 		_alpm_log(handle, ALPM_LOG_ERROR, _("missing package metadata in %s\n"), pkgfile);
658 		goto pkg_invalid;
659 	}
660 
661 	_alpm_archive_read_free(archive);
662 	close(fd);
663 
664 	/* internal fields for package struct */
665 	newpkg->origin = ALPM_PKG_FROM_FILE;
666 	newpkg->origin_data.file = strdup(pkgfile);
667 	newpkg->ops = get_file_pkg_ops();
668 	newpkg->handle = handle;
669 	newpkg->infolevel = INFRQ_BASE | INFRQ_DESC | INFRQ_SCRIPTLET;
670 	newpkg->validation = ALPM_PKG_VALIDATION_NONE;
671 
672 	if(full) {
673 		if(newpkg->files.files) {
674 			/* attempt to hand back any memory we don't need */
675 			newpkg->files.files = realloc(newpkg->files.files,
676 					sizeof(alpm_file_t) * newpkg->files.count);
677 			/* "checking for conflicts" requires a sorted list, ensure that here */
678 			_alpm_log(handle, ALPM_LOG_DEBUG,
679 					"sorting package filelist for %s\n", pkgfile);
680 
681 			_alpm_filelist_sort(&newpkg->files);
682 		}
683 		newpkg->infolevel |= INFRQ_FILES;
684 	}
685 
686 	return newpkg;
687 
688 pkg_invalid:
689 	handle->pm_errno = ALPM_ERR_PKG_INVALID;
690 error:
691 	_alpm_pkg_free(newpkg);
692 	_alpm_archive_read_free(archive);
693 	if(fd >= 0) {
694 		close(fd);
695 	}
696 
697 	return NULL;
698 }
699 
700 /* adopted limit from repo-add */
701 #define MAX_SIGFILE_SIZE 16384
702 
read_sigfile(const char * sigpath,unsigned char ** sig)703 static int read_sigfile(const char *sigpath, unsigned char **sig)
704 {
705 	struct stat st;
706 	FILE *fp;
707 
708 	if((fp = fopen(sigpath, "rb")) == NULL) {
709 		return -1;
710 	}
711 
712 	if(fstat(fileno(fp), &st) != 0 || st.st_size > MAX_SIGFILE_SIZE) {
713 		fclose(fp);
714 		return -1;
715 	}
716 
717 	MALLOC(*sig, st.st_size, fclose(fp); return -1);
718 
719 	if(fread(*sig, st.st_size, 1, fp) != 1) {
720 		free(*sig);
721 		fclose(fp);
722 		return -1;
723 	}
724 
725 	fclose(fp);
726 	return st.st_size;
727 }
728 
alpm_pkg_load(alpm_handle_t * handle,const char * filename,int full,int level,alpm_pkg_t ** pkg)729 int SYMEXPORT alpm_pkg_load(alpm_handle_t *handle, const char *filename, int full,
730 		int level, alpm_pkg_t **pkg)
731 {
732 	int validation = 0;
733 	char *sigpath;
734 
735 	CHECK_HANDLE(handle, return -1);
736 	ASSERT(pkg != NULL, RET_ERR(handle, ALPM_ERR_WRONG_ARGS, -1));
737 
738 	sigpath = _alpm_sigpath(handle, filename);
739 	if(sigpath && !_alpm_access(handle, NULL, sigpath, R_OK)) {
740 		if(level & ALPM_SIG_PACKAGE) {
741 			alpm_list_t *keys = NULL;
742 			int fail = 0;
743 			unsigned char *sig = NULL;
744 			int len = read_sigfile(sigpath, &sig);
745 
746 			if(len == -1) {
747 				_alpm_log(handle, ALPM_LOG_ERROR,
748 					_("failed to read signature file: %s\n"), sigpath);
749 				free(sigpath);
750 				return -1;
751 			}
752 
753 			if(alpm_extract_keyid(handle, filename, sig, len, &keys) == 0) {
754 				alpm_list_t *k;
755 				for(k = keys; k; k = k->next) {
756 					char *key = k->data;
757 					if(_alpm_key_in_keychain(handle, key) == 0) {
758 						if(_alpm_key_import(handle, key) == -1) {
759 							fail = 1;
760 						}
761 					}
762 				}
763 				FREELIST(keys);
764 			}
765 
766 			free(sig);
767 
768 			if(fail) {
769 				_alpm_log(handle, ALPM_LOG_ERROR, _("required key missing from keyring\n"));
770 				free(sigpath);
771 				return -1;
772 			}
773 		}
774 	}
775 	free(sigpath);
776 
777 	if(_alpm_pkg_validate_internal(handle, filename, NULL, level, NULL,
778 				&validation) == -1) {
779 		/* pm_errno is set by pkg_validate */
780 		return -1;
781 	}
782 	*pkg = _alpm_pkg_load_internal(handle, filename, full);
783 	if(*pkg == NULL) {
784 		/* pm_errno is set by pkg_load */
785 		return -1;
786 	}
787 	(*pkg)->validation = validation;
788 
789 	return 0;
790 }
791