OpenCPN Partial API docs
Loading...
Searching...
No Matches
mdns_cache.cpp
Go to the documentation of this file.
1/**************************************************************************
2 * Copyright (C) 2024 Alec Leamas *
3 * *
4 * This program is free software; you can redistribute it and/or modify *
5 * it under the terms of the GNU General Public License as published by *
6 * the Free Software Foundation; either version 2 of the License, or *
7 * (at your option) any later version. *
8 * *
9 * This program is distributed in the hope that it will be useful, *
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
12 * GNU General Public License for more details. *
13 * *
14 * You should have received a copy of the GNU General Public License *
15 * along with this program; if not, see <https://www.gnu.org/licenses/>. *
16 **************************************************************************/
17
24#include <algorithm>
25
26#include <curl/curl.h>
27
28#include "model/logger.h"
29#include "model/mdns_cache.h"
30
35static bool Ping(const std::string& url, long port = 8443L) {
36 CURL* c = curl_easy_init();
37 curl_easy_setopt(c, CURLOPT_URL, url.c_str());
38 curl_easy_setopt(c, CURLOPT_PORT, port);
39 curl_easy_setopt(c, CURLOPT_TIMEOUT_MS, 2000L);
40 CURLcode result = curl_easy_perform(c);
41 curl_easy_cleanup(c);
42 bool ok = result == CURLE_RECV_ERROR || result == CURLE_OK;
43 DEBUG_LOG << "Checked mdns host: " << url << ": "
44 << (ok ? "ok" : curl_easy_strerror(result));
45 return ok;
46}
47
48MdnsCache& MdnsCache::GetInstance() {
49 static MdnsCache mdns_cache;
50 return mdns_cache;
51}
52
53bool MdnsCache::Add(const Entry& entry) {
54 std::unique_lock lock(m_mutex);
55 auto found = std::find_if(m_cache.begin(), m_cache.end(),
56 [entry](Entry& e) { return e.ip == entry.ip; });
57 DEBUG_LOG << "Added mdns cache entry, ip: " << entry.ip
58 << ", status: " << (found == m_cache.end() ? "true" : "false");
59 if (found != m_cache.end()) return false;
60 m_cache.push_back(entry);
61 return true;
62}
63
64bool MdnsCache::Add(const std::string& service, const std::string& host,
65 const std::string& _ip, const std::string& _port) {
66 return Add(Entry(service, host, _ip, _port));
67}
68
69bool MdnsCache::Add(const std::string& _ip, const std::string& _port) {
70 return Add(Entry("opencpn", "unknown", _ip, _port));
71}
72
74 std::unique_lock lock(m_mutex);
75 for (auto it = m_cache.begin(); it != m_cache.end();) {
76 if (!Ping(it->ip)) {
77 m_cache.erase(it);
78 } else {
79 it++;
80 }
81 }
82}
Singleton cache for hosts looked up using mdns.
Definition mdns_cache.h:40
bool Add(const Entry &entry)
Add new entry to the cache.
void Validate()
Check that all entries are accessible, remove stale ones.
Enhanced logging interface on top of wx/log.h.
mDNS host lookups cache.