PlaylistFile.cxx 10.6 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright (C) 2003-2015 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 24
#include "db/PlaylistInfo.hxx"
#include "db/PlaylistVector.hxx"
25
#include "DetachedSong.hxx"
26
#include "SongLoader.hxx"
Max Kellermann's avatar
Max Kellermann committed
27
#include "Mapper.hxx"
28
#include "fs/io/TextFile.hxx"
29 30 31
#include "config/ConfigGlobal.hxx"
#include "config/ConfigOption.hxx"
#include "config/ConfigDefaults.hxx"
Max Kellermann's avatar
Max Kellermann committed
32
#include "Idle.hxx"
33
#include "fs/Limits.hxx"
34
#include "fs/AllocatedPath.hxx"
35
#include "fs/Traits.hxx"
36
#include "fs/Charset.hxx"
37
#include "fs/FileSystem.hxx"
38
#include "fs/DirectoryReader.hxx"
39
#include "util/StringUtil.hxx"
Max Kellermann's avatar
Max Kellermann committed
40
#include "util/UriUtil.hxx"
41
#include "util/Error.hxx"
42

Max Kellermann's avatar
Max Kellermann committed
43 44 45
#include <assert.h>
#include <sys/stat.h>
#include <string.h>
46
#include <errno.h>
47

48 49
static const char PLAYLIST_COMMENT = '#';

50 51 52 53 54 55 56 57 58 59 60 61 62 63
static unsigned playlist_max_length;
bool playlist_saveAbsolutePaths = DEFAULT_PLAYLIST_SAVE_ABSOLUTE_PATHS;

void
spl_global_init(void)
{
	playlist_max_length = config_get_positive(CONF_MAX_PLAYLIST_LENGTH,
						  DEFAULT_PLAYLIST_MAX_LENGTH);

	playlist_saveAbsolutePaths =
		config_get_bool(CONF_SAVE_ABSOLUTE_PATHS,
				DEFAULT_PLAYLIST_SAVE_ABSOLUTE_PATHS);
}

64 65 66
bool
spl_valid_name(const char *name_utf8)
{
67 68 69 70
	if (*name_utf8 == 0)
		/* empty name not allowed */
		return false;

71 72 73 74 75 76 77 78 79 80 81
	/*
	 * 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.
	 */

82 83 84
	return strchr(name_utf8, '/') == nullptr &&
		strchr(name_utf8, '\n') == nullptr &&
		strchr(name_utf8, '\r') == nullptr;
85 86
}

87
static const AllocatedPath &
88
spl_map(Error &error)
89
{
90
	const AllocatedPath &path_fs = map_spl_path();
91
	if (path_fs.IsNull())
92
		error.Set(playlist_domain, int(PlaylistResult::DISABLED),
93
			  "Stored playlists are disabled");
94
	return path_fs;
95 96 97
}

static bool
98
spl_check_name(const char *name_utf8, Error &error)
99 100
{
	if (!spl_valid_name(name_utf8)) {
101
		error.Set(playlist_domain, int(PlaylistResult::BAD_NAME),
102 103 104 105 106 107 108
				    "Bad playlist name");
		return false;
	}

	return true;
}

109
static AllocatedPath
110
spl_map_to_fs(const char *name_utf8, Error &error)
111
{
112
	if (spl_map(error).IsNull() || !spl_check_name(name_utf8, error))
113
		return AllocatedPath::Null();
114

115
	auto path_fs = map_spl_utf8_to_fs(name_utf8);
116
	if (path_fs.IsNull())
117
		error.Set(playlist_domain, int(PlaylistResult::BAD_NAME),
118
			  "Bad playlist name");
119 120 121 122

	return path_fs;
}

123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
gcc_pure
static bool
IsNotFoundError(const Error &error)
{
#ifdef WIN32
	return error.IsDomain(win32_domain) &&
		error.GetCode() == ERROR_FILE_NOT_FOUND;
#else
	return error.IsDomain(errno_domain) &&
		error.GetCode() == ENOENT;
#endif
}

static void
TranslatePlaylistError(Error &error)
{
	if (IsNotFoundError(error)) {
		error.Clear();
		error.Set(playlist_domain, int(PlaylistResult::NO_SUCH_LIST),
			  "No such playlist");
	}
}

146
/**
147
 * Create an #Error for the current errno.
148 149
 */
static void
150
playlist_errno(Error &error)
151 152 153
{
	switch (errno) {
	case ENOENT:
154
		error.Set(playlist_domain, int(PlaylistResult::NO_SUCH_LIST),
155
			  "No such playlist");
156 157 158
		break;

	default:
159
		error.SetErrno();
160 161 162 163
		break;
	}
}

164
static bool
165
LoadPlaylistFileInfo(PlaylistInfo &info,
166 167
		     const Path parent_path_fs,
		     const Path name_fs)
168
{
169 170
	const char *name_fs_str = name_fs.c_str();
	size_t name_length = strlen(name_fs_str);
171

172
	if (name_length < sizeof(PLAYLIST_FILE_SUFFIX) ||
173
	    memchr(name_fs_str, '\n', name_length) != nullptr)
174
		return false;
175

176
	if (!StringEndsWith(name_fs_str, PLAYLIST_FILE_SUFFIX))
177
		return false;
178

179
	const auto path_fs = AllocatedPath::Build(parent_path_fs, name_fs);
180
	struct stat st;
181
	if (!StatFile(path_fs, st) || !S_ISREG(st.st_mode))
182
		return false;
183

184 185 186
	std::string name(name_fs_str,
			 name_length + 1 - sizeof(PLAYLIST_FILE_SUFFIX));
	std::string name_utf8 = PathToUTF8(name.c_str());
187
	if (name_utf8.empty())
188
		return false;
189

190
	info.name = std::move(name_utf8);
191 192
	info.mtime = st.st_mtime;
	return true;
193 194
}

195
PlaylistVector
196
ListPlaylistFiles(Error &error)
197
{
198
	PlaylistVector list;
199

200
	const auto &parent_path_fs = spl_map(error);
201
	if (parent_path_fs.IsNull())
202
		return list;
203

204 205
	DirectoryReader reader(parent_path_fs);
	if (reader.HasFailed()) {
206
		error.SetErrno();
207
		return list;
208
	}
209

210
	PlaylistInfo info;
211
	while (reader.ReadEntry()) {
212
		const auto entry = reader.GetEntry();
213
		if (LoadPlaylistFileInfo(info, parent_path_fs, entry))
214
			list.push_back(std::move(info));
215 216 217 218 219
	}

	return list;
}

220
static bool
221
SavePlaylistFile(const PlaylistFileContents &contents, const char *utf8path,
222
		 Error &error)
223
{
224
	assert(utf8path != nullptr);
225

226
	if (spl_map(error).IsNull())
227
		return false;
228

229
	const auto path_fs = spl_map_to_fs(utf8path, error);
230
	if (path_fs.IsNull())
231
		return false;
232

233
	FILE *file = FOpen(path_fs, FOpenMode::WriteText);
234
	if (file == nullptr) {
235
		playlist_errno(error);
236 237
		return false;
	}
238

239 240
	for (const auto &uri_utf8 : contents)
		playlist_print_uri(file, uri_utf8.c_str());
241

242
	fclose(file);
243
	return true;
244 245
}

246
PlaylistFileContents
247
LoadPlaylistFile(const char *utf8path, Error &error)
248
{
249 250
	PlaylistFileContents contents;

251
	if (spl_map(error).IsNull())
252
		return contents;
253

254
	const auto path_fs = spl_map_to_fs(utf8path, error);
255
	if (path_fs.IsNull())
256
		return contents;
257

258
	TextFile file(path_fs, error);
259
	if (file.HasFailed()) {
260
		TranslatePlaylistError(error);
261
		return contents;
262
	}
263

264
	char *s;
265
	while ((s = file.ReadLine()) != nullptr) {
266
		if (*s == 0 || *s == PLAYLIST_COMMENT)
267
			continue;
268

269 270
		std::string uri_utf8;

271
		if (!uri_has_scheme(s)) {
272
#ifdef ENABLE_DATABASE
273
			uri_utf8 = map_fs_to_utf8(s);
274
			if (uri_utf8.empty()) {
275
				if (PathTraitsFS::IsAbsolute(s)) {
276
					uri_utf8 = PathToUTF8(s);
277 278 279 280 281 282 283
					if (uri_utf8.empty())
						continue;

					uri_utf8.insert(0, "file://");
				} else
					continue;
			}
284 285 286
#else
			continue;
#endif
287
		} else {
288
			uri_utf8 = PathToUTF8(s);
289
			if (uri_utf8.empty())
290 291
				continue;
		}
292

293
		contents.emplace_back(std::move(uri_utf8));
294
		if (contents.size() >= playlist_max_length)
295
			break;
296 297
	}

298
	return contents;
299 300
}

301 302
bool
spl_move_index(const char *utf8path, unsigned src, unsigned dest,
303
	       Error &error)
304
{
305 306 307
	if (src == dest)
		/* this doesn't check whether the playlist exists, but
		   what the hell.. */
308
		return true;
309

310 311
	auto contents = LoadPlaylistFile(utf8path, error);
	if (contents.empty() && error.IsDefined())
312
		return false;
313

314
	if (src >= contents.size() || dest >= contents.size()) {
315
		error.Set(playlist_domain, int(PlaylistResult::BAD_RANGE),
316
			  "Bad range");
317
		return false;
318 319
	}

320 321 322
	const auto src_i = std::next(contents.begin(), src);
	auto value = std::move(*src_i);
	contents.erase(src_i);
323

324 325
	const auto dest_i = std::next(contents.begin(), dest);
	contents.insert(dest_i, std::move(value));
326

327
	bool result = SavePlaylistFile(contents, utf8path, error);
328 329

	idle_add(IDLE_STORED_PLAYLIST);
330
	return result;
331 332
}

333
bool
334
spl_clear(const char *utf8path, Error &error)
335
{
336
	if (spl_map(error).IsNull())
337
		return false;
338

339
	const auto path_fs = spl_map_to_fs(utf8path, error);
340
	if (path_fs.IsNull())
341
		return false;
342

343
	FILE *file = FOpen(path_fs, FOpenMode::WriteText);
344
	if (file == nullptr) {
345
		playlist_errno(error);
346 347
		return false;
	}
348

349
	fclose(file);
350 351

	idle_add(IDLE_STORED_PLAYLIST);
352
	return true;
353 354
}

355
bool
356
spl_delete(const char *name_utf8, Error &error)
357
{
358
	const auto path_fs = spl_map_to_fs(name_utf8, error);
359
	if (path_fs.IsNull())
360
		return false;
361

362
	if (!RemoveFile(path_fs)) {
363
		playlist_errno(error);
364 365
		return false;
	}
366

367
	idle_add(IDLE_STORED_PLAYLIST);
368
	return true;
369 370
}

371
bool
372
spl_remove_index(const char *utf8path, unsigned pos, Error &error)
373
{
374 375
	auto contents = LoadPlaylistFile(utf8path, error);
	if (contents.empty() && error.IsDefined())
376
		return false;
377

378
	if (pos >= contents.size()) {
379
		error.Set(playlist_domain, int(PlaylistResult::BAD_RANGE),
380
			  "Bad range");
381
		return false;
382 383
	}

384
	contents.erase(std::next(contents.begin(), pos));
385

386
	bool result = SavePlaylistFile(contents, utf8path, error);
387 388

	idle_add(IDLE_STORED_PLAYLIST);
389
	return result;
390 391
}

392
bool
393
spl_append_song(const char *utf8path, const DetachedSong &song, Error &error)
394
{
395
	if (spl_map(error).IsNull())
396
		return false;
397

398
	const auto path_fs = spl_map_to_fs(utf8path, error);
399
	if (path_fs.IsNull())
400
		return false;
401

402
	FILE *file = FOpen(path_fs, FOpenMode::AppendText);
403
	if (file == nullptr) {
404
		playlist_errno(error);
405 406
		return false;
	}
407

408
	struct stat st;
409
	if (fstat(fileno(file), &st) < 0) {
410
		playlist_errno(error);
411
		fclose(file);
412
		return false;
413
	}
414

415
	if (st.st_size / off_t(MPD_PATH_MAX + 1) >= (off_t)playlist_max_length) {
416
		fclose(file);
417
		error.Set(playlist_domain, int(PlaylistResult::TOO_LARGE),
418
			  "Stored playlist is too large");
419
		return false;
420
	}
421

422
	playlist_print_song(file, song);
423

424
	fclose(file);
425 426

	idle_add(IDLE_STORED_PLAYLIST);
427
	return true;
428 429
}

430
bool
431 432 433
spl_append_uri(const char *utf8file,
	       const SongLoader &loader, const char *url,
	       Error &error)
434
{
435 436
	DetachedSong *song = loader.LoadSong(url, error);
	if (song == nullptr)
437
		return false;
438 439 440 441

	bool success = spl_append_song(utf8file, *song, error);
	delete song;
	return success;
442 443
}

444
static bool
445
spl_rename_internal(Path from_path_fs, Path to_path_fs,
446
		    Error &error)
447
{
448
	if (!FileExists(from_path_fs)) {
449
		error.Set(playlist_domain, int(PlaylistResult::NO_SUCH_LIST),
450
			  "No such playlist");
451 452
		return false;
	}
453

454
	if (FileExists(to_path_fs)) {
455
		error.Set(playlist_domain, int(PlaylistResult::LIST_EXISTS),
456
			  "Playlist exists already");
457 458
		return false;
	}
459

460
	if (!RenameFile(from_path_fs, to_path_fs)) {
461
		playlist_errno(error);
462 463
		return false;
	}
464

465
	idle_add(IDLE_STORED_PLAYLIST);
466
	return true;
467
}
468

469
bool
470
spl_rename(const char *utf8from, const char *utf8to, Error &error)
471
{
472
	if (spl_map(error).IsNull())
473
		return false;
474

475
	const auto from_path_fs = spl_map_to_fs(utf8from, error);
476
	if (from_path_fs.IsNull())
477
		return false;
478

479
	const auto to_path_fs = spl_map_to_fs(utf8to, error);
480
	if (to_path_fs.IsNull())
481
		return false;
482

483
	return spl_rename_internal(from_path_fs, to_path_fs, error);
484
}