diff options
Diffstat (limited to '')
29 files changed, 3483 insertions, 137 deletions
diff --git a/src/db/LazyDatabase.cxx b/src/db/LazyDatabase.cxx new file mode 100644 index 000000000..6a01ffb82 --- /dev/null +++ b/src/db/LazyDatabase.cxx @@ -0,0 +1,103 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * http://www.musicpd.org + * + * 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. + * + * 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. + */ + +#include "config.h" +#include "LazyDatabase.hxx" + +#include <assert.h> + +LazyDatabase::~LazyDatabase() +{ + assert(!open); + + delete db; +} + +bool +LazyDatabase::EnsureOpen(Error &error) const +{ + if (open) + return true; + + if (!db->Open(error)) + return false; + + open = true; + return true; +} + +void +LazyDatabase::Close() +{ + if (open) { + open = false; + db->Close(); + } +} + +const LightSong * +LazyDatabase::GetSong(const char *uri, Error &error) const +{ + return EnsureOpen(error) + ? db->GetSong(uri, error) + : nullptr; +} + +void +LazyDatabase::ReturnSong(const LightSong *song) const +{ + assert(open); + + db->ReturnSong(song); +} + +bool +LazyDatabase::Visit(const DatabaseSelection &selection, + VisitDirectory visit_directory, + VisitSong visit_song, + VisitPlaylist visit_playlist, + Error &error) const +{ + return EnsureOpen(error) && + db->Visit(selection, visit_directory, visit_song, + visit_playlist, error); +} + +bool +LazyDatabase::VisitUniqueTags(const DatabaseSelection &selection, + TagType tag_type, + VisitString visit_string, + Error &error) const +{ + return EnsureOpen(error) && + db->VisitUniqueTags(selection, tag_type, visit_string, error); +} + +bool +LazyDatabase::GetStats(const DatabaseSelection &selection, + DatabaseStats &stats, Error &error) const +{ + return EnsureOpen(error) && db->GetStats(selection, stats, error); +} + +time_t +LazyDatabase::GetUpdateStamp() const +{ + return open ? db->GetUpdateStamp() : 0; +} diff --git a/src/db/LazyDatabase.hxx b/src/db/LazyDatabase.hxx new file mode 100644 index 000000000..f718ecb3f --- /dev/null +++ b/src/db/LazyDatabase.hxx @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * http://www.musicpd.org + * + * 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. + * + * 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. + */ + +#ifndef MPD_LAZY_DATABASE_PLUGIN_HXX +#define MPD_LAZY_DATABASE_PLUGIN_HXX + +#include "DatabasePlugin.hxx" + +/** + * A wrapper for a #Database object that gets opened on the first + * database access. This works around daemonization problems with + * some plugins. + */ +class LazyDatabase final : public Database { + Database *const db; + + mutable bool open; + +public: + gcc_nonnull_all + LazyDatabase(Database *_db) + :db(_db), open(false) {} + + virtual ~LazyDatabase(); + + virtual void Close() override; + + virtual const LightSong *GetSong(const char *uri_utf8, + Error &error) const override; + virtual void ReturnSong(const LightSong *song) const; + + virtual bool Visit(const DatabaseSelection &selection, + VisitDirectory visit_directory, + VisitSong visit_song, + VisitPlaylist visit_playlist, + Error &error) const override; + + virtual bool VisitUniqueTags(const DatabaseSelection &selection, + TagType tag_type, + VisitString visit_string, + Error &error) const override; + + virtual bool GetStats(const DatabaseSelection &selection, + DatabaseStats &stats, + Error &error) const override; + + virtual time_t GetUpdateStamp() const override; + +private: + bool EnsureOpen(Error &error) const; +}; + +#endif diff --git a/src/db/ProxyDatabasePlugin.cxx b/src/db/ProxyDatabasePlugin.cxx index 00b5d445f..f65e4f3d0 100644 --- a/src/db/ProxyDatabasePlugin.cxx +++ b/src/db/ProxyDatabasePlugin.cxx @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2013 The Music Player Daemon Project + * Copyright (C) 2003-2014 The Music Player Daemon Project * http://www.musicpd.org * * This program is free software; you can redistribute it and/or modify @@ -20,26 +20,53 @@ #include "config.h" #include "ProxyDatabasePlugin.hxx" #include "DatabasePlugin.hxx" +#include "DatabaseListener.hxx" #include "DatabaseSelection.hxx" #include "DatabaseError.hxx" -#include "PlaylistVector.hxx" #include "Directory.hxx" -#include "Song.hxx" +#include "LightSong.hxx" #include "SongFilter.hxx" #include "Compiler.h" #include "ConfigData.hxx" #include "tag/TagBuilder.hxx" +#include "tag/Tag.hxx" #include "util/Error.hxx" #include "util/Domain.hxx" #include "protocol/Ack.hxx" +#include "Main.hxx" +#include "event/SocketMonitor.hxx" +#include "event/IdleMonitor.hxx" +#include "Log.hxx" #include <mpd/client.h> +#include <mpd/async.h> #include <cassert> #include <string> #include <list> -class ProxyDatabase : public Database { +class ProxySong : public LightSong { + Tag tag2; + +public: + explicit ProxySong(const mpd_song *song); +}; + +class AllocatedProxySong : public ProxySong { + mpd_song *const song; + +public: + explicit AllocatedProxySong(mpd_song *_song) + :ProxySong(_song), song(_song) {} + + ~AllocatedProxySong() { + mpd_song_free(song); + } +}; + +class ProxyDatabase final : public Database, SocketMonitor, IdleMonitor { + DatabaseListener &listener; + std::string host; unsigned port; @@ -49,15 +76,32 @@ class ProxyDatabase : public Database { /* this is mutable because GetStats() must be "const" */ mutable time_t update_stamp; + /** + * The libmpdclient idle mask that was removed from the other + * MPD. This will be handled by the next OnIdle() call. + */ + unsigned idle_received; + + /** + * Is the #connection currently "idle"? That is, did we send + * the "idle" command to it? + */ + bool is_idle; + public: - static Database *Create(const config_param ¶m, + ProxyDatabase(EventLoop &_loop, DatabaseListener &_listener) + :SocketMonitor(_loop), IdleMonitor(_loop), + listener(_listener) {} + + static Database *Create(EventLoop &loop, DatabaseListener &listener, + const config_param ¶m, Error &error); virtual bool Open(Error &error) override; virtual void Close() override; - virtual Song *GetSong(const char *uri_utf8, + virtual const LightSong *GetSong(const char *uri_utf8, Error &error) const override; - virtual void ReturnSong(Song *song) const; + virtual void ReturnSong(const LightSong *song) const; virtual bool Visit(const DatabaseSelection &selection, VisitDirectory visit_directory, @@ -84,6 +128,14 @@ private: bool Connect(Error &error); bool CheckConnection(Error &error); bool EnsureConnected(Error &error); + + void Disconnect(); + + /* virtual methods from SocketMonitor */ + virtual bool OnSocketReady(unsigned flags) override; + + /* virtual methods from IdleMonitor */ + virtual void OnIdle() override; }; static constexpr Domain libmpdclient_domain("libmpdclient"); @@ -112,6 +164,38 @@ static constexpr struct { { TAG_NUM_OF_ITEM_TYPES, MPD_TAG_COUNT } }; +static void +Copy(TagBuilder &tag, TagType d_tag, + const struct mpd_song *song, enum mpd_tag_type s_tag) +{ + + for (unsigned i = 0;; ++i) { + const char *value = mpd_song_get_tag(song, s_tag, i); + if (value == nullptr) + break; + + tag.AddItem(d_tag, value); + } +} + +ProxySong::ProxySong(const mpd_song *song) +{ + directory = nullptr; + uri = mpd_song_get_uri(song); + tag = &tag2; + mtime = mpd_song_get_last_modified(song); + start_ms = mpd_song_get_start(song) * 1000; + end_ms = mpd_song_get_end(song) * 1000; + + TagBuilder tag_builder; + tag_builder.SetTime(mpd_song_get_duration(song)); + + for (const auto *i = &tag_table[0]; i->d != TAG_NUM_OF_ITEM_TYPES; ++i) + Copy(tag_builder, i->d, song, i->s); + + tag_builder.Commit(tag2); +} + gcc_const static enum mpd_tag_type Convert(TagType tag_type) @@ -217,9 +301,10 @@ SendConstraints(mpd_connection *connection, const DatabaseSelection &selection) } Database * -ProxyDatabase::Create(const config_param ¶m, Error &error) +ProxyDatabase::Create(EventLoop &loop, DatabaseListener &listener, + const config_param ¶m, Error &error) { - ProxyDatabase *db = new ProxyDatabase(); + ProxyDatabase *db = new ProxyDatabase(loop, listener); if (!db->Configure(param, error)) { delete db; db = nullptr; @@ -252,10 +337,10 @@ ProxyDatabase::Open(Error &error) void ProxyDatabase::Close() { - root->Free(); + delete root; if (connection != nullptr) - mpd_connection_free(connection); + Disconnect(); } bool @@ -269,11 +354,15 @@ ProxyDatabase::Connect(Error &error) return false; } + idle_received = unsigned(-1); + is_idle = false; + + SocketMonitor::Open(mpd_async_get_fd(mpd_connection_get_async(connection))); + IdleMonitor::Schedule(); + if (!CheckError(connection, error)) { - if (connection != nullptr) { - mpd_connection_free(connection); - connection = nullptr; - } + if (connection != nullptr) + Disconnect(); return false; } @@ -287,10 +376,22 @@ ProxyDatabase::CheckConnection(Error &error) assert(connection != nullptr); if (!mpd_connection_clear_error(connection)) { - mpd_connection_free(connection); + Disconnect(); return Connect(error); } + if (is_idle) { + unsigned idle = mpd_run_noidle(connection); + if (idle == 0 && !CheckError(connection, error)) { + Disconnect(); + return false; + } + + idle_received |= idle; + is_idle = false; + IdleMonitor::Schedule(); + } + return true; } @@ -302,10 +403,80 @@ ProxyDatabase::EnsureConnected(Error &error) : Connect(error); } -static Song * -Convert(const struct mpd_song *song); +void +ProxyDatabase::Disconnect() +{ + assert(connection != nullptr); + + IdleMonitor::Cancel(); + SocketMonitor::Steal(); + + mpd_connection_free(connection); + connection = nullptr; +} + +bool +ProxyDatabase::OnSocketReady(gcc_unused unsigned flags) +{ + assert(connection != nullptr); -Song * + if (!is_idle) { + // TODO: can this happen? + IdleMonitor::Schedule(); + return false; + } + + unsigned idle = (unsigned)mpd_recv_idle(connection, false); + if (idle == 0) { + Error error; + if (!CheckError(connection, error)) { + LogError(error); + Disconnect(); + return false; + } + } + + /* let OnIdle() handle this */ + idle_received |= idle; + is_idle = false; + IdleMonitor::Schedule(); + return false; +} + +void +ProxyDatabase::OnIdle() +{ + assert(connection != nullptr); + + /* handle previous idle events */ + + if (idle_received & MPD_IDLE_DATABASE) + listener.OnDatabaseModified(); + + idle_received = 0; + + /* send a new idle command to the other MPD */ + + if (is_idle) + // TODO: can this happen? + return; + + if (!mpd_send_idle_mask(connection, MPD_IDLE_DATABASE)) { + Error error; + if (!CheckError(connection, error)) + LogError(error); + + SocketMonitor::Steal(); + mpd_connection_free(connection); + connection = nullptr; + return; + } + + is_idle = true; + SocketMonitor::ScheduleRead(); +} + +const LightSong * ProxyDatabase::GetSong(const char *uri, Error &error) const { // TODO: eliminate the const_cast @@ -318,43 +489,39 @@ ProxyDatabase::GetSong(const char *uri, Error &error) const } struct mpd_song *song = mpd_recv_song(connection); - Song *song2 = song != nullptr - ? Convert(song) - : nullptr; - if (song != nullptr) - mpd_song_free(song); - if (!mpd_response_finish(connection)) { - if (song2 != nullptr) - song2->Free(); - - CheckError(connection, error); + if (!mpd_response_finish(connection) && + !CheckError(connection, error)) { + if (song != nullptr) + mpd_song_free(song); return nullptr; } - if (song2 == nullptr) + if (song == nullptr) { error.Format(db_domain, DB_NOT_FOUND, "No such song: %s", uri); + return nullptr; + } - return song2; + return new AllocatedProxySong(song); } void -ProxyDatabase::ReturnSong(Song *song) const +ProxyDatabase::ReturnSong(const LightSong *_song) const { - assert(song != nullptr); - assert(song->IsInDatabase()); - assert(song->IsDetached()); + assert(_song != nullptr); - song->Free(); + AllocatedProxySong *song = (AllocatedProxySong *) + const_cast<LightSong *>(_song); + delete song; } static bool -Visit(struct mpd_connection *connection, const char *uri, +Visit(struct mpd_connection *connection, Directory &root, const char *uri, bool recursive, const SongFilter *filter, VisitDirectory visit_directory, VisitSong visit_song, VisitPlaylist visit_playlist, Error &error); static bool -Visit(struct mpd_connection *connection, +Visit(struct mpd_connection *connection, Directory &root, bool recursive, const SongFilter *filter, const struct mpd_directory *directory, VisitDirectory visit_directory, VisitSong visit_song, @@ -362,80 +529,39 @@ Visit(struct mpd_connection *connection, { const char *path = mpd_directory_get_path(directory); - if (visit_directory) { - Directory *d = Directory::NewGeneric(path, &detached_root); - bool success = visit_directory(*d, error); - d->Free(); - if (!success) - return false; - } + if (visit_directory && + !visit_directory(Directory(path, &root), error)) + return false; if (recursive && - !Visit(connection, path, recursive, filter, + !Visit(connection, root, path, recursive, filter, visit_directory, visit_song, visit_playlist, error)) return false; return true; } -static void -Copy(TagBuilder &tag, TagType d_tag, - const struct mpd_song *song, enum mpd_tag_type s_tag) -{ - - for (unsigned i = 0;; ++i) { - const char *value = mpd_song_get_tag(song, s_tag, i); - if (value == nullptr) - break; - - tag.AddItem(d_tag, value); - } -} - -static Song * -Convert(const struct mpd_song *song) -{ - Song *s = Song::NewDetached(mpd_song_get_uri(song)); - - s->mtime = mpd_song_get_last_modified(song); - s->start_ms = mpd_song_get_start(song) * 1000; - s->end_ms = mpd_song_get_end(song) * 1000; - - TagBuilder tag; - tag.SetTime(mpd_song_get_duration(song)); - - for (const auto *i = &tag_table[0]; i->d != TAG_NUM_OF_ITEM_TYPES; ++i) - Copy(tag, i->d, song, i->s); - - s->tag = tag.Commit(); - - return s; -} - gcc_pure static bool -Match(const SongFilter *filter, const Song &song) +Match(const SongFilter *filter, const LightSong &song) { return filter == nullptr || filter->Match(song); } static bool Visit(const SongFilter *filter, - const struct mpd_song *song, + const mpd_song *_song, VisitSong visit_song, Error &error) { if (!visit_song) return true; - Song *s = Convert(song); - bool success = !Match(filter, *s) || visit_song(*s, error); - s->Free(); - - return success; + const ProxySong song(_song); + return !Match(filter, song) || visit_song(song, error); } static bool -Visit(const struct mpd_playlist *playlist, +Visit(const struct mpd_playlist *playlist, Directory &root, VisitPlaylist visit_playlist, Error &error) { if (!visit_playlist) @@ -444,7 +570,7 @@ Visit(const struct mpd_playlist *playlist, PlaylistInfo p(mpd_playlist_get_path(playlist), mpd_playlist_get_last_modified(playlist)); - return visit_playlist(p, detached_root, error); + return visit_playlist(p, root, error); } class ProxyEntity { @@ -486,7 +612,7 @@ ReceiveEntities(struct mpd_connection *connection) } static bool -Visit(struct mpd_connection *connection, const char *uri, +Visit(struct mpd_connection *connection, Directory &root, const char *uri, bool recursive, const SongFilter *filter, VisitDirectory visit_directory, VisitSong visit_song, VisitPlaylist visit_playlist, Error &error) @@ -504,7 +630,7 @@ Visit(struct mpd_connection *connection, const char *uri, break; case MPD_ENTITY_TYPE_DIRECTORY: - if (!Visit(connection, recursive, filter, + if (!Visit(connection, root, recursive, filter, mpd_entity_get_directory(entity), visit_directory, visit_song, visit_playlist, error)) @@ -519,7 +645,7 @@ Visit(struct mpd_connection *connection, const char *uri, break; case MPD_ENTITY_TYPE_PLAYLIST: - if (!Visit(mpd_entity_get_playlist(entity), + if (!Visit(mpd_entity_get_playlist(entity), root, visit_playlist, error)) return false; break; @@ -549,12 +675,10 @@ SearchSongs(struct mpd_connection *connection, bool result = true; struct mpd_song *song; while (result && (song = mpd_recv_song(connection)) != nullptr) { - Song *song2 = Convert(song); - mpd_song_free(song); + AllocatedProxySong song2(song); - result = !Match(selection.filter, *song2) || - visit_song(*song2, error); - song2->Free(); + result = !Match(selection.filter, song2) || + visit_song(song2, error); } mpd_response_finish(connection); @@ -578,7 +702,7 @@ ProxyDatabase::Visit(const DatabaseSelection &selection, return ::SearchSongs(connection, selection, visit_song, error); /* fall back to recursive walk (slow!) */ - return ::Visit(connection, selection.uri.c_str(), + return ::Visit(connection, *root, selection.uri.c_str(), selection.recursive, selection.filter, visit_directory, visit_song, visit_playlist, error); diff --git a/src/db/ProxyDatabasePlugin.hxx b/src/db/ProxyDatabasePlugin.hxx index 576c01c69..699d374b5 100644 --- a/src/db/ProxyDatabasePlugin.hxx +++ b/src/db/ProxyDatabasePlugin.hxx @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2013 The Music Player Daemon Project + * Copyright (C) 2003-2014 The Music Player Daemon Project * http://www.musicpd.org * * This program is free software; you can redistribute it and/or modify diff --git a/src/db/SimpleDatabasePlugin.cxx b/src/db/SimpleDatabasePlugin.cxx index e7ea7a62d..3d947c042 100644 --- a/src/db/SimpleDatabasePlugin.cxx +++ b/src/db/SimpleDatabasePlugin.cxx @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2013 The Music Player Daemon Project + * Copyright (C) 2003-2014 The Music Player Daemon Project * http://www.musicpd.org * * This program is free software; you can redistribute it and/or modify @@ -22,24 +22,26 @@ #include "DatabaseSelection.hxx" #include "DatabaseHelpers.hxx" #include "Directory.hxx" +#include "Song.hxx" #include "SongFilter.hxx" #include "DatabaseSave.hxx" #include "DatabaseLock.hxx" #include "DatabaseError.hxx" -#include "TextFile.hxx" +#include "fs/TextFile.hxx" #include "ConfigData.hxx" #include "fs/FileSystem.hxx" #include "util/Error.hxx" #include "util/Domain.hxx" #include "Log.hxx" -#include <sys/types.h> #include <errno.h> static constexpr Domain simple_db_domain("simple_db"); Database * -SimpleDatabase::Create(const config_param ¶m, Error &error) +SimpleDatabase::Create(gcc_unused EventLoop &loop, + gcc_unused DatabaseListener &listener, + const config_param ¶m, Error &error) { SimpleDatabase *db = new SimpleDatabase(); if (!db->Configure(param, error)) { @@ -72,7 +74,7 @@ SimpleDatabase::Check(Error &error) const assert(!path.IsNull()); /* Check if the file exists */ - if (!CheckAccess(path, F_OK)) { + if (!CheckAccess(path)) { /* If the file doesn't exist, we can't check if we can write * it, so we are going to try to get the directory path, and * see if we can write a file in that */ @@ -95,6 +97,7 @@ SimpleDatabase::Check(Error &error) const return false; } +#ifndef WIN32 /* Check if we can write to the directory */ if (!CheckAccess(dirPath, X_OK | W_OK)) { const int e = errno; @@ -103,7 +106,7 @@ SimpleDatabase::Check(Error &error) const dirPath_utf8.c_str()); return false; } - +#endif return true; } @@ -122,12 +125,14 @@ SimpleDatabase::Check(Error &error) const return false; } +#ifndef WIN32 /* And check that we can write to it */ if (!CheckAccess(path, R_OK | W_OK)) { error.FormatErrno("Can't open db file \"%s\" for reading/writing", path_utf8.c_str()); return false; } +#endif return true; } @@ -166,7 +171,7 @@ SimpleDatabase::Open(Error &error) #endif if (!Load(error)) { - root->Free(); + delete root; LogError(error); error.Clear(); @@ -186,36 +191,41 @@ SimpleDatabase::Close() assert(root != nullptr); assert(borrowed_song_count == 0); - root->Free(); + delete root; } -Song * +const LightSong * SimpleDatabase::GetSong(const char *uri, Error &error) const { assert(root != nullptr); + assert(borrowed_song_count == 0); db_lock(); - Song *song = root->LookupSong(uri); + const Song *song = root->LookupSong(uri); db_unlock(); - if (song == nullptr) + if (song == nullptr) { error.Format(db_domain, DB_NOT_FOUND, "No such song: %s", uri); + return nullptr; + } + + light_song = song->Export(); + #ifndef NDEBUG - else - ++const_cast<unsigned &>(borrowed_song_count); + ++borrowed_song_count; #endif - return song; + return &light_song; } void -SimpleDatabase::ReturnSong(gcc_unused Song *song) const +SimpleDatabase::ReturnSong(gcc_unused const LightSong *song) const { - assert(song != nullptr); + assert(song == &light_song); #ifndef NDEBUG assert(borrowed_song_count > 0); - --const_cast<unsigned &>(borrowed_song_count); + --borrowed_song_count; #endif } @@ -243,9 +253,11 @@ SimpleDatabase::Visit(const DatabaseSelection &selection, if (directory == nullptr) { if (visit_song) { Song *song = root->LookupSong(selection.uri.c_str()); - if (song != nullptr) - return !selection.Match(*song) || - visit_song(*song, error); + if (song != nullptr) { + const LightSong song2 = song->Export(); + return !selection.Match(song2) || + visit_song(song2, error); + } } error.Set(db_domain, DB_NOT_FOUND, "No such directory"); diff --git a/src/db/SimpleDatabasePlugin.hxx b/src/db/SimpleDatabasePlugin.hxx index dfe981dd8..509b91e4e 100644 --- a/src/db/SimpleDatabasePlugin.hxx +++ b/src/db/SimpleDatabasePlugin.hxx @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2013 The Music Player Daemon Project + * Copyright (C) 2003-2014 The Music Player Daemon Project * http://www.musicpd.org * * This program is free software; you can redistribute it and/or modify @@ -22,6 +22,7 @@ #include "DatabasePlugin.hxx" #include "fs/AllocatedPath.hxx" +#include "LightSong.hxx" #include "Compiler.h" #include <cassert> @@ -36,8 +37,13 @@ class SimpleDatabase : public Database { time_t mtime; + /** + * A buffer for GetSong(). + */ + mutable LightSong light_song; + #ifndef NDEBUG - unsigned borrowed_song_count; + mutable unsigned borrowed_song_count; #endif SimpleDatabase() @@ -53,15 +59,16 @@ public: bool Save(Error &error); - static Database *Create(const config_param ¶m, + static Database *Create(EventLoop &loop, DatabaseListener &listener, + const config_param ¶m, Error &error); virtual bool Open(Error &error) override; virtual void Close() override; - virtual Song *GetSong(const char *uri_utf8, - Error &error) const override; - virtual void ReturnSong(Song *song) const; + virtual const LightSong *GetSong(const char *uri_utf8, + Error &error) const override; + virtual void ReturnSong(const LightSong *song) const; virtual bool Visit(const DatabaseSelection &selection, VisitDirectory visit_directory, diff --git a/src/db/UpnpDatabasePlugin.cxx b/src/db/UpnpDatabasePlugin.cxx new file mode 100644 index 000000000..0768488a3 --- /dev/null +++ b/src/db/UpnpDatabasePlugin.cxx @@ -0,0 +1,790 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * http://www.musicpd.org + * + * 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. + * + * 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. + */ + +#include "config.h" +#include "UpnpDatabasePlugin.hxx" +#include "upnp/Domain.hxx" +#include "upnp/upnpplib.hxx" +#include "upnp/Discovery.hxx" +#include "upnp/ContentDirectoryService.hxx" +#include "upnp/Directory.hxx" +#include "upnp/Tags.hxx" +#include "upnp/Util.hxx" +#include "DatabasePlugin.hxx" +#include "DatabaseSelection.hxx" +#include "DatabaseError.hxx" +#include "PlaylistVector.hxx" +#include "Directory.hxx" +#include "LightSong.hxx" +#include "ConfigData.hxx" +#include "tag/TagBuilder.hxx" +#include "tag/TagTable.hxx" +#include "util/Error.hxx" +#include "util/Domain.hxx" +#include "Log.hxx" +#include "SongFilter.hxx" + +#include <string> +#include <vector> +#include <set> + +#include <assert.h> +#include <string.h> + +static const char *const rootid = "0"; + +class UpnpSong : public LightSong { + std::string uri2; + + Tag tag2; + +public: + explicit UpnpSong(UPnPDirObject &&object) + :uri2(std::move(object.url)), tag2(std::move(object.tag)) { + directory = nullptr; + uri = uri2.c_str(); + tag = &tag2; + mtime = 0; + start_ms = end_ms = 0; + } + + UpnpSong(UPnPDirObject &&object, const char *_uri) + :uri2(_uri), tag2(std::move(object.tag)) { + directory = nullptr; + uri = uri2.c_str(); + tag = &tag2; + mtime = 0; + start_ms = end_ms = 0; + } +}; + +class UpnpDatabase : public Database { + LibUPnP *m_lib; + UPnPDeviceDirectory *m_superdir; + Directory *m_root; + +public: + static Database *Create(EventLoop &loop, DatabaseListener &listener, + const config_param ¶m, + Error &error); + + virtual bool Open(Error &error) override; + virtual void Close() override; + virtual const LightSong *GetSong(const char *uri_utf8, + Error &error) const override; + virtual void ReturnSong(const LightSong *song) const; + + virtual bool Visit(const DatabaseSelection &selection, + VisitDirectory visit_directory, + VisitSong visit_song, + VisitPlaylist visit_playlist, + Error &error) const override; + + virtual bool VisitUniqueTags(const DatabaseSelection &selection, + TagType tag_type, + VisitString visit_string, + Error &error) const override; + + virtual bool GetStats(const DatabaseSelection &selection, + DatabaseStats &stats, + Error &error) const override; + virtual time_t GetUpdateStamp() const {return 0;} + +protected: + bool Configure(const config_param ¶m, Error &error); + +private: + bool VisitServer(ContentDirectoryService &server, + const std::vector<std::string> &vpath, + const DatabaseSelection &selection, + VisitDirectory visit_directory, + VisitSong visit_song, + VisitPlaylist visit_playlist, + Error &error) const; + + /** + * Run an UPnP search according to MPD parameters, and + * visit_song the results. + */ + bool SearchSongs(ContentDirectoryService &server, + const char *objid, + const DatabaseSelection &selection, + VisitSong visit_song, + Error &error) const; + + bool SearchSongs(ContentDirectoryService &server, + const char *objid, + const DatabaseSelection &selection, + UPnPDirContent& dirbuf, + Error &error) const; + + bool Namei(ContentDirectoryService &server, + const std::vector<std::string> &vpath, + std::string &oobjid, UPnPDirObject &dirent, + Error &error) const; + + /** + * Take server and objid, return metadata. + */ + bool ReadNode(ContentDirectoryService &server, + const char *objid, UPnPDirObject& dirent, + Error &error) const; + + /** + * Get the path for an object Id. This works much like pwd, + * except easier cause our inodes have a parent id. Not used + * any more actually (see comments in SearchSongs). + */ + bool BuildPath(ContentDirectoryService &server, + const UPnPDirObject& dirent, std::string &idpath, + Error &error) const; +}; + +Database * +UpnpDatabase::Create(gcc_unused EventLoop &loop, + gcc_unused DatabaseListener &listener, + const config_param ¶m, Error &error) +{ + UpnpDatabase *db = new UpnpDatabase(); + if (!db->Configure(param, error)) { + delete db; + return nullptr; + } + + /* libupnp loses its ability to receive multicast messages + apparently due to daemonization; using the LazyDatabase + wrapper works around this problem */ + return db; +} + +bool +UpnpDatabase::Configure(const config_param &, Error &) +{ + return true; +} + +bool +UpnpDatabase::Open(Error &error) +{ + m_lib = new LibUPnP(); + if (!m_lib->ok()) { + error.Set(m_lib->GetInitError()); + delete m_lib; + return false; + } + + m_superdir = new UPnPDeviceDirectory(m_lib); + if (!m_superdir->Start(error)) { + delete m_superdir; + delete m_lib; + return false; + } + + m_root = Directory::NewRoot(); + // Wait for device answers. This should be consistent with the value set + // in the lib (currently 2) + sleep(2); + return true; +} + +void +UpnpDatabase::Close() +{ + delete m_root; + delete m_superdir; + delete m_lib; +} + +void +UpnpDatabase::ReturnSong(const LightSong *_song) const +{ + assert(_song != nullptr); + + UpnpSong *song = (UpnpSong *)const_cast<LightSong *>(_song); + delete song; +} + +// Get song info by path. We can receive either the id path, or the titles +// one +const LightSong * +UpnpDatabase::GetSong(const char *uri, Error &error) const +{ + UpnpSong *song = nullptr; + auto vpath = stringToTokens(uri, "/", true); + if (vpath.size() >= 2) { + ContentDirectoryService server; + if (!m_superdir->getServer(vpath[0].c_str(), server, error)) + return nullptr; + + vpath.erase(vpath.begin()); + UPnPDirObject dirent; + if (vpath[0].compare(rootid)) { + std::string objid; + if (!Namei(server, vpath, objid, dirent, error)) + return nullptr; + } else { + if (!ReadNode(server, vpath.back().c_str(), dirent, + error)) + return nullptr; + } + + song = new UpnpSong(std::move(dirent)); + } + if (song == nullptr) + error.Format(db_domain, DB_NOT_FOUND, "No such song: %s", uri); + + return song; +} + +/** + * Double-quote a string, adding internal backslash escaping. + */ +static void +dquote(std::string &out, const char *in) +{ + out.append(1, '"'); + + for (; *in != 0; ++in) { + switch(*in) { + case '\\': + case '"': + out.append(1, '\\'); + out.append(1, *in); + break; + + default: + out.append(1, *in); + } + } + + out.append(1, '"'); +} + +// Run an UPnP search, according to MPD parameters. Return results as +// UPnP items +bool +UpnpDatabase::SearchSongs(ContentDirectoryService &server, + const char *objid, + const DatabaseSelection &selection, + UPnPDirContent &dirbuf, + Error &error) const +{ + const SongFilter *filter = selection.filter; + if (selection.filter == nullptr) + return true; + + std::set<std::string> searchcaps; + if (!server.getSearchCapabilities(m_lib->getclh(), searchcaps, error)) + return false; + + if (searchcaps.empty()) + return true; + + std::string cond; + for (const auto &item : filter->GetItems()) { + switch (auto tag = item.GetTag()) { + case LOCATE_TAG_ANY_TYPE: + { + if (!cond.empty()) { + cond += " and "; + } + cond += "("; + bool first(true); + for (const auto& cap : searchcaps) { + if (first) + first = false; + else + cond += " or "; + cond += cap; + if (item.GetFoldCase()) { + cond += " contains "; + } else { + cond += " = "; + } + dquote(cond, item.GetValue().c_str()); + } + cond += ")"; + } + break; + + default: + /* Unhandled conditions like + LOCATE_TAG_BASE_TYPE or + LOCATE_TAG_FILE_TYPE won't have a + corresponding upnp prop, so they will be + skipped */ + if (tag == TAG_ALBUM_ARTIST) + tag = TAG_ARTIST; + + // TODO: support LOCATE_TAG_ANY_TYPE etc. + const char *name = tag_table_lookup(upnp_tags, + TagType(tag)); + if (name == nullptr) + continue; + + if (!cond.empty()) { + cond += " and "; + } + cond += name; + + /* FoldCase doubles up as contains/equal + switch. UpNP search is supposed to be + case-insensitive, but at least some servers + have the same convention as mpd (e.g.: + minidlna) */ + if (item.GetFoldCase()) { + cond += " contains "; + } else { + cond += " = "; + } + dquote(cond, item.GetValue().c_str()); + } + } + + return server.search(m_lib->getclh(), + objid, cond.c_str(), dirbuf, + error); +} + +static bool +visitSong(UPnPDirObject &&meta, const char *path, + const DatabaseSelection &selection, + VisitSong visit_song, Error& error) +{ + if (!visit_song) + return true; + + const UpnpSong song(std::move(meta), path); + return !selection.Match(song) || visit_song(song, error); +} + +/** + * Build synthetic path based on object id for search results. The use + * of "rootid" is arbitrary, any name that is not likely to be a top + * directory name would fit. + */ +static const std::string +songPath(const std::string &servername, + const std::string &objid) +{ + return servername + "/" + rootid + "/" + objid; +} + +bool +UpnpDatabase::SearchSongs(ContentDirectoryService &server, + const char *objid, + const DatabaseSelection &selection, + VisitSong visit_song, + Error &error) const +{ + UPnPDirContent dirbuf; + if (!visit_song) + return true; + if (!SearchSongs(server, objid, selection, dirbuf, error)) + return false; + + for (auto &dirent : dirbuf.objects) { + if (dirent.type != UPnPDirObject::Type::ITEM || + dirent.item_class != UPnPDirObject::ItemClass::MUSIC) + continue; + + // We get song ids as the result of the UPnP search. But our + // client expects paths (e.g. we get 1$4$3788 from minidlna, + // but we need to translate to /Music/All_Music/Satisfaction). + // We can do this in two ways: + // - Rebuild a normal path using BuildPath() which is a kind of pwd + // - Build a bogus path based on the song id. + // The first method is nice because the returned paths are pretty, but + // it has two big problems: + // - The song paths are ambiguous: e.g. minidlna returns all search + // results as being from the "All Music" directory, which can + // contain several songs with the same title (but different objids) + // - The performance of BuildPath() is atrocious on very big + // directories, even causing timeouts in clients. And of + // course, 'All Music' is very big. + // So we return synthetic and ugly paths based on the object id, + // which we later have to detect. + std::string path = songPath(server.getFriendlyName(), + dirent.m_id); + //BuildPath(server, dirent, path); + if (!visitSong(std::move(dirent), path.c_str(), + selection, visit_song, + error)) + return false; + } + + return true; +} + +bool +UpnpDatabase::ReadNode(ContentDirectoryService &server, + const char *objid, UPnPDirObject &dirent, + Error &error) const +{ + UPnPDirContent dirbuf; + if (!server.getMetadata(m_lib->getclh(), objid, dirbuf, error)) + return false; + + if (dirbuf.objects.size() == 1) { + dirent = std::move(dirbuf.objects[0]); + } else { + error.Format(upnp_domain, "Bad resource"); + return false; + } + + return true; +} + +bool +UpnpDatabase::BuildPath(ContentDirectoryService &server, + const UPnPDirObject& idirent, + std::string &path, + Error &error) const +{ + const char *pid = idirent.m_id.c_str(); + path.clear(); + UPnPDirObject dirent; + while (strcmp(pid, rootid) != 0) { + if (!ReadNode(server, pid, dirent, error)) + return false; + pid = dirent.m_pid.c_str(); + path = dirent.name + (path.empty()? "" : "/" + path); + } + path = std::string(server.getFriendlyName()) + "/" + path; + return true; +} + +// Take server and internal title pathname and return objid and metadata. +bool +UpnpDatabase::Namei(ContentDirectoryService &server, + const std::vector<std::string> &vpath, + std::string &oobjid, UPnPDirObject &odirent, + Error &error) const +{ + oobjid.clear(); + std::string objid(rootid); + + if (vpath.empty()) { + // looking for root info + if (!ReadNode(server, rootid, odirent, error)) + return false; + + oobjid = rootid; + return true; + } + + const UpnpClient_Handle handle = m_lib->getclh(); + + // Walk the path elements, read each directory and try to find the next one + for (unsigned int i = 0; i < vpath.size(); i++) { + UPnPDirContent dirbuf; + if (!server.readDir(handle, objid.c_str(), dirbuf, error)) + return false; + + // Look for the name in the sub-container list + UPnPDirObject *child = dirbuf.FindObject(vpath[i].c_str()); + if (child == nullptr) + break; + + switch (child->type) { + case UPnPDirObject::Type::UNKNOWN: + assert(false); + gcc_unreachable(); + + case UPnPDirObject::Type::CONTAINER: + objid = child->m_id; // Next readdir target + if (i == vpath.size() - 1) { + // The last element in the path was found and it's + // a container, we're done + oobjid = objid; + odirent = std::move(*child); + return true; + } + break; + + case UPnPDirObject::Type::ITEM: + // If this is the last path elt, we found the target, + // else it does not exist + if (i == vpath.size() - 1) { + oobjid = objid; + odirent = std::move(*child); + return true; + } else { + error.Format(db_domain, DB_NOT_FOUND, + "No such object"); + return false; + } + } + } + + error.Format(db_domain, DB_NOT_FOUND, "No such object"); + return false; +} + +// vpath is a parsed and writeable version of selection.uri. There is +// really just one path parameter. +bool +UpnpDatabase::VisitServer(ContentDirectoryService &server, + const std::vector<std::string> &vpath, + const DatabaseSelection &selection, + VisitDirectory visit_directory, + VisitSong visit_song, + VisitPlaylist visit_playlist, + Error &error) const +{ + /* If the path begins with rootid, we know that this is a + song, not a directory (because that's how we set things + up). Just visit it. Note that the choice of rootid is + arbitrary, any value not likely to be the name of a top + directory would be ok. */ + /* !Note: this *can't* be handled by Namei further down, + because the path is not valid for traversal. Besides, it's + just faster to access the target node directly */ + if (!vpath.empty() && !vpath[0].compare(rootid)) { + if (visit_song) { + UPnPDirObject dirent; + if (!ReadNode(server, vpath.back().c_str(), dirent, + error)) + return false; + + if (!visitSong(std::move(dirent), "", selection, + visit_song, error)) + return false; + } + return true; + } + + // Translate the target path into an object id and the associated metadata. + std::string objid; + UPnPDirObject tdirent; + if (!Namei(server, vpath, objid, tdirent, error)) + return false; + + if (objid.empty()) + // Not found, not a fatal error + return true; + + /* If recursive is set, this is a search... No use sending it + if the filter is empty. In this case, we implement limited + recursion (1-deep) here, which will handle the "add dir" + case. */ + if (selection.recursive && selection.filter) + return SearchSongs(server, objid.c_str(), selection, + visit_song, error); + + if (tdirent.type == UPnPDirObject::Type::ITEM) { + // Target is a song. Not too sure we ever get there actually, maybe + // this is always catched by the special uri test above. + switch (tdirent.item_class) { + case UPnPDirObject::ItemClass::MUSIC: + if (visit_song) + return visitSong(std::move(tdirent), "", + selection, visit_song, + error); + break; + + case UPnPDirObject::ItemClass::PLAYLIST: + if (visit_playlist) { + /* Note: I've yet to see a playlist + item (playlists seem to be usually + handled as containers, so I'll decide + what to do when I see one... */ + } + break; + + case UPnPDirObject::ItemClass::UNKNOWN: + break; + } + + return true; + } + + /* Target was a a container. Visit it. We could read slices + and loop here, but it's not useful as mpd will only return + data to the client when we're done anyway. */ + UPnPDirContent dirbuf; + if (!server.readDir(m_lib->getclh(), objid.c_str(), dirbuf, error)) + return false; + + for (auto &dirent : dirbuf.objects) { + switch (dirent.type) { + case UPnPDirObject::Type::UNKNOWN: + assert(false); + gcc_unreachable(); + + case UPnPDirObject::Type::CONTAINER: + if (visit_directory) { + Directory d((selection.uri + "/" + + dirent.name).c_str(), + m_root); + if (!visit_directory(d, error)) + return false; + } + + break; + + case UPnPDirObject::Type::ITEM: + switch (dirent.item_class) { + case UPnPDirObject::ItemClass::MUSIC: + if (visit_song) { + /* We identify songs by giving + them a special path. The Id + is enough to fetch them + from the server anyway. */ + + std::string p; + if (!selection.recursive) + p = selection.uri + "/" + + dirent.name; + + if (!visitSong(std::move(dirent), + p.c_str(), + selection, visit_song, error)) + return false; + } + + break; + + case UPnPDirObject::ItemClass::PLAYLIST: + if (visit_playlist) { + /* Note: I've yet to see a + playlist item (playlists + seem to be usually handled + as containers, so I'll + decide what to do when I + see one... */ + } + + break; + + case UPnPDirObject::ItemClass::UNKNOWN: + break; + } + } + } + + return true; +} + +// Deal with the possibly multiple servers, call VisitServer if needed. +bool +UpnpDatabase::Visit(const DatabaseSelection &selection, + VisitDirectory visit_directory, + VisitSong visit_song, + VisitPlaylist visit_playlist, + Error &error) const +{ + auto vpath = stringToTokens(selection.uri, "/", true); + if (vpath.empty()) { + std::vector<ContentDirectoryService> servers; + if (!m_superdir->getDirServices(servers, error)) + return false; + + if (!selection.recursive) { + // If the path is empty and recursive is not set, synthetize a + // pseudo-directory from the list of servers. + if (visit_directory) { + for (auto& server : servers) { + Directory d(server.getFriendlyName(), m_root); + if (!visit_directory(d, error)) + return false; + } + } + } else { + // Recursive is set: visit each server + for (auto& server : servers) { + if (!VisitServer(server, std::vector<std::string>(), selection, + visit_directory, visit_song, visit_playlist, error)) + return false; + } + } + return true; + } + + // We do have a path: the first element selects the server + std::string servername(vpath[0]); + vpath.erase(vpath.begin()); + + ContentDirectoryService server; + if (!m_superdir->getServer(servername.c_str(), server, error)) + return false; + + return VisitServer(server, vpath, selection, + visit_directory, visit_song, visit_playlist, error); +} + +bool +UpnpDatabase::VisitUniqueTags(const DatabaseSelection &selection, + TagType tag, + VisitString visit_string, + Error &error) const +{ + if (!visit_string) + return true; + + std::vector<ContentDirectoryService> servers; + if (!m_superdir->getDirServices(servers, error)) + return false; + + std::set<std::string> values; + for (auto& server : servers) { + UPnPDirContent dirbuf; + if (!SearchSongs(server, rootid, selection, dirbuf, error)) + return false; + + for (const auto &dirent : dirbuf.objects) { + if (dirent.type != UPnPDirObject::Type::ITEM || + dirent.item_class != UPnPDirObject::ItemClass::MUSIC) + continue; + + const char *value = dirent.tag.GetValue(tag); + if (value != nullptr) { +#if defined(__clang__) || GCC_CHECK_VERSION(4,8) + values.emplace(value); +#else + values.insert(value); +#endif + } + } + } + + for (const auto& value : values) + if (!visit_string(value.c_str(), error)) + return false; + + return true; +} + +bool +UpnpDatabase::GetStats(const DatabaseSelection &, + DatabaseStats &stats, Error &) const +{ + /* Note: this gets called before the daemonizing so we can't + reallyopen this would be a problem if we had real stats */ + stats.song_count = 0; + stats.total_duration = 0; + stats.artist_count = 0; + stats.album_count = 0; + return true; +} + +const DatabasePlugin upnp_db_plugin = { + "upnp", + UpnpDatabase::Create, +}; diff --git a/test/FakeSong.cxx b/src/db/UpnpDatabasePlugin.hxx index c0859d7b1..0228405cd 100644 --- a/test/FakeSong.cxx +++ b/src/db/UpnpDatabasePlugin.hxx @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2012 The Music Player Daemon Project + * Copyright (C) 2003-2014 The Music Player Daemon Project * http://www.musicpd.org * * This program is free software; you can redistribute it and/or modify @@ -17,17 +17,11 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ -#include "config.h" -#include "Song.hxx" -#include "directory.h" -#include "Compiler.h" +#ifndef MPD_UPNP_DATABASE_PLUGIN_HXX +#define MPD_UPNP_DATABASE_PLUGIN_HXX -#include <stdlib.h> +struct DatabasePlugin; -struct directory detached_root; +extern const DatabasePlugin upnp_db_plugin; -Song * -song_dup_detached(gcc_unused const Song *src) -{ - abort(); -} +#endif diff --git a/src/db/upnp/Action.hxx b/src/db/upnp/Action.hxx new file mode 100644 index 000000000..28c88be92 --- /dev/null +++ b/src/db/upnp/Action.hxx @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * http://www.musicpd.org + * + * 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. + * + * 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. + */ + +#ifndef MPD_UPNP_ACTION_HXX +#define MPD_UPNP_ACTION_HXX + +#include "Compiler.h" + +#include <upnp/upnptools.h> + +static inline constexpr unsigned +CountNameValuePairs() +{ + return 0; +} + +template<typename... Args> +static inline constexpr unsigned +CountNameValuePairs(gcc_unused const char *name, gcc_unused const char *value, + Args... args) +{ + return 1 + CountNameValuePairs(args...); +} + +/** + * A wrapper for UpnpMakeAction() that counts the number of name/value + * pairs and adds the nullptr sentinel. + */ +template<typename... Args> +static inline IXML_Document * +MakeActionHelper(const char *action_name, const char *service_type, + Args... args) +{ + const unsigned n = CountNameValuePairs(args...); + return UpnpMakeAction(action_name, service_type, n, + args..., + nullptr, nullptr); +} + +#endif diff --git a/src/db/upnp/ContentDirectoryService.cxx b/src/db/upnp/ContentDirectoryService.cxx new file mode 100644 index 000000000..aea8144bf --- /dev/null +++ b/src/db/upnp/ContentDirectoryService.cxx @@ -0,0 +1,295 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * http://www.musicpd.org + * + * 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. + * + * 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. + */ + +#include "config.h" +#include "ContentDirectoryService.hxx" +#include "Domain.hxx" +#include "Device.hxx" +#include "ixmlwrap.hxx" +#include "Directory.hxx" +#include "Util.hxx" +#include "Action.hxx" +#include "util/Error.hxx" + +#include <stdio.h> + +ContentDirectoryService::ContentDirectoryService(const UPnPDevice &device, + const UPnPService &service) + :m_actionURL(caturl(device.URLBase, service.controlURL)), + m_serviceType(service.serviceType), + m_deviceId(device.UDN), + m_friendlyName(device.friendlyName), + m_manufacturer(device.manufacturer), + m_modelName(device.modelName), + m_rdreqcnt(200) +{ + if (!m_modelName.compare("MediaTomb")) { + // Readdir by 200 entries is good for most, but MediaTomb likes + // them really big. Actually 1000 is better but I don't dare + m_rdreqcnt = 500; + } +} + +class DirBResFree { +public: + IXML_Document **rspp; + DirBResFree(IXML_Document **_rspp) + :rspp(_rspp) {} + ~DirBResFree() + { + if (*rspp) + ixmlDocument_free(*rspp); + } +}; + +static bool +ReadResultTag(UPnPDirContent &dirbuf, IXML_Document *response, Error &error) +{ + const char *p = ixmlwrap::getFirstElementValue(response, "Result"); + if (p == nullptr) + p = ""; + + return dirbuf.parse(p, error); +} + +bool +ContentDirectoryService::readDirSlice(UpnpClient_Handle hdl, + const char *objectId, int offset, + int count, UPnPDirContent &dirbuf, + int *didreadp, int *totalp, + Error &error) +{ + // Create request + char ofbuf[100], cntbuf[100]; + sprintf(ofbuf, "%d", offset); + sprintf(cntbuf, "%d", count); + // Some devices require an empty SortCriteria, else bad params + IXML_Document *request = + MakeActionHelper("Browse", m_serviceType.c_str(), + "ObjectID", objectId, + "BrowseFlag", "BrowseDirectChildren", + "Filter", "*", + "SortCriteria", "", + "StartingIndex", ofbuf, + "RequestedCount", cntbuf); + if (request == nullptr) { + error.Set(upnp_domain, "UpnpMakeAction() failed"); + return false; + } + + IXML_Document *response; + int code = UpnpSendAction(hdl, m_actionURL.c_str(), m_serviceType.c_str(), + 0 /*devUDN*/, request, &response); + ixmlDocument_free(request); + if (code != UPNP_E_SUCCESS) { + error.Format(upnp_domain, code, + "UpnpSendAction() failed: %s", + UpnpGetErrorMessage(code)); + return false; + } + + DirBResFree cleaner(&response); + + int didread = -1; + const char *value = ixmlwrap::getFirstElementValue(response, "NumberReturned"); + if (value != nullptr) + didread = atoi(value); + + if (count == -1 || count == 0) { + // TODO: what's this? + error.Set(upnp_domain, "got -1 or 0 entries"); + return false; + } + + value = ixmlwrap::getFirstElementValue(response, "TotalMatches"); + if (value != nullptr) + *totalp = atoi(value); + + if (!ReadResultTag(dirbuf, response, error)) + return false; + + *didreadp = didread; + return true; +} + +bool +ContentDirectoryService::readDir(UpnpClient_Handle handle, + const char *objectId, + UPnPDirContent &dirbuf, + Error &error) +{ + int offset = 0; + int total = 1000;// Updated on first read. + + while (offset < total) { + int count; + if (!readDirSlice(handle, objectId, offset, m_rdreqcnt, dirbuf, + &count, &total, error)) + return false; + + offset += count; + } + + return true; +} + +bool +ContentDirectoryService::search(UpnpClient_Handle hdl, + const char *objectId, + const char *ss, + UPnPDirContent &dirbuf, + Error &error) +{ + int offset = 0; + int total = 1000;// Updated on first read. + + while (offset < total) { + char ofbuf[100]; + sprintf(ofbuf, "%d", offset); + + IXML_Document *request = + MakeActionHelper("Search", m_serviceType.c_str(), + "ContainerID", objectId, + "SearchCriteria", ss, + "Filter", "*", + "SortCriteria", "", + "StartingIndex", ofbuf, + "RequestedCount", "0"); // Setting a value here gets twonky into fits + if (request == 0) { + error.Set(upnp_domain, "UpnpMakeAction() failed"); + return false; + } + + IXML_Document *response; + auto code = UpnpSendAction(hdl, m_actionURL.c_str(), + m_serviceType.c_str(), + 0 /*devUDN*/, request, &response); + ixmlDocument_free(request); + if (code != UPNP_E_SUCCESS) { + error.Format(upnp_domain, code, + "UpnpSendAction() failed: %s", + UpnpGetErrorMessage(code)); + return false; + } + + DirBResFree cleaner(&response); + + int count = -1; + const char *value = + ixmlwrap::getFirstElementValue(response, "NumberReturned"); + if (value != nullptr) + count = atoi(value); + + if (count == -1 || count == 0) { + // TODO: what's this? + error.Set(upnp_domain, "got -1 or 0 entries"); + return false; + } + + offset += count; + + value = ixmlwrap::getFirstElementValue(response, "TotalMatches"); + if (value != nullptr) + total = atoi(value); + + if (!ReadResultTag(dirbuf, response, error)) + return false; + } + + return true; +} + +bool +ContentDirectoryService::getSearchCapabilities(UpnpClient_Handle hdl, + std::set<std::string> &result, + Error &error) +{ + IXML_Document *request = + UpnpMakeAction("GetSearchCapabilities", m_serviceType.c_str(), + 0, + nullptr, nullptr); + if (request == 0) { + error.Set(upnp_domain, "UpnpMakeAction() failed"); + return false; + } + + IXML_Document *response; + auto code = UpnpSendAction(hdl, m_actionURL.c_str(), + m_serviceType.c_str(), + 0 /*devUDN*/, request, &response); + ixmlDocument_free(request); + if (code != UPNP_E_SUCCESS) { + error.Format(upnp_domain, code, + "UpnpSendAction() failed: %s", + UpnpGetErrorMessage(code)); + return false; + } + + std::string tbuf = ixmlwrap::getFirstElementValue(response, "SearchCaps"); + ixmlDocument_free(response); + + result.clear(); + if (!tbuf.compare("*")) { + result.insert(result.end(), "*"); + } else if (!tbuf.empty()) { + if (!csvToStrings(tbuf, result)) { + error.Set(upnp_domain, "Bad response"); + return false; + } + } + + return true; +} + +bool +ContentDirectoryService::getMetadata(UpnpClient_Handle hdl, + const char *objectId, + UPnPDirContent &dirbuf, + Error &error) +{ + // Create request + IXML_Document *request = + MakeActionHelper("Browse", m_serviceType.c_str(), + "ObjectID", objectId, + "BrowseFlag", "BrowseMetadata", + "Filter", "*", + "SortCriteria", "", + "StartingIndex", "0", + "RequestedCount", "1"); + if (request == nullptr) { + error.Set(upnp_domain, "UpnpMakeAction() failed"); + return false; + } + + IXML_Document *response; + auto code = UpnpSendAction(hdl, m_actionURL.c_str(), + m_serviceType.c_str(), + 0 /*devUDN*/, request, &response); + ixmlDocument_free(request); + if (code != UPNP_E_SUCCESS) { + error.Format(upnp_domain, code, + "UpnpSendAction() failed: %s", + UpnpGetErrorMessage(code)); + return false; + } + + bool success = ReadResultTag(dirbuf, response, error); + ixmlDocument_free(response); + return success; +} diff --git a/src/db/upnp/ContentDirectoryService.hxx b/src/db/upnp/ContentDirectoryService.hxx new file mode 100644 index 000000000..63a13583f --- /dev/null +++ b/src/db/upnp/ContentDirectoryService.hxx @@ -0,0 +1,126 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * http://www.musicpd.org + * + * 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. + * + * 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. + */ + +#ifndef _UPNPDIR_HXX_INCLUDED_ +#define _UPNPDIR_HXX_INCLUDED_ + +#include <upnp/upnp.h> + +#include <string> +#include <set> + +class Error; +class UPnPDevice; +struct UPnPService; +class UPnPDirContent; + +/** + * Content Directory Service class. + * + * This stores identity data from a directory service + * and the device it belongs to, and has methods to query + * the directory, using libupnp for handling the UPnP protocols. + * + * Note: m_rdreqcnt: number of entries requested per directory read. + * 0 means all entries. The device can still return less entries than + * requested, depending on its own limits. In general it's not optimal + * becauses it triggers issues, and is sometimes actually slower, e.g. on + * a D-Link NAS 327 + * + * The value chosen may affect by the UpnpSetMaxContentLength + * (2000*1024) done during initialization, but this should be ample + */ +class ContentDirectoryService { + std::string m_actionURL; + std::string m_serviceType; + std::string m_deviceId; + std::string m_friendlyName; + std::string m_manufacturer; + std::string m_modelName; + + int m_rdreqcnt; // Slice size to use when reading + +public: + /** + * Construct by copying data from device and service objects. + * + * The discovery service does this: use getDirServices() + */ + ContentDirectoryService(const UPnPDevice &device, + const UPnPService &service); + + /** An empty one */ + ContentDirectoryService() = default; + + /** Read a container's children list into dirbuf. + * + * @param objectId the UPnP object Id for the container. Root has Id "0" + * @param[out] dirbuf stores the entries we read. + */ + bool readDir(UpnpClient_Handle handle, + const char *objectId, UPnPDirContent &dirbuf, + Error &error); + + bool readDirSlice(UpnpClient_Handle handle, + const char *objectId, int offset, + int count, UPnPDirContent& dirbuf, + int *didread, int *total, + Error &error); + + /** Search the content directory service. + * + * @param objectId the UPnP object Id under which the search + * should be done. Not all servers actually support this below + * root. Root has Id "0" + * @param searchstring an UPnP searchcriteria string. Check the + * UPnP document: UPnP-av-ContentDirectory-v1-Service-20020625.pdf + * section 2.5.5. Maybe we'll provide an easier way some day... + * @param[out] dirbuf stores the entries we read. + */ + bool search(UpnpClient_Handle handle, + const char *objectId, const char *searchstring, + UPnPDirContent &dirbuf, + Error &error); + + /** Read metadata for a given node. + * + * @param objectId the UPnP object Id. Root has Id "0" + * @param[out] dirbuf stores the entries we read. At most one entry will be + * returned. + */ + bool getMetadata(UpnpClient_Handle handle, + const char *objectId, UPnPDirContent &dirbuf, + Error &error); + + /** Retrieve search capabilities + * + * @param[out] result an empty vector: no search, or a single '*' element: + * any tag can be used in a search, or a list of usable tag names. + */ + bool getSearchCapabilities(UpnpClient_Handle handle, + std::set<std::string> &result, + Error &error); + + /** Retrieve the "friendly name" for this server, useful for display. */ + const char *getFriendlyName() const { + return m_friendlyName.c_str(); + } +}; + +#endif /* _UPNPDIR_HXX_INCLUDED_ */ diff --git a/src/db/upnp/Device.cxx b/src/db/upnp/Device.cxx new file mode 100644 index 000000000..e668f839a --- /dev/null +++ b/src/db/upnp/Device.cxx @@ -0,0 +1,133 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * http://www.musicpd.org + * + * 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. + * + * 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. + */ + +#include "config.h" +#include "Device.hxx" +#include "Util.hxx" +#include "Expat.hxx" +#include "util/Error.hxx" + +#include <stdlib.h> + +#include <string.h> + +/** + * An XML parser which constructs an UPnP device object from the + * device descriptor. + */ +class UPnPDeviceParser final : public CommonExpatParser { + UPnPDevice &m_device; + std::vector<std::string> m_path; + UPnPService m_tservice; + +public: + UPnPDeviceParser(UPnPDevice& device) + :m_device(device) {} + +protected: + virtual void StartElement(const XML_Char *name, const XML_Char **) { + m_path.push_back(name); + } + + virtual void EndElement(const XML_Char *name) { + if (!strcmp(name, "service")) { + m_device.services.push_back(m_tservice); + m_tservice.clear(); + } + + m_path.pop_back(); + } + + virtual void CharacterData(const XML_Char *s, int len) { + const auto ¤t = m_path.back(); + std::string str = trimstring(s, len); + switch (current[0]) { + case 'c': + if (!current.compare("controlURL")) + m_tservice.controlURL = std::move(str); + break; + case 'd': + if (!current.compare("deviceType")) + m_device.deviceType = std::move(str); + break; + case 'e': + if (!current.compare("eventSubURL")) + m_tservice.eventSubURL = std::move(str); + break; + case 'f': + if (!current.compare("friendlyName")) + m_device.friendlyName = std::move(str); + break; + case 'm': + if (!current.compare("manufacturer")) + m_device.manufacturer = std::move(str); + else if (!current.compare("modelName")) + m_device.modelName = std::move(str); + break; + case 's': + if (!current.compare("serviceType")) + m_tservice.serviceType = std::move(str); + else if (!current.compare("serviceId")) + m_tservice.serviceId = std::move(str); + case 'S': + if (!current.compare("SCPDURL")) + m_tservice.SCPDURL = std::move(str); + break; + case 'U': + if (!current.compare("UDN")) + m_device.UDN = std::move(str); + else if (!current.compare("URLBase")) + m_device.URLBase = std::move(str); + break; + } + } +}; + +bool +UPnPDevice::Parse(const std::string &url, const char *description, + Error &error) +{ + { + UPnPDeviceParser mparser(*this); + if (!mparser.Parse(description, strlen(description), + true, error)) + return false; + } + + if (URLBase.empty()) { + // The standard says that if the URLBase value is empty, we should use + // the url the description was retrieved from. However this is + // sometimes something like http://host/desc.xml, sometimes something + // like http://host/ + + if (url.size() < 8) { + // ??? + URLBase = url; + } else { + auto hostslash = url.find_first_of("/", 7); + if (hostslash == std::string::npos || hostslash == url.size()-1) { + URLBase = url; + } else { + URLBase = path_getfather(url); + } + } + } + + return true; +} diff --git a/src/db/upnp/Device.hxx b/src/db/upnp/Device.hxx new file mode 100644 index 000000000..d03ad24f6 --- /dev/null +++ b/src/db/upnp/Device.hxx @@ -0,0 +1,93 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * http://www.musicpd.org + * + * 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. + * + * 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. + */ + +#ifndef _UPNPDEV_HXX_INCLUDED_ +#define _UPNPDEV_HXX_INCLUDED_ + +#include <vector> +#include <string> + +class Error; + +/** + * UPnP Description phase: interpreting the device description which we + * downloaded from the URL obtained by the discovery phase. + */ + +/** + * Data holder for a UPnP service, parsed from the XML description + * downloaded after discovery yielded its URL. + */ +struct UPnPService { + // e.g. urn:schemas-upnp-org:service:ConnectionManager:1 + std::string serviceType; + // Unique Id inside device: e.g here THE ConnectionManager + std::string serviceId; // e.g. urn:upnp-org:serviceId:ConnectionManager + std::string SCPDURL; // Service description URL. e.g.: cm.xml + std::string controlURL; // e.g.: /upnp/control/cm + std::string eventSubURL; // e.g.: /upnp/event/cm + + void clear() + { + serviceType.clear(); + serviceId.clear(); + SCPDURL.clear(); + controlURL.clear(); + eventSubURL.clear(); + } +}; + +/** + * Data holder for a UPnP device, parsed from the XML description obtained + * during discovery. + * A device may include several services. To be of interest to us, + * one of them must be a ContentDirectory. + */ +class UPnPDevice { +public: + // e.g. urn:schemas-upnp-org:device:MediaServer:1 + std::string deviceType; + // e.g. MediaTomb + std::string friendlyName; + // Unique device number. This should match the deviceID in the + // discovery message. e.g. uuid:a7bdcd12-e6c1-4c7e-b588-3bbc959eda8d + std::string UDN; + // Base for all relative URLs. e.g. http://192.168.4.4:49152/ + std::string URLBase; + // Manufacturer: e.g. D-Link, PacketVideo ("manufacturer") + std::string manufacturer; + // Model name: e.g. MediaTomb, DNS-327L ("modelName") + std::string modelName; + // Services provided by this device. + std::vector<UPnPService> services; + + UPnPDevice() = default; + UPnPDevice(const UPnPDevice &) = delete; + UPnPDevice(UPnPDevice &&) = default; + UPnPDevice &operator=(UPnPDevice &&) = default; + + /** Build device from xml description downloaded from discovery + * @param url where the description came from + * @param description the xml device description + */ + bool Parse(const std::string &url, const char *description, + Error &error); +}; + +#endif /* _UPNPDEV_HXX_INCLUDED_ */ diff --git a/src/db/upnp/Directory.cxx b/src/db/upnp/Directory.cxx new file mode 100644 index 000000000..ce0a86fda --- /dev/null +++ b/src/db/upnp/Directory.cxx @@ -0,0 +1,194 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * http://www.musicpd.org + * + * 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. + * + * 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. + */ + +#include "config.h" +#include "Directory.hxx" +#include "Util.hxx" +#include "Expat.hxx" +#include "Tags.hxx" +#include "tag/TagBuilder.hxx" +#include "tag/TagTable.hxx" + +#include <algorithm> +#include <string> +#include <vector> + +#include <string.h> + +gcc_pure +static UPnPDirObject::ItemClass +ParseItemClass(const char *name) +{ + if (strcmp(name, "object.item.audioItem.musicTrack") == 0) + return UPnPDirObject::ItemClass::MUSIC; + else if (strcmp(name, "object.item.playlistItem") == 0) + return UPnPDirObject::ItemClass::PLAYLIST; + else + return UPnPDirObject::ItemClass::UNKNOWN; +} + +gcc_pure +static int +ParseDuration(const std::string &duration) +{ + const auto v = stringToTokens(duration, ":"); + if (v.size() != 3) + return 0; + return atoi(v[0].c_str())*3600 + atoi(v[1].c_str())*60 + atoi(v[2].c_str()); +} + +/** + * Transform titles to turn '/' into '_' to make them acceptable path + * elements. There is a very slight risk of collision in doing + * this. Twonky returns directory names (titles) like 'Artist/Album'. + */ +gcc_pure +static std::string +titleToPathElt(std::string &&s) +{ + std::replace(s.begin(), s.end(), '/', '_'); + return s; +} + +/** + * An XML parser which builds directory contents from DIDL lite input. + */ +class UPnPDirParser final : public CommonExpatParser { + std::vector<std::string> m_path; + UPnPDirObject m_tobj; + TagBuilder tag; + +public: + UPnPDirParser(UPnPDirContent& dir) + :m_dir(dir) + { + } + UPnPDirContent& m_dir; + +protected: + virtual void StartElement(const XML_Char *name, const XML_Char **attrs) + { + m_path.push_back(name); + + switch (name[0]) { + case 'c': + if (!strcmp(name, "container")) { + m_tobj.clear(); + m_tobj.type = UPnPDirObject::Type::CONTAINER; + + const char *id = GetAttribute(attrs, "id"); + if (id != nullptr) + m_tobj.m_id = id; + + const char *pid = GetAttribute(attrs, "parentID"); + if (pid != nullptr) + m_tobj.m_pid = pid; + } + break; + + case 'i': + if (!strcmp(name, "item")) { + m_tobj.clear(); + m_tobj.type = UPnPDirObject::Type::ITEM; + + const char *id = GetAttribute(attrs, "id"); + if (id != nullptr) + m_tobj.m_id = id; + + const char *pid = GetAttribute(attrs, "parentID"); + if (pid != nullptr) + m_tobj.m_pid = pid; + } + break; + + case 'r': + if (!strcmp(name, "res")) { + // <res protocolInfo="http-get:*:audio/mpeg:*" size="5171496" + // bitrate="24576" duration="00:03:35" sampleFrequency="44100" + // nrAudioChannels="2"> + + const char *duration = + GetAttribute(attrs, "duration"); + if (duration != nullptr) + tag.SetTime(ParseDuration(duration)); + } + + break; + } + } + + bool checkobjok() { + if (m_tobj.m_id.empty() || m_tobj.m_pid.empty() || + m_tobj.name.empty() || + (m_tobj.type == UPnPDirObject::Type::ITEM && + m_tobj.item_class == UPnPDirObject::ItemClass::UNKNOWN)) + return false; + + return true; + } + + virtual void EndElement(const XML_Char *name) + { + if ((!strcmp(name, "container") || !strcmp(name, "item")) && + checkobjok()) { + tag.Commit(m_tobj.tag); + m_dir.objects.push_back(std::move(m_tobj)); + } + + m_path.pop_back(); + } + + virtual void CharacterData(const XML_Char *s, int len) + { + const auto ¤t = m_path.back(); + std::string str = trimstring(s, len); + + TagType type = tag_table_lookup(upnp_tags, + current.c_str()); + if (type != TAG_NUM_OF_ITEM_TYPES) { + tag.AddItem(type, str.c_str()); + + if (type == TAG_TITLE) + m_tobj.name = titleToPathElt(std::move(str)); + + return; + } + + switch (current[0]) { + case 'r': + if (!current.compare("res")) { + m_tobj.url = std::move(str); + } + break; + case 'u': + if (current == "upnp:class") { + m_tobj.item_class = ParseItemClass(str.c_str()); + break; + } + break; + } + } +}; + +bool +UPnPDirContent::parse(const char *input, Error &error) +{ + UPnPDirParser parser(*this); + return parser.Parse(input, strlen(input), true, error); +} diff --git a/src/db/upnp/Directory.hxx b/src/db/upnp/Directory.hxx new file mode 100644 index 000000000..8858c9325 --- /dev/null +++ b/src/db/upnp/Directory.hxx @@ -0,0 +1,64 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * http://www.musicpd.org + * + * 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. + * + * 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. + */ + +#ifndef MPD_UPNP_DIRECTORY_HXX +#define MPD_UPNP_DIRECTORY_HXX + +#include "Object.hxx" +#include "Compiler.h" + +#include <string> +#include <vector> + +class Error; + +/** + * Image of a MediaServer Directory Service container (directory), + * possibly containing items and subordinate containers. + */ +class UPnPDirContent { +public: + std::vector<UPnPDirObject> objects; + + gcc_pure + UPnPDirObject *FindObject(const char *name) { + for (auto &o : objects) + if (o.name == name) + return &o; + + return nullptr; + } + + /** + * Parse from DIDL-Lite XML data. + * + * Normally only used by ContentDirectoryService::readDir() + * This is cumulative: in general, the XML data is obtained in + * several documents corresponding to (offset,count) slices of the + * directory (container). parse() can be called repeatedly with + * the successive XML documents and will accumulate entries in the item + * and container vectors. This makes more sense if the different + * chunks are from the same container, but given that UPnP Ids are + * actually global, nothing really bad will happen if you mix + * up... + */ + bool parse(const char *didltext, Error &error); +}; + +#endif /* _UPNPDIRCONTENT_H_X_INCLUDED_ */ diff --git a/src/db/upnp/Discovery.cxx b/src/db/upnp/Discovery.cxx new file mode 100644 index 000000000..085e5c336 --- /dev/null +++ b/src/db/upnp/Discovery.cxx @@ -0,0 +1,289 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * http://www.musicpd.org + * + * 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. + * + * 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. + */ + +#include "config.h" +#include "Discovery.hxx" +#include "Domain.hxx" +#include "ContentDirectoryService.hxx" +#include "upnpplib.hxx" +#include "system/Clock.hxx" +#include "Log.hxx" + +#include <upnp/upnptools.h> + +#include <string.h> + +// The service type string we are looking for. +static const char *const ContentDirectorySType = "urn:schemas-upnp-org:service:ContentDirectory:1"; + +// We don't include a version in comparisons, as we are satisfied with +// version 1 +gcc_pure +static bool +isCDService(const char *st) +{ + const size_t sz = strlen(ContentDirectorySType) - 2; + return memcmp(ContentDirectorySType, st, sz) == 0; +} + +// The type of device we're asking for in search +static const char *const MediaServerDType = "urn:schemas-upnp-org:device:MediaServer:1"; + +gcc_pure +static bool +isMSDevice(const char *st) +{ + const size_t sz = strlen(MediaServerDType) - 2; + return memcmp(MediaServerDType, st, sz) == 0; +} + +inline void +UPnPDeviceDirectory::discoExplorer() +{ + for (;;) { + DiscoveredTask *tsk = 0; + if (!discoveredQueue.take(tsk)) { + discoveredQueue.workerExit(); + return; + } + + // Device signals its existence and well-being. Perform the + // UPnP "description" phase by downloading and decoding the + // description document. + char *buf; + // LINE_SIZE is defined by libupnp's upnp.h... + char contentType[LINE_SIZE]; + int code = UpnpDownloadUrlItem(tsk->url.c_str(), &buf, contentType); + if (code != UPNP_E_SUCCESS) { + continue; + } + + // Update or insert the device + ContentDirectoryDescriptor d(MonotonicClockS(), tsk->expires); + + { + Error error2; + bool success = d.Parse(tsk->url, buf, error2); + free(buf); + if (!success) { + delete tsk; + LogError(error2); + continue; + } + } + + const ScopeLock protect(mutex); + directories[std::move(tsk->deviceId)] = std::move(d); + + delete tsk; + } +} + +void * +UPnPDeviceDirectory::discoExplorer(void *ctx) +{ + UPnPDeviceDirectory &directory = *(UPnPDeviceDirectory *)ctx; + directory.discoExplorer(); + return (void*)1; +} + +inline int +UPnPDeviceDirectory::OnAlive(Upnp_Discovery *disco) +{ + if (isMSDevice(disco->DeviceType) || + isCDService(disco->ServiceType)) { + DiscoveredTask *tp = new DiscoveredTask(disco); + if (discoveredQueue.put(tp)) + return UPNP_E_FINISH; + } + + return UPNP_E_SUCCESS; +} + +inline int +UPnPDeviceDirectory::OnByeBye(Upnp_Discovery *disco) +{ + + if (isMSDevice(disco->DeviceType) || + isCDService(disco->ServiceType)) { + // Device signals it is going off. + const ScopeLock protect(mutex); + auto it = directories.find(disco->DeviceId); + if (it != directories.end()) + directories.erase(it); + } + + return UPNP_E_SUCCESS; +} + +// This gets called for all libupnp asynchronous events, in a libupnp +// thread context. +// Example: ContentDirectories appearing and disappearing from the network +// We queue a task for our worker thread(s) +inline int +UPnPDeviceDirectory::cluCallBack(Upnp_EventType et, void *evp) +{ + switch (et) { + case UPNP_DISCOVERY_SEARCH_RESULT: + case UPNP_DISCOVERY_ADVERTISEMENT_ALIVE: + { + Upnp_Discovery *disco = (Upnp_Discovery *)evp; + return OnAlive(disco); + } + + case UPNP_DISCOVERY_ADVERTISEMENT_BYEBYE: + { + Upnp_Discovery *disco = (Upnp_Discovery *)evp; + return OnByeBye(disco); + } + + default: + // Ignore other events for now + break; + } + + return UPNP_E_SUCCESS; +} + +bool +UPnPDeviceDirectory::expireDevices(Error &error) +{ + const ScopeLock protect(mutex); + const unsigned now = MonotonicClockS(); + bool didsomething = false; + + for (auto it = directories.begin(); + it != directories.end();) { + if (now > it->second.expires) { + it = directories.erase(it); + didsomething = true; + } else { + it++; + } + } + + if (didsomething) + return search(error); + + return true; +} + +UPnPDeviceDirectory::UPnPDeviceDirectory(LibUPnP *_lib) + :lib(_lib), + discoveredQueue("DiscoveredQueue"), + m_searchTimeout(2), m_lastSearch(0) +{ +} + +bool +UPnPDeviceDirectory::Start(Error &error) +{ + if (!discoveredQueue.start(1, discoExplorer, this)) { + error.Set(upnp_domain, "Discover work queue start failed"); + return false; + } + + lib->SetHandler([this](Upnp_EventType type, void *event){ + cluCallBack(type, event); + }); + + return search(error); +} + +bool +UPnPDeviceDirectory::search(Error &error) +{ + const unsigned now = MonotonicClockS(); + if (now - m_lastSearch < 10) + return true; + m_lastSearch = now; + + // We search both for device and service just in case. + int code = UpnpSearchAsync(lib->getclh(), m_searchTimeout, + ContentDirectorySType, lib); + if (code != UPNP_E_SUCCESS) { + error.Format(upnp_domain, code, + "UpnpSearchAsync() failed: %s", + UpnpGetErrorMessage(code)); + return false; + } + + code = UpnpSearchAsync(lib->getclh(), m_searchTimeout, + MediaServerDType, lib); + if (code != UPNP_E_SUCCESS) { + error.Format(upnp_domain, code, + "UpnpSearchAsync() failed: %s", + UpnpGetErrorMessage(code)); + return false; + } + + return true; +} + +bool +UPnPDeviceDirectory::getDirServices(std::vector<ContentDirectoryService> &out, + Error &error) +{ + // Has locking, do it before our own lock + if (!expireDevices(error)) + return false; + + const ScopeLock protect(mutex); + + for (auto dit = directories.begin(); + dit != directories.end(); dit++) { + for (const auto &service : dit->second.device.services) { + if (isCDService(service.serviceType.c_str())) { + out.emplace_back(dit->second.device, service); + } + } + } + + return true; +} + +bool +UPnPDeviceDirectory::getServer(const char *friendlyName, + ContentDirectoryService &server, + Error &error) +{ + // Has locking, do it before our own lock + if (!expireDevices(error)) + return false; + + const ScopeLock protect(mutex); + + for (const auto &i : directories) { + const auto &device = i.second.device; + + if (device.friendlyName != friendlyName) + continue; + + for (const auto &service : device.services) { + if (isCDService(service.serviceType.c_str())) { + server = ContentDirectoryService(device, + service); + return true; + } + } + } + + error.Set(upnp_domain, "Server not found"); + return false; +} diff --git a/src/db/upnp/Discovery.hxx b/src/db/upnp/Discovery.hxx new file mode 100644 index 000000000..a45163e9b --- /dev/null +++ b/src/db/upnp/Discovery.hxx @@ -0,0 +1,145 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * http://www.musicpd.org + * + * 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. + * + * 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. + */ + +#ifndef _UPNPPDISC_H_X_INCLUDED_ +#define _UPNPPDISC_H_X_INCLUDED_ + +#include "Device.hxx" +#include "WorkQueue.hxx" +#include "thread/Mutex.hxx" +#include "util/Error.hxx" + +#include <upnp/upnp.h> + +#include <map> +#include <vector> +#include <string> + +class LibUPnP; +class ContentDirectoryService; + +/** + * Manage UPnP discovery and maintain a directory of active devices. Singleton. + * + * We are only interested in MediaServers with a ContentDirectory service + * for now, but this could be made more general, by removing the filtering. + */ +class UPnPDeviceDirectory { + /** + * Each appropriate discovery event (executing in a libupnp thread + * context) queues the following task object for processing by the + * discovery thread. + */ + struct DiscoveredTask { + std::string url; + std::string deviceId; + unsigned expires; // Seconds valid + + DiscoveredTask(const Upnp_Discovery *disco) + :url(disco->Location), + deviceId(disco->DeviceId), + expires(disco->Expires) {} + }; + + /** + * Descriptor for one device having a Content Directory + * service found on the network. + */ + class ContentDirectoryDescriptor { + public: + UPnPDevice device; + + /** + * The MonotonicClockS() time stamp when this device + * expires. + */ + unsigned expires; + + ContentDirectoryDescriptor() = default; + + ContentDirectoryDescriptor(unsigned last, int exp) + :expires(last + exp + 20) {} + + bool Parse(const std::string &url, const char *description, + Error &_error) { + return device.Parse(url, description, _error); + } + }; + + LibUPnP *const lib; + + Mutex mutex; + std::map<std::string, ContentDirectoryDescriptor> directories; + WorkQueue<DiscoveredTask *> discoveredQueue; + + /** + * The UPnP device search timeout, which should actually be + * called delay because it's the base of a random delay that + * the devices apply to avoid responding all at the same time. + */ + int m_searchTimeout; + + /** + * The MonotonicClockS() time stamp of the last search. + */ + unsigned m_lastSearch; + +public: + UPnPDeviceDirectory(LibUPnP *_lib); + + UPnPDeviceDirectory(const UPnPDeviceDirectory &) = delete; + UPnPDeviceDirectory& operator=(const UPnPDeviceDirectory &) = delete; + + bool Start(Error &error); + + /** Retrieve the directory services currently seen on the network */ + bool getDirServices(std::vector<ContentDirectoryService> &, Error &); + + /** + * Get server by friendly name. + */ + bool getServer(const char *friendlyName, + ContentDirectoryService &server, + Error &error); + +private: + bool search(Error &error); + + /** + * Look at the devices and get rid of those which have not + * been seen for too long. We do this when listing the top + * directory. + */ + bool expireDevices(Error &error); + + /** + * Worker routine for the discovery queue. Get messages about + * devices appearing and disappearing, and update the + * directory pool accordingly. + */ + static void *discoExplorer(void *); + void discoExplorer(); + + int OnAlive(Upnp_Discovery *disco); + int OnByeBye(Upnp_Discovery *disco); + int cluCallBack(Upnp_EventType et, void *evp); +}; + + +#endif /* _UPNPPDISC_H_X_INCLUDED_ */ diff --git a/src/db/upnp/Domain.cxx b/src/db/upnp/Domain.cxx new file mode 100644 index 000000000..010d4c7c2 --- /dev/null +++ b/src/db/upnp/Domain.cxx @@ -0,0 +1,23 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * http://www.musicpd.org + * + * 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. + * + * 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. + */ + +#include "Domain.hxx" +#include "util/Domain.hxx" + +const Domain upnp_domain("upnp"); diff --git a/src/db/upnp/Domain.hxx b/src/db/upnp/Domain.hxx new file mode 100644 index 000000000..ec01ef735 --- /dev/null +++ b/src/db/upnp/Domain.hxx @@ -0,0 +1,27 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * http://www.musicpd.org + * + * 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. + * + * 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. + */ + +#ifndef MPD_UPNP_DOMAIN_HXX +#define MPD_UPNP_DOMAIN_HXX + +class Domain; + +extern const Domain upnp_domain; + +#endif diff --git a/src/db/upnp/Object.hxx b/src/db/upnp/Object.hxx new file mode 100644 index 000000000..65a6b323f --- /dev/null +++ b/src/db/upnp/Object.hxx @@ -0,0 +1,82 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * http://www.musicpd.org + * + * 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. + * + * 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. + */ + +#ifndef MPD_UPNP_OBJECT_HXX +#define MPD_UPNP_OBJECT_HXX + +#include "tag/Tag.hxx" + +#include <string> + +/** + * UpnP Media Server directory entry, converted from XML data. + * + * This is a dumb data holder class, a struct with helpers. + */ +class UPnPDirObject { +public: + enum class Type { + UNKNOWN, + ITEM, + CONTAINER, + }; + + // There are actually several kinds of containers: + // object.container.storageFolder, object.container.person, + // object.container.playlistContainer etc., but they all seem to + // behave the same as far as we're concerned. Otoh, musicTrack + // items are special to us, and so should playlists, but I've not + // seen one of the latter yet (servers seem to use containers for + // playlists). + enum class ItemClass { + UNKNOWN, + MUSIC, + PLAYLIST, + }; + + std::string m_id; // ObjectId + std::string m_pid; // Parent ObjectId + std::string url; + + /** + * A copy of "dc:title" sanitized as a file name. + */ + std::string name; + + Type type; + ItemClass item_class; + + Tag tag; + + UPnPDirObject() = default; + UPnPDirObject(UPnPDirObject &&) = default; + UPnPDirObject &operator=(UPnPDirObject &&) = default; + + void clear() + { + m_id.clear(); + m_pid.clear(); + url.clear(); + type = Type::UNKNOWN; + item_class = ItemClass::UNKNOWN; + tag.Clear(); + } +}; + +#endif /* _UPNPDIRCONTENT_H_X_INCLUDED_ */ diff --git a/src/db/upnp/Tags.cxx b/src/db/upnp/Tags.cxx new file mode 100644 index 000000000..fd65df4d0 --- /dev/null +++ b/src/db/upnp/Tags.cxx @@ -0,0 +1,33 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * http://www.musicpd.org + * + * 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. + * + * 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. + */ + +#include "config.h" +#include "Tags.hxx" +#include "tag/TagTable.hxx" + +const struct tag_table upnp_tags[] = { + { "upnp:artist", TAG_ARTIST }, + { "upnp:album", TAG_ALBUM }, + { "upnp:originalTrackNumber", TAG_TRACK }, + { "upnp:genre", TAG_GENRE }, + { "dc:title", TAG_TITLE }, + + /* sentinel */ + { nullptr, TAG_NUM_OF_ITEM_TYPES } +}; diff --git a/src/db/upnp/Tags.hxx b/src/db/upnp/Tags.hxx new file mode 100644 index 000000000..ec6d18478 --- /dev/null +++ b/src/db/upnp/Tags.hxx @@ -0,0 +1,28 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * http://www.musicpd.org + * + * 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. + * + * 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. + */ + +#ifndef MPD_UPNP_TAGS_HXX +#define MPD_UPNP_TAGS_HXX + +/** + * Map UPnP property names to MPD tags. + */ +extern const struct tag_table upnp_tags[]; + +#endif diff --git a/src/db/upnp/Util.cxx b/src/db/upnp/Util.cxx new file mode 100644 index 000000000..fc9ef6281 --- /dev/null +++ b/src/db/upnp/Util.cxx @@ -0,0 +1,183 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * http://www.musicpd.org + * + * 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. + * + * 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. + */ + +#include "Util.hxx" +#include "util/CharUtil.hxx" + +#include <string> +#include <map> +#include <vector> +#include <set> + +#include <upnp/ixml.h> + +/** Get rid of white space at both ends */ +std::string +trimstring(const char *p, size_t length) +{ + while (length > 0 && IsWhitespaceOrNull(p[length - 1])) + --length; + + const char *end = p + length; + while (p != end && IsWhitespaceOrNull(*p)) + ++p; + + return std::string(p, end); +} + +std::string +caturl(const std::string &s1, const std::string &s2) +{ + std::string out(s1); + if (out[out.size()-1] == '/') { + if (s2[0] == '/') + out.erase(out.size()-1); + } else { + if (s2[0] != '/') + out.push_back('/'); + } + out += s2; + return out; +} + +static void +path_catslash(std::string &s) +{ + if (s.empty() || s[s.length() - 1] != '/') + s += '/'; +} + +std::string +path_getfather(const std::string &s) +{ + std::string father = s; + + // ?? + if (father.empty()) + return "./"; + + if (father[father.length() - 1] == '/') { + // Input ends with /. Strip it, handle special case for root + if (father.length() == 1) + return father; + father.erase(father.length()-1); + } + + auto slp = father.rfind('/'); + if (slp == std::string::npos) + return "./"; + + father.erase(slp); + path_catslash(father); + return father; +} + +std::vector<std::string> +stringToTokens(const std::string &str, + const char *delims, bool skipinit) +{ + std::vector<std::string> tokens; + + std::string::size_type startPos = 0; + + // Skip initial delims, return empty if this eats all. + if (skipinit && + (startPos = str.find_first_not_of(delims, 0)) == std::string::npos) + return tokens; + + while (startPos < str.size()) { + // Find next delimiter or end of string (end of token) + auto pos = str.find_first_of(delims, startPos); + + // Add token to the vector and adjust start + if (pos == std::string::npos) { + tokens.push_back(str.substr(startPos)); + break; + } else if (pos == startPos) { + // Dont' push empty tokens after first + if (tokens.empty()) + tokens.push_back(std::string()); + startPos = ++pos; + } else { + tokens.push_back(str.substr(startPos, pos - startPos)); + startPos = ++pos; + } + } + + return tokens; +} + +template <class T> +bool +csvToStrings(const std::string &s, T &tokens) +{ + std::string current; + tokens.clear(); + enum states {TOKEN, ESCAPE}; + states state = TOKEN; + for (unsigned int i = 0; i < s.length(); i++) { + switch (s[i]) { + case ',': + switch(state) { + case TOKEN: + tokens.insert(tokens.end(), current); + current.clear(); + continue; + case ESCAPE: + current += ','; + state = TOKEN; + continue; + } + break; + case '\\': + switch(state) { + case TOKEN: + state=ESCAPE; + continue; + case ESCAPE: + current += '\\'; + state = TOKEN; + continue; + } + break; + + default: + switch(state) { + case ESCAPE: + state = TOKEN; + break; + case TOKEN: + break; + } + current += s[i]; + } + } + switch(state) { + case TOKEN: + tokens.insert(tokens.end(), current); + break; + case ESCAPE: + return false; + } + return true; +} + +//template bool csvToStrings<list<string> >(const string &, list<string> &); +template bool csvToStrings<std::vector<std::string> >(const std::string &, std::vector<std::string> &); +template bool csvToStrings<std::set<std::string> >(const std::string &, std::set<std::string> &); diff --git a/src/db/upnp/Util.hxx b/src/db/upnp/Util.hxx new file mode 100644 index 000000000..ba5633331 --- /dev/null +++ b/src/db/upnp/Util.hxx @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * http://www.musicpd.org + * + * 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. + * + * 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. + */ + +#ifndef MPD_UPNP_UTIL_HXX +#define MPD_UPNP_UTIL_HXX + +#include "Compiler.h" + +#include <string> +#include <vector> + +std::string +caturl(const std::string& s1, const std::string& s2); + +gcc_pure +std::string +trimstring(const char *p, size_t length); + +std::string +path_getfather(const std::string &s); + +gcc_pure +std::vector<std::string> +stringToTokens(const std::string &str, + const char *delims = "/", bool skipinit = true); + +template <class T> +bool csvToStrings(const std::string& s, T &tokens); + +#endif /* _UPNPP_H_X_INCLUDED_ */ diff --git a/src/db/upnp/WorkQueue.hxx b/src/db/upnp/WorkQueue.hxx new file mode 100644 index 000000000..fe8ce53f9 --- /dev/null +++ b/src/db/upnp/WorkQueue.hxx @@ -0,0 +1,206 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * http://www.musicpd.org + * + * 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. + * + * 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. + */ + +#ifndef _WORKQUEUE_H_INCLUDED_ +#define _WORKQUEUE_H_INCLUDED_ + +#include "thread/Mutex.hxx" +#include "thread/Cond.hxx" + +#include <assert.h> +#include <pthread.h> + +#include <string> +#include <queue> + +#define LOGINFO(X) +#define LOGERR(X) + +/** + * A WorkQueue manages the synchronisation around a queue of work items, + * where a number of client threads queue tasks and a number of worker + * threads take and execute them. The goal is to introduce some level + * of parallelism between the successive steps of a previously single + * threaded pipeline. For example data extraction / data preparation / index + * update, but this could have other uses. + * + * There is no individual task status return. In case of fatal error, + * the client or worker sets an end condition on the queue. A second + * queue could conceivably be used for returning individual task + * status. + */ +template <class T> +class WorkQueue { + // Configuration + const std::string name; + + // Status + // Worker threads having called exit + unsigned n_workers_exited; + bool ok; + + unsigned n_threads; + pthread_t *threads; + + // Synchronization + std::queue<T> queue; + Cond client_cond; + Cond worker_cond; + Mutex mutex; + +public: + /** Create a WorkQueue + * @param name for message printing + * @param hi number of tasks on queue before clients blocks. Default 0 + * meaning no limit. hi == -1 means that the queue is disabled. + * @param lo minimum count of tasks before worker starts. Default 1. + */ + WorkQueue(const char *_name) + :name(_name), + n_workers_exited(0), + ok(false), + n_threads(0), threads(nullptr) + { + } + + ~WorkQueue() { + setTerminateAndWait(); + } + + /** Start the worker threads. + * + * @param nworkers number of threads copies to start. + * @param start_routine thread function. It should loop + * taking (QueueWorker::take()) and executing tasks. + * @param arg initial parameter to thread function. + * @return true if ok. + */ + bool start(unsigned nworkers, void *(*workproc)(void *), void *arg) + { + const ScopeLock protect(mutex); + + assert(nworkers > 0); + assert(!ok); + assert(n_threads == 0); + assert(threads == nullptr); + + n_threads = nworkers; + threads = new pthread_t[n_threads]; + + for (unsigned i = 0; i < nworkers; i++) { + int err; + if ((err = pthread_create(&threads[i], 0, workproc, arg))) { + LOGERR(("WorkQueue:%s: pthread_create failed, err %d\n", + name.c_str(), err)); + return false; + } + } + + ok = true; + return true; + } + + /** Add item to work queue, called from client. + * + * Sleeps if there are already too many. + */ + template<typename U> + bool put(U &&u) + { + const ScopeLock protect(mutex); + + queue.emplace(std::forward<U>(u)); + + // Just wake one worker, there is only one new task. + worker_cond.signal(); + + return true; + } + + + /** Tell the workers to exit, and wait for them. + */ + void setTerminateAndWait() + { + const ScopeLock protect(mutex); + + // Wait for all worker threads to have called workerExit() + ok = false; + while (n_workers_exited < n_threads) { + worker_cond.broadcast(); + client_cond.wait(mutex); + } + + // Perform the thread joins and compute overall status + // Workers return (void*)1 if ok + for (unsigned i = 0; i < n_threads; ++i) { + void *status; + pthread_join(threads[i], &status); + } + + delete[] threads; + threads = nullptr; + n_threads = 0; + + // Reset to start state. + n_workers_exited = 0; + } + + /** Take task from queue. Called from worker. + * + * Sleeps if there are not enough. Signal if we go to sleep on empty + * queue: client may be waiting for our going idle. + */ + bool take(T &tp) + { + const ScopeLock protect(mutex); + + if (!ok) + return false; + + while (queue.empty()) { + worker_cond.wait(mutex); + if (!ok) + return false; + } + + tp = std::move(queue.front()); + queue.pop(); + return true; + } + + /** Advertise exit and abort queue. Called from worker + * + * This would happen after an unrecoverable error, or when + * the queue is terminated by the client. Workers never exit normally, + * except when the queue is shut down (at which point ok is set to + * false by the shutdown code anyway). The thread must return/exit + * immediately after calling this. + */ + void workerExit() + { + const ScopeLock protect(mutex); + + n_workers_exited++; + ok = false; + client_cond.broadcast(); + } +}; + +#endif /* _WORKQUEUE_H_INCLUDED_ */ diff --git a/src/db/upnp/ixmlwrap.cxx b/src/db/upnp/ixmlwrap.cxx new file mode 100644 index 000000000..6a2829cf9 --- /dev/null +++ b/src/db/upnp/ixmlwrap.cxx @@ -0,0 +1,44 @@ +/* Copyright (C) 2013 J.F.Dockes + * 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. + * + * 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., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#include "ixmlwrap.hxx" + +namespace ixmlwrap { + +const char * +getFirstElementValue(IXML_Document *doc, const char *name) +{ + const char *ret = nullptr; + IXML_NodeList *nodes = + ixmlDocument_getElementsByTagName(doc, name); + + if (nodes) { + IXML_Node *first = ixmlNodeList_item(nodes, 0); + if (first) { + IXML_Node *dnode = ixmlNode_getFirstChild(first); + if (dnode) { + ret = ixmlNode_getNodeValue(dnode); + } + } + + ixmlNodeList_free(nodes); + } + + return ret; +} + +} diff --git a/src/db/upnp/ixmlwrap.hxx b/src/db/upnp/ixmlwrap.hxx new file mode 100644 index 000000000..0d519a323 --- /dev/null +++ b/src/db/upnp/ixmlwrap.hxx @@ -0,0 +1,35 @@ +/* Copyright (C) 2013 J.F.Dockes + * 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. + * + * 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., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ +#ifndef _IXMLWRAP_H_INCLUDED_ +#define _IXMLWRAP_H_INCLUDED_ + +#include <upnp/ixml.h> + +#include <string> + +namespace ixmlwrap { + /** + * Retrieve the text content for the first element of given + * name. Returns nullptr if the element does not + * contain a text node + */ + const char *getFirstElementValue(IXML_Document *doc, + const char *name); + +}; + +#endif /* _IXMLWRAP_H_INCLUDED_ */ diff --git a/src/db/upnp/upnpplib.cxx b/src/db/upnp/upnpplib.cxx new file mode 100644 index 000000000..27b4e0564 --- /dev/null +++ b/src/db/upnp/upnpplib.cxx @@ -0,0 +1,75 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * http://www.musicpd.org + * + * 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. + * + * 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. + */ + +#include "config.h" +#include "upnpplib.hxx" +#include "Domain.hxx" +#include "Log.hxx" + +#include <upnp/ixml.h> +#include <upnp/upnptools.h> + +static LibUPnP *theLib; + +LibUPnP::LibUPnP() +{ + auto code = UpnpInit(0, 0); + if (code != UPNP_E_SUCCESS) { + init_error.Format(upnp_domain, code, + "UpnpInit() failed: %s", + UpnpGetErrorMessage(code)); + return; + } + + UpnpSetMaxContentLength(2000*1024); + + code = UpnpRegisterClient(o_callback, (void *)this, &m_clh); + if (code != UPNP_E_SUCCESS) { + init_error.Format(upnp_domain, code, + "UpnpRegisterClient() failed: %s", + UpnpGetErrorMessage(code)); + return; + } + + // Servers sometimes make error (e.g.: minidlna returns bad utf-8) + ixmlRelaxParser(1); +} + +int +LibUPnP::o_callback(Upnp_EventType et, void* evp, void* cookie) +{ + LibUPnP *ulib = (LibUPnP *)cookie; + if (ulib == nullptr) { + // Because the asyncsearch calls uses a null cookie. + ulib = theLib; + } + + if (ulib->handler) + ulib->handler(et, evp); + + return UPNP_E_SUCCESS; +} + +LibUPnP::~LibUPnP() +{ + int error = UpnpFinish(); + if (error != UPNP_E_SUCCESS) + FormatError(upnp_domain, "UpnpFinish() failed: %s", + UpnpGetErrorMessage(error)); +} diff --git a/src/db/upnp/upnpplib.hxx b/src/db/upnp/upnpplib.hxx new file mode 100644 index 000000000..6759aa16d --- /dev/null +++ b/src/db/upnp/upnpplib.hxx @@ -0,0 +1,70 @@ +/* + * Copyright (C) 2003-2014 The Music Player Daemon Project + * http://www.musicpd.org + * + * 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. + * + * 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. + */ + +#ifndef _LIBUPNP_H_X_INCLUDED_ +#define _LIBUPNP_H_X_INCLUDED_ + +#include "util/Error.hxx" + +#include <upnp/upnp.h> + +#include <functional> + +/** Our link to libupnp. Initialize and keep the handle around */ +class LibUPnP { + typedef std::function<void(Upnp_EventType type, void *event)> Handler; + + Error init_error; + UpnpClient_Handle m_clh; + + Handler handler; + + static int o_callback(Upnp_EventType, void *, void *); + +public: + LibUPnP(); + + LibUPnP(const LibUPnP &) = delete; + LibUPnP &operator=(const LibUPnP &) = delete; + + ~LibUPnP(); + + /** Check state after initialization */ + bool ok() const + { + return !init_error.IsDefined(); + } + + /** Retrieve init error if state not ok */ + const Error &GetInitError() const { + return init_error; + } + + template<typename T> + void SetHandler(T &&_handler) { + handler = std::forward<T>(_handler); + } + + UpnpClient_Handle getclh() + { + return m_clh; + } +}; + +#endif /* _LIBUPNP.H_X_INCLUDED_ */ |