ZeroconfGlue.cxx 2.51 KB
Newer Older
1
/*
2
 * Copyright 2003-2018 The Music Player Daemon Project
3
 * http://www.musicpd.org
4 5 6 7 8 9 10 11 12 13
 *
 * 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 21 22
#include "ZeroconfGlue.hxx"
#include "ZeroconfAvahi.hxx"
#include "ZeroconfBonjour.hxx"
23
#include "config/Data.hxx"
24
#include "config/Option.hxx"
Max Kellermann's avatar
Max Kellermann committed
25
#include "Listen.hxx"
26 27
#include "util/Domain.hxx"
#include "Log.hxx"
28
#include "util/Compiler.h"
29 30

#include <string.h>
31 32
#include <unistd.h>
#include <limits.h>
33

34 35 36 37 38 39
#ifndef HOST_NAME_MAX
/* HOST_NAME_MAX is not a portable macro; it is undefined on some
   systems */
#define HOST_NAME_MAX 255
#endif

40
static constexpr Domain zeroconf_domain("zeroconf");
41

42
/* The default service name to publish
43 44
 * (overridden by 'zeroconf_name' config parameter)
 */
45
#define SERVICE_NAME		"Music Player @ %h"
46

47 48
#define DEFAULT_ZEROCONF_ENABLED 1

49
static int zeroconfEnabled;
50

51
void
52
ZeroconfInit(const ConfigData &config, gcc_unused EventLoop &loop)
53
{
54
	const char *serviceName;
55

56 57
	zeroconfEnabled = config.GetBool(ConfigOption::ZEROCONF_ENABLED,
					 DEFAULT_ZEROCONF_ENABLED);
58
	if (!zeroconfEnabled)
59
		return;
60

61
	if (listen_port <= 0) {
62 63
		LogWarning(zeroconf_domain,
			   "No global port, disabling zeroconf");
64 65 66 67
		zeroconfEnabled = false;
		return;
	}

68 69
	serviceName = config.GetString(ConfigOption::ZEROCONF_NAME,
				       SERVICE_NAME);
70

71 72 73 74 75 76 77 78 79 80 81
	/* replace "%h" with the host name */
	const char *h = strstr(serviceName, "%h");
	std::string buffer;
	if (h != nullptr) {
		char hostname[HOST_NAME_MAX+1];
		if (gethostname(hostname, HOST_NAME_MAX) == 0) {
			buffer = serviceName;
			buffer.replace(h - serviceName, 2, hostname);
			serviceName = buffer.c_str();
		}
	}
82

83
#ifdef HAVE_AVAHI
84
	AvahiInit(loop, serviceName);
85 86 87
#endif

#ifdef HAVE_BONJOUR
88
	BonjourInit(loop, serviceName);
89
#endif
90 91
}

92 93
void
ZeroconfDeinit()
94
{
95
	if (!zeroconfEnabled)
96 97
		return;

98
#ifdef HAVE_AVAHI
99
	AvahiDeinit();
100
#endif /* HAVE_AVAHI */
101 102

#ifdef HAVE_BONJOUR
103
	BonjourDeinit();
104
#endif
105
}