PlaylistFile.cxx 10.1 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"
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/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 67 68 69 70 71 72 73 74 75 76 77
bool
spl_valid_name(const char *name_utf8)
{
	/*
	 * 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.
	 */

78 79 80
	return strchr(name_utf8, '/') == nullptr &&
		strchr(name_utf8, '\n') == nullptr &&
		strchr(name_utf8, '\r') == nullptr;
81 82
}

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

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

	return true;
}

105
static AllocatedPath
106
spl_map_to_fs(const char *name_utf8, Error &error)
107
{
108
	if (spl_map(error).IsNull() || !spl_check_name(name_utf8, error))
109
		return AllocatedPath::Null();
110

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

	return path_fs;
}

/**
120
 * Create an #Error for the current errno.
121 122
 */
static void
123
playlist_errno(Error &error)
124 125 126
{
	switch (errno) {
	case ENOENT:
127
		error.Set(playlist_domain, int(PlaylistResult::NO_SUCH_LIST),
128
			  "No such playlist");
129 130 131
		break;

	default:
132
		error.SetErrno();
133 134 135 136
		break;
	}
}

137
static bool
138
LoadPlaylistFileInfo(PlaylistInfo &info,
139 140
		     const Path parent_path_fs,
		     const Path name_fs)
141
{
142 143
	const char *name_fs_str = name_fs.c_str();
	size_t name_length = strlen(name_fs_str);
144

145
	if (name_length < sizeof(PLAYLIST_FILE_SUFFIX) ||
146
	    memchr(name_fs_str, '\n', name_length) != nullptr)
147
		return false;
148

149
	if (!StringEndsWith(name_fs_str, PLAYLIST_FILE_SUFFIX))
150
		return false;
151

152
	const auto path_fs = AllocatedPath::Build(parent_path_fs, name_fs);
153
	struct stat st;
154
	if (!StatFile(path_fs, st) || !S_ISREG(st.st_mode))
155
		return false;
156

157 158 159
	std::string name(name_fs_str,
			 name_length + 1 - sizeof(PLAYLIST_FILE_SUFFIX));
	std::string name_utf8 = PathToUTF8(name.c_str());
160
	if (name_utf8.empty())
161
		return false;
162

163
	info.name = std::move(name_utf8);
164 165
	info.mtime = st.st_mtime;
	return true;
166 167
}

168
PlaylistVector
169
ListPlaylistFiles(Error &error)
170
{
171
	PlaylistVector list;
172

173
	const auto &parent_path_fs = spl_map(error);
174
	if (parent_path_fs.IsNull())
175
		return list;
176

177 178
	DirectoryReader reader(parent_path_fs);
	if (reader.HasFailed()) {
179
		error.SetErrno();
180
		return list;
181
	}
182

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

	return list;
}

193
static bool
194
SavePlaylistFile(const PlaylistFileContents &contents, const char *utf8path,
195
		 Error &error)
196
{
197
	assert(utf8path != nullptr);
198

199
	if (spl_map(error).IsNull())
200
		return false;
201

202
	const auto path_fs = spl_map_to_fs(utf8path, error);
203
	if (path_fs.IsNull())
204
		return false;
205

206
	FILE *file = FOpen(path_fs, FOpenMode::WriteText);
207
	if (file == nullptr) {
208
		playlist_errno(error);
209 210
		return false;
	}
211

212 213
	for (const auto &uri_utf8 : contents)
		playlist_print_uri(file, uri_utf8.c_str());
214

215
	fclose(file);
216
	return true;
217 218
}

219
PlaylistFileContents
220
LoadPlaylistFile(const char *utf8path, Error &error)
221
{
222 223
	PlaylistFileContents contents;

224
	if (spl_map(error).IsNull())
225
		return contents;
226

227
	const auto path_fs = spl_map_to_fs(utf8path, error);
228
	if (path_fs.IsNull())
229
		return contents;
230

231 232
	TextFile file(path_fs);
	if (file.HasFailed()) {
233
		playlist_errno(error);
234
		return contents;
235
	}
236

237
	char *s;
238
	while ((s = file.ReadLine()) != nullptr) {
239
		if (*s == 0 || *s == PLAYLIST_COMMENT)
240
			continue;
241

242 243
		std::string uri_utf8;

244
		if (!uri_has_scheme(s)) {
245
#ifdef ENABLE_DATABASE
246
			uri_utf8 = map_fs_to_utf8(s);
247
			if (uri_utf8.empty()) {
248
				if (PathTraitsFS::IsAbsolute(s)) {
249
					uri_utf8 = PathToUTF8(s);
250 251 252 253 254 255 256
					if (uri_utf8.empty())
						continue;

					uri_utf8.insert(0, "file://");
				} else
					continue;
			}
257 258 259
#else
			continue;
#endif
260
		} else {
261
			uri_utf8 = PathToUTF8(s);
262
			if (uri_utf8.empty())
263 264
				continue;
		}
265

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

271
	return contents;
272 273
}

274 275
bool
spl_move_index(const char *utf8path, unsigned src, unsigned dest,
276
	       Error &error)
277
{
278 279 280
	if (src == dest)
		/* this doesn't check whether the playlist exists, but
		   what the hell.. */
281
		return true;
282

283 284
	auto contents = LoadPlaylistFile(utf8path, error);
	if (contents.empty() && error.IsDefined())
285
		return false;
286

287
	if (src >= contents.size() || dest >= contents.size()) {
288
		error.Set(playlist_domain, int(PlaylistResult::BAD_RANGE),
289
			  "Bad range");
290
		return false;
291 292
	}

293 294 295
	const auto src_i = std::next(contents.begin(), src);
	auto value = std::move(*src_i);
	contents.erase(src_i);
296

297 298
	const auto dest_i = std::next(contents.begin(), dest);
	contents.insert(dest_i, std::move(value));
299

300
	bool result = SavePlaylistFile(contents, utf8path, error);
301 302

	idle_add(IDLE_STORED_PLAYLIST);
303
	return result;
304 305
}

306
bool
307
spl_clear(const char *utf8path, Error &error)
308
{
309
	if (spl_map(error).IsNull())
310
		return false;
311

312
	const auto path_fs = spl_map_to_fs(utf8path, error);
313
	if (path_fs.IsNull())
314
		return false;
315

316
	FILE *file = FOpen(path_fs, FOpenMode::WriteText);
317
	if (file == nullptr) {
318
		playlist_errno(error);
319 320
		return false;
	}
321

322
	fclose(file);
323 324

	idle_add(IDLE_STORED_PLAYLIST);
325
	return true;
326 327
}

328
bool
329
spl_delete(const char *name_utf8, Error &error)
330
{
331
	const auto path_fs = spl_map_to_fs(name_utf8, error);
332
	if (path_fs.IsNull())
333
		return false;
334

335
	if (!RemoveFile(path_fs)) {
336
		playlist_errno(error);
337 338
		return false;
	}
339

340
	idle_add(IDLE_STORED_PLAYLIST);
341
	return true;
342 343
}

344
bool
345
spl_remove_index(const char *utf8path, unsigned pos, Error &error)
346
{
347 348
	auto contents = LoadPlaylistFile(utf8path, error);
	if (contents.empty() && error.IsDefined())
349
		return false;
350

351
	if (pos >= contents.size()) {
352
		error.Set(playlist_domain, int(PlaylistResult::BAD_RANGE),
353
			  "Bad range");
354
		return false;
355 356
	}

357
	contents.erase(std::next(contents.begin(), pos));
358

359
	bool result = SavePlaylistFile(contents, utf8path, error);
360 361

	idle_add(IDLE_STORED_PLAYLIST);
362
	return result;
363 364
}

365
bool
366
spl_append_song(const char *utf8path, const DetachedSong &song, Error &error)
367
{
368
	if (spl_map(error).IsNull())
369
		return false;
370

371
	const auto path_fs = spl_map_to_fs(utf8path, error);
372
	if (path_fs.IsNull())
373
		return false;
374

375
	FILE *file = FOpen(path_fs, FOpenMode::AppendText);
376
	if (file == nullptr) {
377
		playlist_errno(error);
378 379
		return false;
	}
380

381
	struct stat st;
382
	if (fstat(fileno(file), &st) < 0) {
383
		playlist_errno(error);
384
		fclose(file);
385
		return false;
386
	}
387

388
	if (st.st_size / off_t(MPD_PATH_MAX + 1) >= (off_t)playlist_max_length) {
389
		fclose(file);
390
		error.Set(playlist_domain, int(PlaylistResult::TOO_LARGE),
391
			  "Stored playlist is too large");
392
		return false;
393
	}
394

395
	playlist_print_song(file, song);
396

397
	fclose(file);
398 399

	idle_add(IDLE_STORED_PLAYLIST);
400
	return true;
401 402
}

403
bool
404 405 406
spl_append_uri(const char *utf8file,
	       const SongLoader &loader, const char *url,
	       Error &error)
407
{
408 409
	DetachedSong *song = loader.LoadSong(url, error);
	if (song == nullptr)
410
		return false;
411 412 413 414

	bool success = spl_append_song(utf8file, *song, error);
	delete song;
	return success;
415 416
}

417
static bool
418
spl_rename_internal(Path from_path_fs, Path to_path_fs,
419
		    Error &error)
420
{
421
	if (!FileExists(from_path_fs)) {
422
		error.Set(playlist_domain, int(PlaylistResult::NO_SUCH_LIST),
423
			  "No such playlist");
424 425
		return false;
	}
426

427
	if (FileExists(to_path_fs)) {
428
		error.Set(playlist_domain, int(PlaylistResult::LIST_EXISTS),
429
			  "Playlist exists already");
430 431
		return false;
	}
432

433
	if (!RenameFile(from_path_fs, to_path_fs)) {
434
		playlist_errno(error);
435 436
		return false;
	}
437

438
	idle_add(IDLE_STORED_PLAYLIST);
439
	return true;
440
}
441

442
bool
443
spl_rename(const char *utf8from, const char *utf8to, Error &error)
444
{
445
	if (spl_map(error).IsNull())
446
		return false;
447

448
	const auto from_path_fs = spl_map_to_fs(utf8from, error);
449
	if (from_path_fs.IsNull())
450
		return false;
451

452
	const auto to_path_fs = spl_map_to_fs(utf8to, error);
453
	if (to_path_fs.IsNull())
454
		return false;
455

456
	return spl_rename_internal(from_path_fs, to_path_fs, error);
457
}