PlaylistFile.cxx 9.2 KB
Newer Older
1
/*
2
 * Copyright 2003-2016 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"
Max Kellermann's avatar
Max Kellermann committed
21
#include "PlaylistFile.hxx"
22
#include "PlaylistSave.hxx"
23
#include "PlaylistError.hxx"
24 25
#include "db/PlaylistInfo.hxx"
#include "db/PlaylistVector.hxx"
26
#include "DetachedSong.hxx"
27
#include "SongLoader.hxx"
Max Kellermann's avatar
Max Kellermann committed
28
#include "Mapper.hxx"
29
#include "fs/io/TextFile.hxx"
30 31
#include "fs/io/FileOutputStream.hxx"
#include "fs/io/BufferedOutputStream.hxx"
32 33 34
#include "config/ConfigGlobal.hxx"
#include "config/ConfigOption.hxx"
#include "config/ConfigDefaults.hxx"
Max Kellermann's avatar
Max Kellermann committed
35
#include "Idle.hxx"
36
#include "fs/Limits.hxx"
37
#include "fs/AllocatedPath.hxx"
38
#include "fs/Traits.hxx"
39
#include "fs/Charset.hxx"
40
#include "fs/FileSystem.hxx"
41
#include "fs/FileInfo.hxx"
42
#include "fs/DirectoryReader.hxx"
43
#include "util/Macros.hxx"
44
#include "util/StringCompare.hxx"
Max Kellermann's avatar
Max Kellermann committed
45
#include "util/UriUtil.hxx"
46
#include "util/Error.hxx"
47

48 49
#include <memory>

Max Kellermann's avatar
Max Kellermann committed
50 51 52
#include <assert.h>
#include <sys/stat.h>
#include <string.h>
53
#include <errno.h>
54

55 56
static const char PLAYLIST_COMMENT = '#';

57 58 59 60 61 62
static unsigned playlist_max_length;
bool playlist_saveAbsolutePaths = DEFAULT_PLAYLIST_SAVE_ABSOLUTE_PATHS;

void
spl_global_init(void)
{
63 64 65
	playlist_max_length =
		config_get_positive(ConfigOption::MAX_PLAYLIST_LENGTH,
				    DEFAULT_PLAYLIST_MAX_LENGTH);
66 67

	playlist_saveAbsolutePaths =
68
		config_get_bool(ConfigOption::SAVE_ABSOLUTE_PATHS,
69 70 71
				DEFAULT_PLAYLIST_SAVE_ABSOLUTE_PATHS);
}

72 73 74
bool
spl_valid_name(const char *name_utf8)
{
75
	if (StringIsEmpty(name_utf8))
76 77 78
		/* empty name not allowed */
		return false;

79 80 81 82 83 84 85 86 87 88 89
	/*
	 * Not supporting '/' was done out of laziness, and we should
	 * really strive to support it in the future.
	 *
	 * Not supporting '\r' and '\n' is done out of protocol
	 * limitations (and arguably laziness), but bending over head
	 * over heels to modify the protocol (and compatibility with
	 * all clients) to support idiots who put '\r' and '\n' in
	 * filenames isn't going to happen, either.
	 */

90 91 92
	return strchr(name_utf8, '/') == nullptr &&
		strchr(name_utf8, '\n') == nullptr &&
		strchr(name_utf8, '\r') == nullptr;
93 94
}

95
static const AllocatedPath &
96
spl_map()
97
{
98
	const AllocatedPath &path_fs = map_spl_path();
99
	if (path_fs.IsNull())
100 101 102
		throw PlaylistError(PlaylistResult::DISABLED,
				    "Stored playlists are disabled");

103
	return path_fs;
104 105
}

106 107
static void
spl_check_name(const char *name_utf8)
108
{
109 110
	if (!spl_valid_name(name_utf8))
		throw PlaylistError(PlaylistResult::BAD_NAME,
111 112 113
				    "Bad playlist name");
}

114
AllocatedPath
115
spl_map_to_fs(const char *name_utf8)
116
{
117 118
	spl_map();
	spl_check_name(name_utf8);
119

120
	auto path_fs = map_spl_utf8_to_fs(name_utf8);
121
	if (path_fs.IsNull())
122 123
		throw PlaylistError(PlaylistResult::BAD_NAME,
				    "Bad playlist name");
124 125 126 127 128

	return path_fs;
}

/**
129
 * Throw an exception for the current errno.
130 131
 */
static void
132
ThrowPlaylistErrno()
133 134 135
{
	switch (errno) {
	case ENOENT:
136 137
		throw PlaylistError(PlaylistResult::NO_SUCH_LIST,
				    "No such playlist");
138 139

	default:
140 141 142
		throw std::system_error(std::error_code(errno,
							std::system_category()),
					"Error");
143 144 145
	}
}

146
static bool
147
LoadPlaylistFileInfo(PlaylistInfo &info,
148 149
		     const Path parent_path_fs,
		     const Path name_fs)
150
{
151 152 153
	if (name_fs.HasNewline())
		return false;

154
	const auto *const name_fs_str = name_fs.c_str();
155
	const auto *const name_fs_end =
156 157
		FindStringSuffix(name_fs_str,
				 PATH_LITERAL(PLAYLIST_FILE_SUFFIX));
158
	if (name_fs_end == nullptr)
159
		return false;
160

161
	FileInfo fi;
162 163
	if (!GetFileInfo(AllocatedPath::Build(parent_path_fs, name_fs), fi) ||
	    !fi.IsRegular())
164
		return false;
165

166
	PathTraitsFS::string name(name_fs_str, name_fs_end);
167
	std::string name_utf8 = PathToUTF8(name.c_str());
168
	if (name_utf8.empty())
169
		return false;
170

171
	info.name = std::move(name_utf8);
172
	info.mtime = fi.GetModificationTime();
173
	return true;
174 175
}

176
PlaylistVector
177
ListPlaylistFiles()
178
{
179
	PlaylistVector list;
180

181 182
	const auto &parent_path_fs = spl_map();
	assert(!parent_path_fs.IsNull());
183

184
	DirectoryReader reader(parent_path_fs);
185

186
	PlaylistInfo info;
187
	while (reader.ReadEntry()) {
188
		const auto entry = reader.GetEntry();
189
		if (LoadPlaylistFileInfo(info, parent_path_fs, entry))
190
			list.push_back(std::move(info));
191 192 193 194 195
	}

	return list;
}

196 197
static void
SavePlaylistFile(const PlaylistFileContents &contents, const char *utf8path)
198
{
199
	assert(utf8path != nullptr);
200

201 202
	const auto path_fs = spl_map_to_fs(utf8path);
	assert(!path_fs.IsNull());
203

204
	FileOutputStream fos(path_fs);
205

206 207
	BufferedOutputStream bos(fos);

208
	for (const auto &uri_utf8 : contents)
209
		playlist_print_uri(bos, uri_utf8.c_str());
210

211
	bos.Flush();
212 213

	fos.Commit();
214 215
}

216
PlaylistFileContents
217
LoadPlaylistFile(const char *utf8path)
218
try {
219 220
	PlaylistFileContents contents;

221 222
	const auto path_fs = spl_map_to_fs(utf8path);
	assert(!path_fs.IsNull());
223

224
	TextFile file(path_fs);
225

226
	char *s;
227
	while ((s = file.ReadLine()) != nullptr) {
228
		if (*s == 0 || *s == PLAYLIST_COMMENT)
229
			continue;
230

231 232 233 234 235 236 237 238 239
#ifdef _UNICODE
		wchar_t buffer[MAX_PATH];
		auto result = MultiByteToWideChar(CP_ACP, 0, s, -1,
						  buffer, ARRAY_SIZE(buffer));
		if (result <= 0)
			continue;

		const Path path = Path::FromFS(buffer);
#else
Max Kellermann's avatar
Max Kellermann committed
240
		const Path path = Path::FromFS(s);
241
#endif
Max Kellermann's avatar
Max Kellermann committed
242

243 244
		std::string uri_utf8;

245
		if (!uri_has_scheme(s)) {
246
#ifdef ENABLE_DATABASE
Max Kellermann's avatar
Max Kellermann committed
247
			uri_utf8 = map_fs_to_utf8(path);
248
			if (uri_utf8.empty()) {
Max Kellermann's avatar
Max Kellermann committed
249
				if (path.IsAbsolute()) {
250
					uri_utf8 = path.ToUTF8();
251 252 253 254 255
					if (uri_utf8.empty())
						continue;
				} else
					continue;
			}
256 257 258
#else
			continue;
#endif
259
		} else {
Max Kellermann's avatar
Max Kellermann committed
260
			uri_utf8 = path.ToUTF8();
261
			if (uri_utf8.empty())
262 263
				continue;
		}
264

265
		contents.emplace_back(std::move(uri_utf8));
266
		if (contents.size() >= playlist_max_length)
267
			break;
268 269
	}

270
	return contents;
271 272 273 274
} catch (const std::system_error &e) {
	if (IsFileNotFound(e))
		throw PlaylistError::NoSuchList();
	throw;
275 276
}

277 278
void
spl_move_index(const char *utf8path, unsigned src, unsigned dest)
279
{
280 281 282
	if (src == dest)
		/* this doesn't check whether the playlist exists, but
		   what the hell.. */
283
		return;
284

285
	auto contents = LoadPlaylistFile(utf8path);
286

287 288
	if (src >= contents.size() || dest >= contents.size())
		throw PlaylistError(PlaylistResult::BAD_RANGE, "Bad range");
289

290 291 292
	const auto src_i = std::next(contents.begin(), src);
	auto value = std::move(*src_i);
	contents.erase(src_i);
293

294 295
	const auto dest_i = std::next(contents.begin(), dest);
	contents.insert(dest_i, std::move(value));
296

297
	SavePlaylistFile(contents, utf8path);
298 299

	idle_add(IDLE_STORED_PLAYLIST);
300 301
}

302 303
void
spl_clear(const char *utf8path)
304
{
305 306
	const auto path_fs = spl_map_to_fs(utf8path);
	assert(!path_fs.IsNull());
307

308
	FILE *file = FOpen(path_fs, FOpenMode::WriteText);
309 310
	if (file == nullptr)
		ThrowPlaylistErrno();
311

312
	fclose(file);
313 314

	idle_add(IDLE_STORED_PLAYLIST);
315 316
}

317 318
void
spl_delete(const char *name_utf8)
319
{
320 321
	const auto path_fs = spl_map_to_fs(name_utf8);
	assert(!path_fs.IsNull());
322

323 324
	if (!RemoveFile(path_fs))
		ThrowPlaylistErrno();
325

326
	idle_add(IDLE_STORED_PLAYLIST);
327 328
}

329 330
void
spl_remove_index(const char *utf8path, unsigned pos)
331
{
332
	auto contents = LoadPlaylistFile(utf8path);
333

334 335
	if (pos >= contents.size())
		throw PlaylistError(PlaylistResult::BAD_RANGE, "Bad range");
336

337
	contents.erase(std::next(contents.begin(), pos));
338

339
	SavePlaylistFile(contents, utf8path);
340
	idle_add(IDLE_STORED_PLAYLIST);
341 342
}

343 344
void
spl_append_song(const char *utf8path, const DetachedSong &song)
345
try {
346 347
	const auto path_fs = spl_map_to_fs(utf8path);
	assert(!path_fs.IsNull());
348

349
	AppendFileOutputStream fos(path_fs);
350

351 352 353
	if (fos.Tell() / (MPD_PATH_MAX + 1) >= playlist_max_length)
		throw PlaylistError(PlaylistResult::TOO_LARGE,
				    "Stored playlist is too large");
354

355
	BufferedOutputStream bos(fos);
356

357 358
	playlist_print_song(bos, song);

359
	bos.Flush();
360 361
	fos.Commit();

362
	idle_add(IDLE_STORED_PLAYLIST);
363 364 365 366
} catch (const std::system_error &e) {
	if (IsFileNotFound(e))
		throw PlaylistError::NoSuchList();
	throw;
367 368
}

369
bool
370 371 372
spl_append_uri(const char *utf8file,
	       const SongLoader &loader, const char *url,
	       Error &error)
373
{
374
	std::unique_ptr<DetachedSong> song(loader.LoadSong(url, error));
375
	if (song == nullptr)
376
		return false;
377

378 379
	spl_append_song(utf8file, *song);
	return true;
380 381
}

382 383
static void
spl_rename_internal(Path from_path_fs, Path to_path_fs)
384
{
385 386 387
	if (!FileExists(from_path_fs))
		throw PlaylistError(PlaylistResult::NO_SUCH_LIST,
				    "No such playlist");
388

389 390 391
	if (FileExists(to_path_fs))
		throw PlaylistError(PlaylistResult::LIST_EXISTS,
				    "Playlist exists already");
392

393 394
	if (!RenameFile(from_path_fs, to_path_fs))
		ThrowPlaylistErrno();
395

396
	idle_add(IDLE_STORED_PLAYLIST);
397
}
398

399 400
void
spl_rename(const char *utf8from, const char *utf8to)
401
{
402 403
	const auto from_path_fs = spl_map_to_fs(utf8from);
	assert(!from_path_fs.IsNull());
404

405 406
	const auto to_path_fs = spl_map_to_fs(utf8to);
	assert(!to_path_fs.IsNull());
407

408
	spl_rename_internal(from_path_fs, to_path_fs);
409
}