PlaylistFile.cxx 10.7 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
#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/StringUtil.hxx"
Max Kellermann's avatar
Max Kellermann committed
45
#include "util/UriUtil.hxx"
46
#include "util/Error.hxx"
47

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

53 54
static const char PLAYLIST_COMMENT = '#';

55 56 57 58 59 60
static unsigned playlist_max_length;
bool playlist_saveAbsolutePaths = DEFAULT_PLAYLIST_SAVE_ABSOLUTE_PATHS;

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

	playlist_saveAbsolutePaths =
66
		config_get_bool(ConfigOption::SAVE_ABSOLUTE_PATHS,
67 68 69
				DEFAULT_PLAYLIST_SAVE_ABSOLUTE_PATHS);
}

70 71 72
bool
spl_valid_name(const char *name_utf8)
{
73 74 75 76
	if (*name_utf8 == 0)
		/* empty name not allowed */
		return false;

77 78 79 80 81 82 83 84 85 86 87
	/*
	 * 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.
	 */

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

93
static const AllocatedPath &
94
spl_map(Error &error)
95
{
96
	const AllocatedPath &path_fs = map_spl_path();
97
	if (path_fs.IsNull())
98
		error.Set(playlist_domain, int(PlaylistResult::DISABLED),
99
			  "Stored playlists are disabled");
100
	return path_fs;
101 102 103
}

static bool
104
spl_check_name(const char *name_utf8, Error &error)
105 106
{
	if (!spl_valid_name(name_utf8)) {
107
		error.Set(playlist_domain, int(PlaylistResult::BAD_NAME),
108 109 110 111 112 113 114
				    "Bad playlist name");
		return false;
	}

	return true;
}

115
AllocatedPath
116
spl_map_to_fs(const char *name_utf8, Error &error)
117
{
118
	if (spl_map(error).IsNull() || !spl_check_name(name_utf8, error))
119
		return AllocatedPath::Null();
120

121
	auto path_fs = map_spl_utf8_to_fs(name_utf8);
122
	if (path_fs.IsNull())
123
		error.Set(playlist_domain, int(PlaylistResult::BAD_NAME),
124
			  "Bad playlist name");
125 126 127 128

	return path_fs;
}

129 130 131 132 133 134 135 136 137 138 139 140 141
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
}

142
void
143 144 145 146 147 148 149 150 151
TranslatePlaylistError(Error &error)
{
	if (IsNotFoundError(error)) {
		error.Clear();
		error.Set(playlist_domain, int(PlaylistResult::NO_SUCH_LIST),
			  "No such playlist");
	}
}

152
/**
153
 * Create an #Error for the current errno.
154 155
 */
static void
156
playlist_errno(Error &error)
157 158 159
{
	switch (errno) {
	case ENOENT:
160
		error.Set(playlist_domain, int(PlaylistResult::NO_SUCH_LIST),
161
			  "No such playlist");
162 163 164
		break;

	default:
165
		error.SetErrno();
166 167 168 169
		break;
	}
}

170
static bool
171
LoadPlaylistFileInfo(PlaylistInfo &info,
172 173
		     const Path parent_path_fs,
		     const Path name_fs)
174
{
175 176 177
	if (name_fs.HasNewline())
		return false;

178
	const auto *const name_fs_str = name_fs.c_str();
179
	const auto *const name_fs_end =
180 181
		FindStringSuffix(name_fs_str,
				 PATH_LITERAL(PLAYLIST_FILE_SUFFIX));
182
	if (name_fs_end == nullptr)
183
		return false;
184

185
	FileInfo fi;
186 187
	if (!GetFileInfo(AllocatedPath::Build(parent_path_fs, name_fs), fi) ||
	    !fi.IsRegular())
188
		return false;
189

190
	PathTraitsFS::string name(name_fs_str, name_fs_end);
191
	std::string name_utf8 = PathToUTF8(name.c_str());
192
	if (name_utf8.empty())
193
		return false;
194

195
	info.name = std::move(name_utf8);
196
	info.mtime = fi.GetModificationTime();
197
	return true;
198 199
}

200
PlaylistVector
201
ListPlaylistFiles(Error &error)
202
{
203
	PlaylistVector list;
204

205
	const auto &parent_path_fs = spl_map(error);
206
	if (parent_path_fs.IsNull())
207
		return list;
208

209 210
	DirectoryReader reader(parent_path_fs);
	if (reader.HasFailed()) {
211
		error.SetErrno();
212
		return list;
213
	}
214

215
	PlaylistInfo info;
216
	while (reader.ReadEntry()) {
217
		const auto entry = reader.GetEntry();
218
		if (LoadPlaylistFileInfo(info, parent_path_fs, entry))
219
			list.push_back(std::move(info));
220 221 222 223 224
	}

	return list;
}

225
static bool
226
SavePlaylistFile(const PlaylistFileContents &contents, const char *utf8path,
227
		 Error &error)
228
{
229
	assert(utf8path != nullptr);
230

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

235 236 237
	FileOutputStream fos(path_fs, error);
	if (!fos.IsDefined()) {
		TranslatePlaylistError(error);
238 239
		return false;
	}
240

241 242
	BufferedOutputStream bos(fos);

243
	for (const auto &uri_utf8 : contents)
244
		playlist_print_uri(bos, uri_utf8.c_str());
245

246
	return bos.Flush(error) && fos.Commit(error);
247 248
}

249
PlaylistFileContents
250
LoadPlaylistFile(const char *utf8path, Error &error)
251
{
252 253
	PlaylistFileContents contents;

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 271 272 273 274 275 276 277
#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
278
		const Path path = Path::FromFS(s);
279
#endif
Max Kellermann's avatar
Max Kellermann committed
280

281 282
		std::string uri_utf8;

283
		if (!uri_has_scheme(s)) {
284
#ifdef ENABLE_DATABASE
Max Kellermann's avatar
Max Kellermann committed
285
			uri_utf8 = map_fs_to_utf8(path);
286
			if (uri_utf8.empty()) {
Max Kellermann's avatar
Max Kellermann committed
287
				if (path.IsAbsolute()) {
288
					uri_utf8 = path.ToUTF8();
289 290 291 292 293
					if (uri_utf8.empty())
						continue;
				} else
					continue;
			}
294 295 296
#else
			continue;
#endif
297
		} else {
Max Kellermann's avatar
Max Kellermann committed
298
			uri_utf8 = path.ToUTF8();
299
			if (uri_utf8.empty())
300 301
				continue;
		}
302

303
		contents.emplace_back(std::move(uri_utf8));
304
		if (contents.size() >= playlist_max_length)
305
			break;
306 307
	}

308
	return contents;
309 310
}

311 312
bool
spl_move_index(const char *utf8path, unsigned src, unsigned dest,
313
	       Error &error)
314
{
315 316 317
	if (src == dest)
		/* this doesn't check whether the playlist exists, but
		   what the hell.. */
318
		return true;
319

320 321
	auto contents = LoadPlaylistFile(utf8path, error);
	if (contents.empty() && error.IsDefined())
322
		return false;
323

324
	if (src >= contents.size() || dest >= contents.size()) {
325
		error.Set(playlist_domain, int(PlaylistResult::BAD_RANGE),
326
			  "Bad range");
327
		return false;
328 329
	}

330 331 332
	const auto src_i = std::next(contents.begin(), src);
	auto value = std::move(*src_i);
	contents.erase(src_i);
333

334 335
	const auto dest_i = std::next(contents.begin(), dest);
	contents.insert(dest_i, std::move(value));
336

337
	bool result = SavePlaylistFile(contents, utf8path, error);
338 339

	idle_add(IDLE_STORED_PLAYLIST);
340
	return result;
341 342
}

343
bool
344
spl_clear(const char *utf8path, Error &error)
345
{
346
	const auto path_fs = spl_map_to_fs(utf8path, error);
347
	if (path_fs.IsNull())
348
		return false;
349

350
	FILE *file = FOpen(path_fs, FOpenMode::WriteText);
351
	if (file == nullptr) {
352
		playlist_errno(error);
353 354
		return false;
	}
355

356
	fclose(file);
357 358

	idle_add(IDLE_STORED_PLAYLIST);
359
	return true;
360 361
}

362
bool
363
spl_delete(const char *name_utf8, Error &error)
364
{
365
	const auto path_fs = spl_map_to_fs(name_utf8, error);
366
	if (path_fs.IsNull())
367
		return false;
368

369
	if (!RemoveFile(path_fs)) {
370
		playlist_errno(error);
371 372
		return false;
	}
373

374
	idle_add(IDLE_STORED_PLAYLIST);
375
	return true;
376 377
}

378
bool
379
spl_remove_index(const char *utf8path, unsigned pos, Error &error)
380
{
381 382
	auto contents = LoadPlaylistFile(utf8path, error);
	if (contents.empty() && error.IsDefined())
383
		return false;
384

385
	if (pos >= contents.size()) {
386
		error.Set(playlist_domain, int(PlaylistResult::BAD_RANGE),
387
			  "Bad range");
388
		return false;
389 390
	}

391
	contents.erase(std::next(contents.begin(), pos));
392

393
	bool result = SavePlaylistFile(contents, utf8path, error);
394 395

	idle_add(IDLE_STORED_PLAYLIST);
396
	return result;
397 398
}

399
bool
400
spl_append_song(const char *utf8path, const DetachedSong &song, Error &error)
401
{
402
	const auto path_fs = spl_map_to_fs(utf8path, error);
403
	if (path_fs.IsNull())
404
		return false;
405

406 407 408
	AppendFileOutputStream fos(path_fs, error);
	if (!fos.IsDefined()) {
		TranslatePlaylistError(error);
409
		return false;
410
	}
411

412
	if (fos.Tell() / (MPD_PATH_MAX + 1) >= playlist_max_length) {
413
		error.Set(playlist_domain, int(PlaylistResult::TOO_LARGE),
414
			  "Stored playlist is too large");
415
		return false;
416
	}
417

418
	BufferedOutputStream bos(fos);
419

420 421 422 423
	playlist_print_song(bos, song);

	if (!bos.Flush(error) || !fos.Commit(error))
		return false;
424 425

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

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

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

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

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

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

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

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

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

479
	return spl_rename_internal(from_path_fs, to_path_fs, error);
480
}