Helper.cxx 2.38 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2021 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13
 * 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.
14 15 16 17
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 19
 */

20
#include "Helper.hxx"
21 22 23 24
#include "Client.hxx"
#include "ErrorHandler.hxx"
#include "Publisher.hxx"
#include "Service.hxx"
25
#include "util/RuntimeError.hxx"
26
#include "Log.hxx"
27 28 29

#include <avahi-common/domain.h>

30
class SharedAvahiClient final : public Avahi::ErrorHandler {
31
public:
32
	Avahi::Client client;
33

34 35
	SharedAvahiClient(EventLoop &event_loop)
		:client(event_loop, *this) {}
36 37 38 39 40 41

	/* virtual methods from class Avahi::ErrorHandler */
	bool OnAvahiError(std::exception_ptr e) noexcept override {
		LogError(e);
		return true;
	}
42 43
};

44 45 46 47 48 49 50
static std::weak_ptr<SharedAvahiClient> shared_avahi_client;

inline
AvahiHelper::AvahiHelper(std::shared_ptr<SharedAvahiClient> _client,
			 std::unique_ptr<Avahi::Publisher> _publisher)
	:client(std::move(_client)),
	 publisher(std::move(_publisher)) {}
51

52 53 54
AvahiHelper::~AvahiHelper() noexcept = default;

std::unique_ptr<AvahiHelper>
55 56
AvahiInit(EventLoop &event_loop, const char *service_name,
	  const char *service_type, unsigned port)
57
{
58 59 60 61 62 63 64 65
	if (!avahi_is_valid_service_name(service_name))
		throw FormatRuntimeError("Invalid zeroconf_name \"%s\"",
					 service_name);

	auto client = shared_avahi_client.lock();
	if (!client)
		shared_avahi_client = client =
			std::make_shared<SharedAvahiClient>(event_loop);
66

67 68 69
	std::forward_list<Avahi::Service> services;
	services.emplace_front(AVAHI_IF_UNSPEC,
			       AVAHI_PROTO_UNSPEC,
70
			       service_type, port);
71

72 73 74 75
	auto publisher = std::make_unique<Avahi::Publisher>(client->client,
							    service_name,
							    std::move(services),
							    *client);
76

77 78
	return std::make_unique<AvahiHelper>(std::move(client),
					     std::move(publisher));
79
}