UdisksNeighborPlugin.cxx 7.17 KB
Newer Older
Max Kellermann's avatar
Max Kellermann committed
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2020 The Music Player Daemon Project
Max Kellermann's avatar
Max Kellermann committed
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
 * 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 "UdisksNeighborPlugin.hxx"
#include "lib/dbus/Connection.hxx"
#include "lib/dbus/Error.hxx"
23
#include "lib/dbus/Glue.hxx"
Max Kellermann's avatar
Max Kellermann committed
24
#include "lib/dbus/Message.hxx"
25
#include "lib/dbus/AsyncRequest.hxx"
Max Kellermann's avatar
Max Kellermann committed
26 27 28 29 30 31 32
#include "lib/dbus/ReadIter.hxx"
#include "lib/dbus/ObjectManager.hxx"
#include "lib/dbus/UDisks2.hxx"
#include "neighbor/NeighborPlugin.hxx"
#include "neighbor/Explorer.hxx"
#include "neighbor/Listener.hxx"
#include "neighbor/Info.hxx"
33
#include "event/Call.hxx"
Max Kellermann's avatar
Max Kellermann committed
34
#include "thread/Mutex.hxx"
35
#include "thread/SafeSingleton.hxx"
36
#include "util/Manual.hxx"
Max Kellermann's avatar
Max Kellermann committed
37 38 39 40 41
#include "Log.hxx"

#include <string>
#include <map>

42 43 44 45 46
static NeighborInfo
ToNeighborInfo(const UDisks2::Object &o) noexcept
{
	return {o.GetUri(), o.path};
}
Max Kellermann's avatar
Max Kellermann committed
47

48 49 50 51 52
static constexpr char udisks_neighbor_match[] =
	"type='signal',sender='" UDISKS2_INTERFACE "',"
	"interface='" DBUS_OM_INTERFACE "',"
	"path='" UDISKS2_PATH "'";

Max Kellermann's avatar
Max Kellermann committed
53
class UdisksNeighborExplorer final
54
	: public NeighborExplorer {
Max Kellermann's avatar
Max Kellermann committed
55

56 57
	EventLoop &event_loop;

58
	Manual<SafeSingleton<ODBus::Glue>> dbus_glue;
Max Kellermann's avatar
Max Kellermann committed
59

60
	ODBus::AsyncRequest list_request;
Max Kellermann's avatar
Max Kellermann committed
61 62 63 64 65 66 67 68 69 70 71

	/**
	 * Protects #by_uri, #by_path.
	 */
	mutable Mutex mutex;

	using ByUri = std::map<std::string, NeighborInfo>;
	ByUri by_uri;
	std::map<std::string, ByUri::iterator> by_path;

public:
72
	UdisksNeighborExplorer(EventLoop &_event_loop,
Max Kellermann's avatar
Max Kellermann committed
73
			       NeighborListener &_listener) noexcept
74
		:NeighborExplorer(_listener), event_loop(_event_loop) {}
Max Kellermann's avatar
Max Kellermann committed
75

76
	auto &GetEventLoop() const noexcept {
77 78 79 80
		return event_loop;
	}

	auto &&GetConnection() noexcept {
81
		return dbus_glue.Get()->GetConnection();
Max Kellermann's avatar
Max Kellermann committed
82 83 84 85 86 87 88 89
	}

	/* virtual methods from class NeighborExplorer */
	void Open() override;
	void Close() noexcept override;
	List GetList() const noexcept override;

private:
90 91 92
	void DoOpen();
	void DoClose() noexcept;

93
	void Insert(UDisks2::Object &&o) noexcept;
Max Kellermann's avatar
Max Kellermann committed
94 95
	void Remove(const std::string &path) noexcept;

96
	void OnListNotify(ODBus::Message reply) noexcept;
Max Kellermann's avatar
Max Kellermann committed
97 98 99 100 101 102 103 104

	DBusHandlerResult HandleMessage(DBusConnection *dbus_connection,
					DBusMessage *message) noexcept;
	static DBusHandlerResult HandleMessage(DBusConnection *dbus_connection,
					       DBusMessage *message,
					       void *user_data) noexcept;
};

105 106
inline void
UdisksNeighborExplorer::DoOpen()
Max Kellermann's avatar
Max Kellermann committed
107 108 109
{
	using namespace ODBus;

110
	dbus_glue.Construct(event_loop);
Max Kellermann's avatar
Max Kellermann committed
111

112
	auto &connection = GetConnection();
Max Kellermann's avatar
Max Kellermann committed
113

114 115
	/* this ugly try/catch cascade is only here because this
	   method has no RAII for this method - TODO: improve this */
Max Kellermann's avatar
Max Kellermann committed
116 117
	try {
		Error error;
118
		dbus_bus_add_match(connection, udisks_neighbor_match, error);
Max Kellermann's avatar
Max Kellermann committed
119 120
		error.CheckThrow("DBus AddMatch error");

121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
		try {
			dbus_connection_add_filter(connection,
						   HandleMessage, this,
						   nullptr);

			try {
				auto msg = Message::NewMethodCall(UDISKS2_INTERFACE,
								  UDISKS2_PATH,
								  DBUS_OM_INTERFACE,
								  "GetManagedObjects");
				list_request.Send(connection, *msg.Get(),
						  std::bind(&UdisksNeighborExplorer::OnListNotify,
							    this, std::placeholders::_1));
			} catch (...) {
				dbus_connection_remove_filter(connection,
							      HandleMessage,
							      this);
				throw;
			}
		} catch (...) {
			dbus_bus_remove_match(connection,
					      udisks_neighbor_match, nullptr);
			throw;
		}
Max Kellermann's avatar
Max Kellermann committed
145
	} catch (...) {
146
		dbus_glue.Destruct();
Max Kellermann's avatar
Max Kellermann committed
147 148 149 150 151
		throw;
	}
}

void
152
UdisksNeighborExplorer::Open()
Max Kellermann's avatar
Max Kellermann committed
153
{
154 155
	BlockingCall(GetEventLoop(), [this](){ DoOpen(); });
}
Max Kellermann's avatar
Max Kellermann committed
156

157 158 159
inline void
UdisksNeighborExplorer::DoClose() noexcept
{
160 161
	if (list_request) {
		list_request.Cancel();
Max Kellermann's avatar
Max Kellermann committed
162 163
	}

164 165 166 167
	auto &connection = GetConnection();

	dbus_connection_remove_filter(connection, HandleMessage, this);
	dbus_bus_remove_match(connection, udisks_neighbor_match, nullptr);
Max Kellermann's avatar
Max Kellermann committed
168

169
	dbus_glue.Destruct();
Max Kellermann's avatar
Max Kellermann committed
170 171
}

172 173 174 175 176 177
void
UdisksNeighborExplorer::Close() noexcept
{
	BlockingCall(GetEventLoop(), [this](){ DoClose(); });
}

Max Kellermann's avatar
Max Kellermann committed
178 179 180 181 182 183 184 185 186 187 188 189 190
NeighborExplorer::List
UdisksNeighborExplorer::GetList() const noexcept
{
	const std::lock_guard<Mutex> lock(mutex);

	NeighborExplorer::List result;

	for (const auto &i : by_uri)
		result.emplace_front(i.second);
	return result;
}

void
191
UdisksNeighborExplorer::Insert(UDisks2::Object &&o) noexcept
Max Kellermann's avatar
Max Kellermann committed
192 193 194
{
	assert(o.IsValid());

195
	const NeighborInfo info = ToNeighborInfo(o);
Max Kellermann's avatar
Max Kellermann committed
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228

	{
		const std::lock_guard<Mutex> protect(mutex);
		auto i = by_uri.emplace(std::make_pair(o.GetUri(), info));
		if (!i.second)
			i.first->second = info;

		by_path.emplace(std::make_pair(o.path, i.first));
		// TODO: do we need to remove a conflicting path?
	}

	listener.FoundNeighbor(info);
}

void
UdisksNeighborExplorer::Remove(const std::string &path) noexcept
{
	std::unique_lock<Mutex> lock(mutex);

	auto i = by_path.find(path);
	if (i == by_path.end())
		return;

	const auto info = std::move(i->second->second);

	by_uri.erase(i->second);
	by_path.erase(i);

	lock.unlock();
	listener.LostNeighbor(info);
}

inline void
229
UdisksNeighborExplorer::OnListNotify(ODBus::Message reply) noexcept
Max Kellermann's avatar
Max Kellermann committed
230
{
231 232 233 234
	try{
		ParseObjects(reply,
			     std::bind(&UdisksNeighborExplorer::Insert,
				       this, std::placeholders::_1));
Max Kellermann's avatar
Max Kellermann committed
235
	} catch (...) {
236 237
		LogError(std::current_exception(),
			 "Failed to parse GetManagedObjects reply");
Max Kellermann's avatar
Max Kellermann committed
238 239 240 241 242 243 244 245 246 247 248
		return;
	}
}

inline DBusHandlerResult
UdisksNeighborExplorer::HandleMessage(DBusConnection *, DBusMessage *message) noexcept
{
	using namespace ODBus;

	if (dbus_message_is_signal(message, DBUS_OM_INTERFACE,
				   "InterfacesAdded") &&
249
	    dbus_message_has_signature(message, InterfacesAddedType::value)) {
250
		RecurseInterfaceDictEntry(ReadMessageIter(*message), [this](const char *path, auto &&i){
251
				UDisks2::Object o(path);
252
				UDisks2::ParseObject(o, std::forward<decltype(i)>(i));
253
				if (o.IsValid())
254
					this->Insert(std::move(o));
255
			});
Max Kellermann's avatar
Max Kellermann committed
256 257 258 259

		return DBUS_HANDLER_RESULT_HANDLED;
	} else if (dbus_message_is_signal(message, DBUS_OM_INTERFACE,
					  "InterfacesRemoved") &&
260
		   dbus_message_has_signature(message, InterfacesRemovedType::value)) {
Max Kellermann's avatar
Max Kellermann committed
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
		Remove(ReadMessageIter(*message).GetString());
		return DBUS_HANDLER_RESULT_HANDLED;
	} else
		return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}

DBusHandlerResult
UdisksNeighborExplorer::HandleMessage(DBusConnection *connection,
				      DBusMessage *message,
				      void *user_data) noexcept
{
	auto &agent = *(UdisksNeighborExplorer *)user_data;

	return agent.HandleMessage(connection, message);
}

static std::unique_ptr<NeighborExplorer>
udisks_neighbor_create(EventLoop &event_loop,
		     NeighborListener &listener,
Rosen Penev's avatar
Rosen Penev committed
280
		     [[maybe_unused]] const ConfigBlock &block)
Max Kellermann's avatar
Max Kellermann committed
281 282 283 284 285 286 287 288
{
	return std::make_unique<UdisksNeighborExplorer>(event_loop, listener);
}

const NeighborPlugin udisks_neighbor_plugin = {
	"udisks",
	udisks_neighbor_create,
};