ArchiveLookup.cxx 2.26 KB
Newer Older
1
/*
2
 * Copyright 2003-2018 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 "ArchiveLookup.hxx"
21
#include "ArchiveDomain.hxx"
22
#include "Log.hxx"
23

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

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

	return nullptr;
}

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

	return nullptr;
}

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

57
	char *slash = nullptr;
58

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

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

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

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

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

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