+#define RESOLV_CONF "/etc/resolv.conf"
+
+static AvahiSEntryGroup *dns_servers_entry_group = NULL;
+static AvahiSEntryGroup *resolv_conf_entry_group = NULL;
+
+static char **resolv_conf = NULL;
+
+static DaemonConfig config;
+
+#define MAX_NAME_SERVERS 10
+
+static int has_prefix(const char *s, const char *prefix) {
+ size_t l;
+
+ l = strlen(prefix);
+
+ return strlen(s) >= l && strncmp(s, prefix, l) == 0;
+}
+
+static int load_resolv_conf(const DaemonConfig *c) {
+ int ret = -1;
+ FILE *f;
+ int i = 0;
+
+ avahi_strfreev(resolv_conf);
+ resolv_conf = NULL;
+
+ if (!c->publish_resolv_conf)
+ return 0;
+
+ if (!(f = fopen(RESOLV_CONF, "r"))) {
+ avahi_log_warn("Failed to open "RESOLV_CONF".");
+ goto finish;
+ }
+
+ resolv_conf = avahi_new0(char*, MAX_NAME_SERVERS+1);
+
+ while (!feof(f) && i < MAX_NAME_SERVERS) {
+ char ln[128];
+ char *p;
+
+ if (!(fgets(ln, sizeof(ln), f)))
+ break;
+
+ ln[strcspn(ln, "\r\n#")] = 0;
+ p = ln + strspn(ln, "\t ");
+
+ if (has_prefix(p, "nameserver")) {
+ p += 10;
+ p += strspn(p, "\t ");
+ p[strcspn(p, "\t ")] = 0;
+ resolv_conf[i++] = avahi_strdup(p);
+ }
+ }
+
+ ret = 0;
+
+finish:
+
+ if (ret != 0) {
+ avahi_strfreev(resolv_conf);
+ resolv_conf = NULL;
+ }
+
+ if (f)
+ fclose(f);
+
+ return ret;
+}
+
+static AvahiSEntryGroup* add_dns_servers(AvahiServer *s, AvahiSEntryGroup* g, char **l) {
+ char **p;
+
+ assert(s);
+ assert(l);
+
+ if (!g)
+ g = avahi_s_entry_group_new(s, NULL, NULL);
+
+ assert(avahi_s_entry_group_is_empty(g));
+
+ for (p = l; *p; p++) {
+ AvahiAddress a;
+
+ if (!avahi_address_parse(*p, AF_UNSPEC, &a))
+ avahi_log_warn("Failed to parse address '%s', ignoring.", *p);
+ else
+ if (avahi_server_add_dns_server_address(s, g, -1, AF_UNSPEC, NULL, AVAHI_DNS_SERVER_RESOLVE, &a, 53) < 0) {
+ avahi_s_entry_group_free(g);
+ avahi_log_error("Failed to add DNS server address: %s", avahi_strerror(avahi_server_errno(s)));
+ return NULL;
+ }
+ }
+
+ avahi_s_entry_group_commit(g);
+
+ return g;
+}
+
+static void remove_dns_server_entry_groups(void) {
+
+ if (resolv_conf_entry_group)
+ avahi_s_entry_group_reset(resolv_conf_entry_group);
+
+ if (dns_servers_entry_group)
+ avahi_s_entry_group_reset(dns_servers_entry_group);
+}
+
+static void server_callback(AvahiServer *s, AvahiServerState state, void *userdata) {
+ DaemonConfig *c = userdata;
+
+ assert(s);
+ assert(c);
+
+ /** This function is possibly called before the global variable
+ * avahi_server has been set, therefore we do it explicitly */
+
+ avahi_server = s;
+
+#ifdef HAVE_DBUS
+ if (c->enable_dbus)
+ dbus_protocol_server_state_changed(state);
+#endif