ArchiveLookup.cxx 2.31 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright (C) 2003-2014 The Music Player Daemon Project
3
 * http://www.musicpd.org
4 5 6 7 8 9 10 11 12 13
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
14 15 16 17
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 19
 */

20
#include "config.h" /* must be first for large file support */
21
#include "ArchiveLookup.hxx"
22
#include "ArchiveDomain.hxx"
23
#include "Log.hxx"
24

25 26 27
#include <string.h>
#include <sys/stat.h>
#include <errno.h>
28

29 30 31 32 33 34 35 36 37 38 39
gcc_pure
static char *
FindSlash(char *p, size_t i)
{
	for (; i > 0; --i)
		if (p[i] == '/')
			return p + i;

	return nullptr;
}

40 41
gcc_pure
static const char *
42
FindSuffix(const char *p, const char *i)
43
{
44 45 46
	for (; i > p; --i) {
		if (*i == '.')
			return i + 1;
47 48 49 50 51
	}

	return nullptr;
}

52 53 54
bool
archive_lookup(char *pathname, const char **archive,
	       const char **inpath, const char **suffix)
55
{
56
	size_t idx = strlen(pathname);
57

58
	char *slash = nullptr;
59

60
	while (true) {
61
		//try to stat if its real directory
62
		struct stat st_info;
63
		if (stat(pathname, &st_info) == -1) {
64
			if (errno != ENOTDIR) {
65
				FormatErrno(archive_domain,
66 67
					    "Failed to stat %s", pathname);
				return false;
68 69 70
			}
		} else {
			//is something found ins original path (is not an archive)
71 72 73
			if (slash == nullptr)
				return false;

74 75 76 77
			//its a file ?
			if (S_ISREG(st_info.st_mode)) {
				//so the upper should be file
				*archive = pathname;
78
				*inpath = slash + 1;
79 80

				//try to get suffix
81 82
				*suffix = FindSuffix(pathname, slash - 1);
				return true;
83
			} else {
84 85
				FormatError(archive_domain,
					    "Not a regular file: %s",
86 87
					    pathname);
				return false;
88 89
			}
		}
90

91
		//find one dir up
92 93 94 95
		if (slash != nullptr)
			*slash = '/';

		slash = FindSlash(pathname, idx - 1);
96
		if (slash == nullptr)
97
			return false;
98 99

		*slash = 0;
100
		idx = slash - pathname;
101 102 103
	}
}