blob: 42e9edc04104db82928a4b18e47fc13af41beba2 [file] [log] [blame]
Václav Kubernátc31bd602019-03-07 11:44:48 +01001/*
2 * Copyright (C) 2019 CESNET, https://photonics.cesnet.cz/
3 *
4 * Written by Václav Kubernát <kubernat@cesnet.cz>
5 * Written by Jan Kundrát <jan.kundrat@cesnet.cz>
6 *
7*/
8
Jan Kundráte0154282020-01-22 19:43:30 +01009#include <cstring>
Václav Kubernátc31bd602019-03-07 11:44:48 +010010#include <libyang/Tree_Data.hpp>
11#include <mutex>
12extern "C" {
13#include <nc_client.h>
14}
15#include <sstream>
Václav Kubernát26b56082020-02-03 18:28:56 +010016#include "netconf-client.hpp"
17#include "UniqueResource.hpp"
Václav Kubernátc31bd602019-03-07 11:44:48 +010018
19namespace libnetconf {
20
21namespace impl {
22
Václav Kubernáte2e15ee2020-02-05 17:38:13 +010023static client::LogCb logCallback;
24
25static void logViaCallback(NC_VERB_LEVEL level, const char* message)
26{
27 logCallback(level, message);
28}
29
30
Václav Kubernátc31bd602019-03-07 11:44:48 +010031/** @short Initialization of the libnetconf2 library client
32
33Just a safe wrapper over nc_client_init and nc_client_destroy, really.
34*/
35class ClientInit {
36 ClientInit()
37 {
38 nc_client_init();
Václav Kubernátc31bd602019-03-07 11:44:48 +010039 }
40
41 ~ClientInit()
42 {
43 nc_client_destroy();
44 }
45
46public:
47 static ClientInit& instance()
48 {
49 static ClientInit lib;
50 return lib;
51 }
52
53 ClientInit(const ClientInit&) = delete;
54 ClientInit(ClientInit&&) = delete;
55 ClientInit& operator=(const ClientInit&) = delete;
56 ClientInit& operator=(ClientInit&&) = delete;
57};
58
59static std::mutex clientOptions;
60
61inline void custom_free_nc_reply_data(nc_reply_data* reply)
62{
63 nc_reply_free(reinterpret_cast<nc_reply*>(reply));
64}
65inline void custom_free_nc_reply_error(nc_reply_error* reply)
66{
67 nc_reply_free(reinterpret_cast<nc_reply*>(reply));
68}
69
Jan Kundráte0154282020-01-22 19:43:30 +010070char *ssh_auth_interactive_cb(const char *auth_name, const char *instruction, const char *prompt, int echo, void *priv)
71{
72 const auto cb = static_cast<const client::KbdInteractiveCb*>(priv);
73 auto res = (*cb)(auth_name, instruction, prompt, echo);
74 return ::strdup(res.c_str());
75}
76
Václav Kubernátdd00eeb2020-06-19 11:13:35 +020077template <typename Type> using deleter_type_for = void (*)(Type*);
78template <typename Type> deleter_type_for<Type> deleter_for;
79
80template <> const auto deleter_for<nc_rpc> = nc_rpc_free;
81template <> const auto deleter_for<nc_reply> = nc_reply_free;
82template <> const auto deleter_for<nc_reply_data> = custom_free_nc_reply_data;
83template <> const auto deleter_for<nc_reply_error> = custom_free_nc_reply_error;
Václav Kubernátc31bd602019-03-07 11:44:48 +010084
85template <typename T>
Václav Kubernátdd00eeb2020-06-19 11:13:35 +020086using unique_ptr_for = std::unique_ptr<T, decltype(deleter_for<T>)>;
Václav Kubernátc31bd602019-03-07 11:44:48 +010087
88template <typename T>
89auto guarded(T* ptr)
90{
Václav Kubernátdd00eeb2020-06-19 11:13:35 +020091 return unique_ptr_for<T>(ptr, deleter_for<T>);
Václav Kubernátc31bd602019-03-07 11:44:48 +010092}
93
94unique_ptr_for<struct nc_reply> do_rpc(client::Session* session, unique_ptr_for<struct nc_rpc>&& rpc)
95{
96 uint64_t msgid;
97 NC_MSG_TYPE msgtype;
98
99 msgtype = nc_send_rpc(session->session_internal(), rpc.get(), 1000, &msgid);
100 if (msgtype == NC_MSG_ERROR) {
101 throw std::runtime_error{"Failed to send RPC"};
102 }
103 if (msgtype == NC_MSG_WOULDBLOCK) {
104 throw std::runtime_error{"Timeout sending an RPC"};
105 }
106
107 struct nc_reply* raw_reply;
108 while (true) {
109 msgtype = nc_recv_reply(session->session_internal(), rpc.get(), msgid, 20000, LYD_OPT_DESTRUCT | LYD_OPT_NOSIBLINGS, &raw_reply);
110 auto reply = guarded(raw_reply);
111 raw_reply = nullptr;
112
113 switch (msgtype) {
114 case NC_MSG_ERROR:
115 throw std::runtime_error{"Failed to receive an RPC reply"};
116 case NC_MSG_WOULDBLOCK:
117 throw std::runtime_error{"Timed out waiting for RPC reply"};
118 case NC_MSG_REPLY_ERR_MSGID:
119 throw std::runtime_error{"Received a wrong reply -- msgid mismatch"};
120 case NC_MSG_NOTIF:
121 continue;
122 default:
123 return reply;
124 }
125 }
126 __builtin_unreachable();
127}
128
129client::ReportedError make_error(unique_ptr_for<struct nc_reply>&& reply)
130{
131 if (reply->type != NC_RPL_ERROR) {
132 throw std::logic_error{"Cannot extract an error from a non-error server reply"};
133 }
134
135 auto errorReply = guarded(reinterpret_cast<struct nc_reply_error*>(reply.release()));
136
137 // TODO: capture the error details, not just that human-readable string
138 std::ostringstream ss;
139 ss << "Server error:" << std::endl;
140 for (uint32_t i = 0; i < errorReply->count; ++i) {
141 const auto e = errorReply->err[i];
142 ss << " #" << i << ": " << e.message;
143 if (e.path) {
144 ss << " (XPath " << e.path << ")";
145 }
146 ss << std::endl;
147 }
148 return client::ReportedError{ss.str()};
149}
150
Jan Kundráta2a44142020-01-24 01:31:54 +0100151std::optional<unique_ptr_for<struct nc_reply_data>> do_rpc_data_or_ok(client::Session* session, unique_ptr_for<struct nc_rpc>&& rpc)
Václav Kubernátc31bd602019-03-07 11:44:48 +0100152{
153 auto x = do_rpc(session, std::move(rpc));
154
155 switch (x->type) {
156 case NC_RPL_DATA:
157 return guarded(reinterpret_cast<struct nc_reply_data*>(x.release()));
158 case NC_RPL_OK:
Jan Kundráta2a44142020-01-24 01:31:54 +0100159 return std::nullopt;
Václav Kubernátc31bd602019-03-07 11:44:48 +0100160 case NC_RPL_ERROR:
161 throw make_error(std::move(x));
162 default:
163 throw std::runtime_error{"Unhandled reply type"};
164 }
Jan Kundráta2a44142020-01-24 01:31:54 +0100165
166}
167
168unique_ptr_for<struct nc_reply_data> do_rpc_data(client::Session* session, unique_ptr_for<struct nc_rpc>&& rpc)
169{
170 auto x = do_rpc_data_or_ok(session, std::move(rpc));
171 if (!x) {
172 throw std::runtime_error{"Received OK instead of a data reply"};
173 }
174 return std::move(*x);
Václav Kubernátc31bd602019-03-07 11:44:48 +0100175}
176
177void do_rpc_ok(client::Session* session, unique_ptr_for<struct nc_rpc>&& rpc)
178{
Jan Kundráta2a44142020-01-24 01:31:54 +0100179 auto x = do_rpc_data_or_ok(session, std::move(rpc));
180 if (x) {
Václav Kubernátc31bd602019-03-07 11:44:48 +0100181 throw std::runtime_error{"Unexpected DATA reply"};
Václav Kubernátc31bd602019-03-07 11:44:48 +0100182 }
183}
184}
185
186namespace client {
187
Václav Kubernáte2e15ee2020-02-05 17:38:13 +0100188void setLogLevel(NC_VERB_LEVEL level)
189{
190 nc_verbosity(level);
191}
192
193void setLogCallback(const client::LogCb& callback)
194{
195 impl::logCallback = callback;
196 nc_set_print_clb(impl::logViaCallback);
197}
198
Václav Kubernátc31bd602019-03-07 11:44:48 +0100199struct nc_session* Session::session_internal()
200{
201 return m_session;
202}
203
Václav Kubernát1d50a5b2020-02-03 16:44:22 +0100204libyang::S_Context Session::libyangContext()
205{
206 return std::make_shared<libyang::Context>(nc_session_get_ctx(m_session), nullptr);
207}
208
Václav Kubernátc31bd602019-03-07 11:44:48 +0100209Session::Session(struct nc_session* session)
210 : m_session(session)
211{
212 impl::ClientInit::instance();
213}
214
215Session::~Session()
216{
217 ::nc_session_free(m_session, nullptr);
218}
219
220std::unique_ptr<Session> Session::connectPubkey(const std::string& host, const uint16_t port, const std::string& user, const std::string& pubPath, const std::string& privPath)
221{
222 impl::ClientInit::instance();
223
224 {
225 // FIXME: this is still horribly not enough. libnetconf *must* provide us with something better.
226 std::lock_guard lk(impl::clientOptions);
227 nc_client_ssh_set_username(user.c_str());
228 nc_client_ssh_set_auth_pref(NC_SSH_AUTH_PUBLICKEY, 5);
229 nc_client_ssh_add_keypair(pubPath.c_str(), privPath.c_str());
230 }
231 auto session = std::make_unique<Session>(nc_connect_ssh(host.c_str(), port, nullptr));
232 if (!session->m_session) {
233 throw std::runtime_error{"nc_connect_ssh failed"};
234 }
235 return session;
236}
237
Jan Kundráte0154282020-01-22 19:43:30 +0100238std::unique_ptr<Session> Session::connectKbdInteractive(const std::string& host, const uint16_t port, const std::string& user, const KbdInteractiveCb& callback)
239{
240 impl::ClientInit::instance();
241
242 std::lock_guard lk(impl::clientOptions);
243 auto cb_guard = make_unique_resource([user, &callback]() {
244 nc_client_ssh_set_username(user.c_str());
245 nc_client_ssh_set_auth_pref(NC_SSH_AUTH_INTERACTIVE, 5);
246 nc_client_ssh_set_auth_interactive_clb(impl::ssh_auth_interactive_cb, static_cast<void *>(&const_cast<KbdInteractiveCb&>(callback)));
247 }, []() {
248 nc_client_ssh_set_auth_interactive_clb(nullptr, nullptr);
249 nc_client_ssh_set_username(nullptr);
250 });
251
252 auto session = std::make_unique<Session>(nc_connect_ssh(host.c_str(), port, nullptr));
253 if (!session->m_session) {
254 throw std::runtime_error{"nc_connect_ssh failed"};
255 }
256 return session;
257}
258
Václav Kubernát7a9463f2020-10-30 08:57:59 +0100259std::unique_ptr<Session> Session::connectFd(const int source, const int sink)
260{
261 impl::ClientInit::instance();
262
263 auto session = std::make_unique<Session>(nc_connect_inout(source, sink, nullptr));
264 if (!session->m_session) {
265 throw std::runtime_error{"nc_connect_inout failed"};
266 }
267 return session;
268}
269
Václav Kubernátc31bd602019-03-07 11:44:48 +0100270std::unique_ptr<Session> Session::connectSocket(const std::string& path)
271{
272 impl::ClientInit::instance();
273
274 auto session = std::make_unique<Session>(nc_connect_unix(path.c_str(), nullptr));
275 if (!session->m_session) {
276 throw std::runtime_error{"nc_connect_unix failed"};
277 }
278 return session;
279}
280
281std::vector<std::string_view> Session::capabilities() const
282{
283 std::vector<std::string_view> res;
284 auto caps = nc_session_get_cpblts(m_session);
285 while (*caps) {
286 res.emplace_back(*caps);
287 ++caps;
288 }
289 return res;
290}
291
Jan Kundrát9138b162020-01-30 09:27:51 +0100292std::shared_ptr<libyang::Data_Node> Session::get(const std::optional<std::string>& filter)
Václav Kubernátc31bd602019-03-07 11:44:48 +0100293{
Jan Kundrát9138b162020-01-30 09:27:51 +0100294 auto rpc = impl::guarded(nc_rpc_get(filter ? filter->c_str() : nullptr, NC_WD_ALL, NC_PARAMTYPE_CONST));
Václav Kubernátc31bd602019-03-07 11:44:48 +0100295 if (!rpc) {
296 throw std::runtime_error("Cannot create get RPC");
297 }
298 auto reply = impl::do_rpc_data(this, std::move(rpc));
Jan Kundráta099fb92020-02-03 08:51:56 +0100299 auto dataNode = libyang::create_new_Data_Node(reply->data);
Václav Kubernátc31bd602019-03-07 11:44:48 +0100300 // TODO: can we do without copying?
301 // If we just default-construct a new node (or use the create_new_Data_Node) and then set reply->data to nullptr,
302 // there are mem leaks and even libnetconf2 complains loudly.
Jan Kundráta099fb92020-02-03 08:51:56 +0100303 return dataNode ? dataNode->dup_withsiblings(1) : nullptr;
Václav Kubernátc31bd602019-03-07 11:44:48 +0100304}
305
306std::string Session::getSchema(const std::string_view identifier, const std::optional<std::string_view> version)
307{
308 auto rpc = impl::guarded(nc_rpc_getschema(identifier.data(), version ? version.value().data() : nullptr, nullptr, NC_PARAMTYPE_CONST));
309 if (!rpc) {
310 throw std::runtime_error("Cannot create get-schema RPC");
311 }
312 auto reply = impl::do_rpc_data(this, std::move(rpc));
313
314 auto node = libyang::create_new_Data_Node(reply->data)->dup_withsiblings(1);
315 auto set = node->find_path("data");
316 for (auto node : set->data()) {
317 if (node->schema()->nodetype() == LYS_ANYXML) {
318 libyang::Data_Node_Anydata anydata(node);
319 return anydata.value().str;
320 }
321 }
322 throw std::runtime_error("Got a reply to get-schema, but it didn't contain the required schema");
323}
324
325std::shared_ptr<libyang::Data_Node> Session::getConfig(const NC_DATASTORE datastore, const std::optional<const std::string> filter)
326{
327 auto rpc = impl::guarded(nc_rpc_getconfig(datastore, filter ? filter->c_str() : nullptr, NC_WD_ALL, NC_PARAMTYPE_CONST));
328 if (!rpc) {
329 throw std::runtime_error("Cannot create get-config RPC");
330 }
331 auto reply = impl::do_rpc_data(this, std::move(rpc));
Václav Kubernátc31bd602019-03-07 11:44:48 +0100332 auto dataNode = libyang::create_new_Data_Node(reply->data);
Jan Kundrátf09a0922020-02-03 08:52:32 +0100333 // TODO: can we do without copying? See Session::get() for details.
334 return dataNode ? dataNode->dup_withsiblings(1) : nullptr;
Václav Kubernátc31bd602019-03-07 11:44:48 +0100335}
336
337void Session::editConfig(const NC_DATASTORE datastore,
338 const NC_RPC_EDIT_DFLTOP defaultOperation,
339 const NC_RPC_EDIT_TESTOPT testOption,
340 const NC_RPC_EDIT_ERROPT errorOption,
341 const std::string& data)
342{
343 auto rpc = impl::guarded(nc_rpc_edit(datastore, defaultOperation, testOption, errorOption, data.c_str(), NC_PARAMTYPE_CONST));
344 if (!rpc) {
345 throw std::runtime_error("Cannot create edit-config RPC");
346 }
347 impl::do_rpc_ok(this, std::move(rpc));
348}
349
350void Session::copyConfigFromString(const NC_DATASTORE target, const std::string& data)
351{
352 auto rpc = impl::guarded(nc_rpc_copy(target, nullptr, target /* yeah, cannot be 0... */, data.c_str(), NC_WD_UNKNOWN, NC_PARAMTYPE_CONST));
353 if (!rpc) {
354 throw std::runtime_error("Cannot create copy-config RPC");
355 }
356 impl::do_rpc_ok(this, std::move(rpc));
357}
358
359void Session::commit()
360{
361 auto rpc = impl::guarded(nc_rpc_commit(1, /* "Optional confirm timeout" how do you optional an uint32_t? */ 0, nullptr, nullptr, NC_PARAMTYPE_CONST));
362 if (!rpc) {
363 throw std::runtime_error("Cannot create commit RPC");
364 }
365 impl::do_rpc_ok(this, std::move(rpc));
366}
367
368void Session::discard()
369{
370 auto rpc = impl::guarded(nc_rpc_discard());
371 if (!rpc) {
372 throw std::runtime_error("Cannot create discard RPC");
373 }
374 impl::do_rpc_ok(this, std::move(rpc));
375}
376
Václav Kubernáta8789602020-07-20 15:18:19 +0200377std::shared_ptr<libyang::Data_Node> Session::rpc_or_action(const std::string& xmlData)
Jan Kundrát59acc2f2020-01-23 15:12:59 +0100378{
379 auto rpc = impl::guarded(nc_rpc_act_generic_xml(xmlData.c_str(), NC_PARAMTYPE_CONST));
380 if (!rpc) {
381 throw std::runtime_error("Cannot create generic RPC");
382 }
383 auto reply = impl::do_rpc_data_or_ok(this, std::move(rpc));
384 if (reply) {
385 auto dataNode = libyang::create_new_Data_Node((*reply)->data);
386 return dataNode->dup_withsiblings(1);
387 } else {
388 return nullptr;
389 }
390}
391
Václav Kubernát7160a132020-04-03 02:11:01 +0200392void Session::copyConfig(const NC_DATASTORE source, const NC_DATASTORE destination)
393{
394 auto rpc = impl::guarded(nc_rpc_copy(destination, nullptr, source, nullptr, NC_WD_UNKNOWN, NC_PARAMTYPE_CONST));
395 if (!rpc) {
396 throw std::runtime_error("Cannot create copy-config RPC");
397 }
398 impl::do_rpc_ok(this, std::move(rpc));
399}
400
Václav Kubernátc31bd602019-03-07 11:44:48 +0100401ReportedError::ReportedError(const std::string& what)
402 : std::runtime_error(what)
403{
404}
405
406ReportedError::~ReportedError() = default;
407}
408}