From 39d6816a6df4929f90eadcc976a7b9a42d84d027 Mon Sep 17 00:00:00 2001
From: Max Kellermann <max@musicpd.org>
Date: Mon, 6 Jul 2020 16:15:10 +0200
Subject: [PATCH] neighbor/upnp: roll back changes if DoOpen() fails

---
 src/neighbor/plugins/UdisksNeighborPlugin.cxx | 35 +++++++++++++------
 1 file changed, 25 insertions(+), 10 deletions(-)

diff --git a/src/neighbor/plugins/UdisksNeighborPlugin.cxx b/src/neighbor/plugins/UdisksNeighborPlugin.cxx
index 359d16ef3..f69901f6a 100644
--- a/src/neighbor/plugins/UdisksNeighborPlugin.cxx
+++ b/src/neighbor/plugins/UdisksNeighborPlugin.cxx
@@ -113,22 +113,37 @@ UdisksNeighborExplorer::DoOpen()
 
 	auto &connection = GetConnection();
 
+	/* this ugly try/catch cascade is only here because this
+	   method has no RAII for this method - TODO: improve this */
 	try {
 		Error error;
 		dbus_bus_add_match(connection, udisks_neighbor_match, error);
 		error.CheckThrow("DBus AddMatch error");
 
-		dbus_connection_add_filter(connection,
-					   HandleMessage, this,
-					   nullptr);
+		try {
+			dbus_connection_add_filter(connection,
+						   HandleMessage, this,
+						   nullptr);
 
-		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));
+			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;
+		}
 	} catch (...) {
 		dbus_glue.Destruct();
 		throw;