-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathmpd_client.cc
483 lines (414 loc) · 15.1 KB
/
mpd_client.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
#include "mpd_client.h"
#include <iostream>
#include <absl/strings/str_format.h>
#include <absl/strings/str_join.h>
#include <mpd/capabilities.h>
#include <mpd/connection.h>
#include <mpd/database.h>
#include <mpd/error.h>
#include <mpd/idle.h>
#include <mpd/pair.h>
#include <mpd/password.h>
#include <mpd/player.h>
#include <mpd/protocol.h>
#include <mpd/queue.h>
#include <mpd/recv.h>
#include <mpd/search.h>
#include <mpd/song.h>
#include <mpd/status.h>
#include "log.h"
#include "mpd.h"
#include "util.h"
namespace ashuffle {
namespace mpd {
namespace client {
namespace {
using Authorization = mpd::MPD::Authorization;
class TagParserImpl : public TagParser {
public:
// Parse parses the given tag, and returns the appropriate tag type.
// If no matching tag is found, then an empty optional is returned.
std::optional<enum mpd_tag_type> Parse(
const std::string_view tag) const override;
};
std::optional<enum mpd_tag_type> TagParserImpl::Parse(
const std::string_view tag_name) const {
std::string name_with_null(tag_name);
enum mpd_tag_type tag = mpd_tag_name_iparse(name_with_null.data());
if (tag == MPD_TAG_UNKNOWN) {
return std::nullopt;
}
return tag;
}
class SongImpl : public Song {
public:
// Create a new song based on the given mpd_song.
SongImpl(struct mpd_song* song) : song_(song){};
// Song is pointer owning. We do not support copies.
SongImpl(Song&) = delete;
SongImpl& operator=(SongImpl&) = delete;
// However, moves are OK, because the "old" owner no longer exists.
SongImpl(SongImpl&&) = default;
// Free the wrapped struct mpd_song;
~SongImpl() override;
std::optional<std::string> Tag(enum mpd_tag_type tag) const override;
std::string URI() const override;
private:
// The wrapped song.
struct mpd_song* song_;
};
SongImpl::~SongImpl() { mpd_song_free(song_); }
std::optional<std::string> SongImpl::Tag(enum mpd_tag_type tag) const {
const char* raw_value = mpd_song_get_tag(song_, tag, 0);
if (raw_value == nullptr) {
return std::nullopt;
}
return std::string(raw_value);
}
std::string SongImpl::URI() const { return mpd_song_get_uri(song_); }
class StatusImpl : public Status {
public:
// Wrap the given mpd_status.
StatusImpl(struct mpd_status* status) : status_(status){};
// StatusImpl is pointer owning. We do not support copies.
StatusImpl(StatusImpl&) = delete;
StatusImpl& operator=(StatusImpl&) = delete;
// Moves are OK, because the "old" owner no longer exists.
StatusImpl(StatusImpl&&) = default;
StatusImpl& operator=(StatusImpl&&) = default;
// Free the wrapped status.
~StatusImpl() override;
unsigned QueueLength() const override;
bool Single() const override;
std::optional<int> SongPosition() const override;
bool IsPlaying() const override;
private:
struct mpd_status* status_;
};
StatusImpl::~StatusImpl() { mpd_status_free(status_); }
unsigned StatusImpl::QueueLength() const {
return mpd_status_get_queue_length(status_);
}
bool StatusImpl::Single() const { return mpd_status_get_single(status_); }
std::optional<int> StatusImpl::SongPosition() const {
int pos = mpd_status_get_song_pos(status_);
if (pos == -1) {
return std::nullopt;
}
return pos;
}
bool StatusImpl::IsPlaying() const {
return mpd_status_get_state(status_) == MPD_STATE_PLAY;
}
// Forward declare SongReaderImpl for MPDImpl;
class SongReaderImpl;
class MPDImpl : public MPD {
public:
MPDImpl(struct mpd_connection* conn) : mpd_(conn){};
// MPDImpl owns the connection pointer, no copies possible.
MPDImpl(MPDImpl&) = delete;
MPDImpl& operator=(MPDImpl&) = delete;
MPDImpl(MPDImpl&&) = default;
MPDImpl& operator=(MPDImpl&&) = default;
~MPDImpl() override;
absl::Status Pause() override;
absl::Status Play() override;
absl::Status PlayAt(unsigned position) override;
absl::StatusOr<std::unique_ptr<Status>> CurrentStatus() override;
absl::StatusOr<std::unique_ptr<SongReader>> ListAll(
MetadataOption metadata) override;
absl::StatusOr<std::unique_ptr<Song>> Search(std::string_view uri) override;
absl::StatusOr<IdleEventSet> Idle(const IdleEventSet&) override;
absl::Status Add(const std::string& uri) override;
absl::StatusOr<MPD::PasswordStatus> ApplyPassword(
const std::string& password) override;
absl::StatusOr<Authorization> CheckCommands(
const std::vector<std::string_view>& cmds) override;
private:
friend SongReaderImpl;
struct mpd_connection* mpd_;
// Returns the current status of the MPD connection as a status.
absl::Status ConnectionStatus();
};
class SongReaderImpl : public SongReader {
public:
SongReaderImpl(MPDImpl& mpd) : mpd_(mpd), song_(std::nullopt){};
// SongReaderImpl is also pointer owning (the pointer to the next song_).
SongReaderImpl(SongReaderImpl&) = delete;
SongReaderImpl& operator=(SongReaderImpl&) = delete;
// As with the other types, moves are OK.
SongReaderImpl(SongReaderImpl&&) = default;
// Default destructor should work fine, since the std::optional owns
// a unique_ptr to an actual Song. The generated destructor will destruct
// that type correctly.
~SongReaderImpl() override = default;
absl::StatusOr<std::unique_ptr<Song>> Next() override;
bool Done() override;
private:
// Fetch the next song, and if there is a song store it in song_. If a song
// has already been fetched (even if no song was returned), take no action.
void FetchNext();
MPDImpl& mpd_;
std::optional<std::unique_ptr<Song>> song_;
};
void SongReaderImpl::FetchNext() {
if (song_) {
return;
}
struct mpd_song* raw_song = mpd_recv_song(mpd_.mpd_);
// Some special error handling for common errors encountered during
// the song reader process.
const enum mpd_error err = mpd_connection_get_error(mpd_.mpd_);
if (err == MPD_ERROR_CLOSED) {
Log().ErrorStr(absl::StrJoin(
{
"MPD server closed the connection while getting the list of",
"all songs. If MPD error logs say \"Output buffer is full\",",
"consider setting max_output_buffer_size to a higher value",
"(e.g. 32768) in your MPD config.",
},
"\n"));
}
if (err == MPD_ERROR_MALFORMED) {
Log().ErrorStr(absl::StrJoin(
{
"libmpdclient received a malformed response from the server.",
"This may be because a song's metadata attribute (for example,",
"a comment) was longer than 4KiB.",
"See https://github.com/joshkunz/ashuffle/issues/89 for",
"details or updates.",
},
"\n"));
}
if (!mpd_.ConnectionStatus().ok()) {
song_ = std::nullopt;
return;
}
if (raw_song == nullptr) {
song_ = std::nullopt;
return;
}
song_ = std::unique_ptr<Song>(new SongImpl(raw_song));
}
absl::StatusOr<std::unique_ptr<Song>> SongReaderImpl::Next() {
FetchNext();
// If an error occured on fetch, then return it.
if (auto status = mpd_.ConnectionStatus(); !status.ok()) {
return status;
}
if (!song_.has_value()) {
return absl::OutOfRangeError("song reader done");
}
// Moving out of an optional will re-set it to null.
auto out = std::move(song_.value());
song_.reset();
return out;
}
bool SongReaderImpl::Done() {
FetchNext();
return !song_.has_value();
}
MPDImpl::~MPDImpl() { mpd_connection_free(mpd_); }
absl::Status MPDImpl::ConnectionStatus() {
enum mpd_error mpd_status = mpd_connection_get_error(mpd_);
if (mpd_status == MPD_ERROR_SUCCESS) {
return absl::OkStatus();
}
if (mpd_status == MPD_ERROR_SERVER) {
enum mpd_server_error mpd_code = mpd_connection_get_server_error(mpd_);
absl::StatusCode code;
switch (mpd_code) {
case MPD_SERVER_ERROR_PASSWORD:
case MPD_SERVER_ERROR_PERMISSION:
code = absl::StatusCode::kPermissionDenied;
break;
case MPD_SERVER_ERROR_NO_EXIST:
code = absl::StatusCode::kNotFound;
break;
case MPD_SERVER_ERROR_SYSTEM:
code = absl::StatusCode::kInternal;
break;
default:
code = absl::StatusCode::kUnknown;
}
return absl::Status(
code, absl::StrFormat("MPD Server error (%d): %s", mpd_code,
mpd_connection_get_error_message(mpd_)));
}
// It should be a non-server error.
absl::StatusCode code;
switch (mpd_status) {
case MPD_ERROR_CLOSED:
code = absl::StatusCode::kUnavailable;
break;
case MPD_ERROR_TIMEOUT:
code = absl::StatusCode::kDeadlineExceeded;
break;
default:
code = absl::StatusCode::kInternal;
}
return absl::Status(
code, absl::StrFormat("MPD Error (%d): %s", mpd_status,
mpd_connection_get_error_message(mpd_)));
}
absl::Status MPDImpl::Pause() {
mpd_run_pause(mpd_, true);
return ConnectionStatus();
}
absl::Status MPDImpl::Play() {
mpd_run_pause(mpd_, false);
return ConnectionStatus();
}
absl::Status MPDImpl::PlayAt(unsigned position) {
mpd_run_play_pos(mpd_, position);
return ConnectionStatus();
}
absl::StatusOr<std::unique_ptr<SongReader>> MPDImpl::ListAll(
MPD::MetadataOption metadata) {
switch (metadata) {
case MPD::MetadataOption::kInclude:
if (!mpd_send_list_all_meta(mpd_, NULL)) {
return ConnectionStatus();
}
break;
case MPD::MetadataOption::kOmit:
if (!mpd_send_list_all(mpd_, NULL)) {
return ConnectionStatus();
}
break;
}
return std::unique_ptr<SongReader>(new SongReaderImpl(*this));
}
absl::StatusOr<std::unique_ptr<Song>> MPDImpl::Search(std::string_view uri) {
// Copy to ensure URI buffer is null-terminated.
std::string uri_copy(uri);
mpd_search_db_songs(mpd_, true);
mpd_search_add_uri_constraint(mpd_, MPD_OPERATOR_DEFAULT, uri_copy.data());
if (!mpd_search_commit(mpd_)) {
return ConnectionStatus();
}
struct mpd_song* raw_song = mpd_recv_song(mpd_);
if (auto status = ConnectionStatus(); !status.ok()) {
return status;
}
if (raw_song == nullptr) {
return absl::NotFoundError(absl::StrFormat("uri %s not found", uri));
}
std::unique_ptr<Song> song = std::unique_ptr<Song>(new SongImpl(raw_song));
/* even though we're searching for a single song, libmpdclient
* still acts like we're reading a song list. We read an aditional
* element to convince MPD this is the end of the song list. */
raw_song = mpd_recv_song(mpd_);
assert(raw_song == nullptr &&
"search by URI should only ever find one song");
return std::unique_ptr<Song>(std::move(song));
}
absl::StatusOr<IdleEventSet> MPDImpl::Idle(const IdleEventSet& events) {
enum mpd_idle occured = mpd_run_idle_mask(mpd_, events.Enum());
if (auto status = ConnectionStatus(); !status.ok()) {
return status;
}
return {static_cast<int>(occured)};
}
absl::Status MPDImpl::Add(const std::string& uri) {
mpd_run_add(mpd_, uri.data());
return ConnectionStatus();
}
absl::StatusOr<std::unique_ptr<Status>> MPDImpl::CurrentStatus() {
struct mpd_status* status = mpd_run_status(mpd_);
if (status == nullptr) {
return ConnectionStatus();
}
return std::unique_ptr<Status>(new StatusImpl(status));
}
absl::StatusOr<MPD::PasswordStatus> MPDImpl::ApplyPassword(
const std::string& password) {
mpd_run_password(mpd_, password.data());
const enum mpd_error err = mpd_connection_get_error(mpd_);
if (err == MPD_ERROR_SUCCESS) {
return MPD::PasswordStatus::kAccepted;
}
if (err != MPD_ERROR_SERVER) {
return ConnectionStatus();
}
enum mpd_server_error serr = mpd_connection_get_server_error(mpd_);
if (serr != MPD_SERVER_ERROR_PASSWORD) {
return ConnectionStatus();
}
mpd_connection_clear_error(mpd_);
return MPD::PasswordStatus::kRejected;
}
absl::StatusOr<Authorization> MPDImpl::CheckCommands(
const std::vector<std::string_view>& cmds) {
Authorization result;
if (cmds.size() < 1) {
// Empty command list is always allowed, and we don't need a round
// trip to the server.
result.authorized = true;
return result;
}
// Fetch a list of the commands we're not allowed to run. In most
// installs, this should be empty.
if (!mpd_send_disallowed_commands(mpd_)) {
if (auto status = ConnectionStatus(); !status.ok()) {
return status;
}
}
std::vector<std::string> disallowed;
struct mpd_pair* command_pair = mpd_recv_command_pair(mpd_);
while (command_pair != nullptr) {
disallowed.push_back(command_pair->value);
mpd_return_pair(mpd_, command_pair);
command_pair = mpd_recv_command_pair(mpd_);
}
if (auto status = ConnectionStatus(); !status.ok()) {
return status;
}
for (std::string_view cmd : cmds) {
if (std::find(disallowed.begin(), disallowed.end(), cmd) !=
disallowed.end()) {
result.missing.emplace_back(cmd);
}
}
// We're authorized as long as we are not missing any required commands.
result.authorized = result.missing.size() == 0;
return result;
}
class DialerImpl : public Dialer {
public:
~DialerImpl() override = default;
// Dial connects to the MPD instance at the given Address, optionally,
// with the given timeout. On success a variant with a unique_ptr to
// an MPD instance is returned. On failure, a string is returned with
// a human-readable description of the error.
absl::StatusOr<std::unique_ptr<MPD>> Dial(
const Address&,
absl::Duration timeout = Dialer::kDefaultTimeout) const override;
};
absl::StatusOr<std::unique_ptr<MPD>> DialerImpl::Dial(
const Address& addr, absl::Duration timeout) const {
unsigned timeout_ms =
static_cast<unsigned>(absl::ToInt64Milliseconds(timeout));
/* Create a new connection to mpd */
struct mpd_connection* mpd =
mpd_connection_new(addr.host.data(), addr.port, timeout_ms);
if (mpd == nullptr) {
return absl::ResourceExhaustedError("out of memory");
}
if (mpd_connection_get_error(mpd) != MPD_ERROR_SUCCESS) {
return absl::UnavailableError(
absl::StrFormat("could not connect to mpd at %s:%u: %s", addr.host,
addr.port, mpd_connection_get_error_message(mpd)));
}
return std::unique_ptr<MPD>(new MPDImpl(mpd));
}
} // namespace
std::unique_ptr<mpd::TagParser> Parser() {
return std::unique_ptr<mpd::TagParser>(new TagParserImpl());
}
std::unique_ptr<mpd::Dialer> Dialer() {
return std::unique_ptr<mpd::Dialer>(new DialerImpl());
}
} // namespace client
} // namespace mpd
} // namespace ashuffle