blob: f1f7bb1b176fbb6e05dadfac0ddfa51cc4de452a [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 "UniqueResource.hpp"
Václav Kubernátb4e5b182020-11-16 19:55:09 +010017#include "netconf-client.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
Václav Kubernátb4e5b182020-11-16 19:55:09 +010070char* ssh_auth_interactive_cb(const char* auth_name, const char* instruction, const char* prompt, int echo, void* priv)
Jan Kundráte0154282020-01-22 19:43:30 +010071{
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*);
Václav Kubernát21fc5e22020-11-26 04:28:27 +010078template <typename Type> deleter_type_for<Type> const deleter_for;
Václav Kubernátdd00eeb2020-06-19 11:13:35 +020079
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
167unique_ptr_for<struct nc_reply_data> do_rpc_data(client::Session* session, unique_ptr_for<struct nc_rpc>&& rpc)
168{
169 auto x = do_rpc_data_or_ok(session, std::move(rpc));
170 if (!x) {
171 throw std::runtime_error{"Received OK instead of a data reply"};
172 }
173 return std::move(*x);
Václav Kubernátc31bd602019-03-07 11:44:48 +0100174}
175
176void do_rpc_ok(client::Session* session, unique_ptr_for<struct nc_rpc>&& rpc)
177{
Jan Kundráta2a44142020-01-24 01:31:54 +0100178 auto x = do_rpc_data_or_ok(session, std::move(rpc));
179 if (x) {
Václav Kubernátc31bd602019-03-07 11:44:48 +0100180 throw std::runtime_error{"Unexpected DATA reply"};
Václav Kubernátc31bd602019-03-07 11:44:48 +0100181 }
182}
Jan Kundrát13666e32021-01-08 14:49:29 +0100183
184std::shared_ptr<libyang::Data_Node> do_get(client::Session* session, unique_ptr_for<nc_rpc> rpc)
185{
186 auto reply = impl::do_rpc_data(session, std::move(rpc));
187 auto dataNode = libyang::create_new_Data_Node(reply->data);
188 // TODO: can we do without copying?
189 // If we just default-construct a new node (or use the create_new_Data_Node) and then set reply->data to nullptr,
190 // there are mem leaks and even libnetconf2 complains loudly.
191 return dataNode ? dataNode->dup_withsiblings(1) : nullptr;
192}
Václav Kubernátc31bd602019-03-07 11:44:48 +0100193}
194
195namespace client {
196
Václav Kubernáte2e15ee2020-02-05 17:38:13 +0100197void setLogLevel(NC_VERB_LEVEL level)
198{
199 nc_verbosity(level);
200}
201
202void setLogCallback(const client::LogCb& callback)
203{
204 impl::logCallback = callback;
205 nc_set_print_clb(impl::logViaCallback);
206}
207
Václav Kubernátc31bd602019-03-07 11:44:48 +0100208struct nc_session* Session::session_internal()
209{
210 return m_session;
211}
212
Václav Kubernát1d50a5b2020-02-03 16:44:22 +0100213libyang::S_Context Session::libyangContext()
214{
215 return std::make_shared<libyang::Context>(nc_session_get_ctx(m_session), nullptr);
216}
217
Václav Kubernátc31bd602019-03-07 11:44:48 +0100218Session::Session(struct nc_session* session)
219 : m_session(session)
220{
221 impl::ClientInit::instance();
222}
223
224Session::~Session()
225{
226 ::nc_session_free(m_session, nullptr);
227}
228
229std::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)
230{
231 impl::ClientInit::instance();
232
233 {
234 // FIXME: this is still horribly not enough. libnetconf *must* provide us with something better.
235 std::lock_guard lk(impl::clientOptions);
236 nc_client_ssh_set_username(user.c_str());
237 nc_client_ssh_set_auth_pref(NC_SSH_AUTH_PUBLICKEY, 5);
238 nc_client_ssh_add_keypair(pubPath.c_str(), privPath.c_str());
239 }
240 auto session = std::make_unique<Session>(nc_connect_ssh(host.c_str(), port, nullptr));
241 if (!session->m_session) {
242 throw std::runtime_error{"nc_connect_ssh failed"};
243 }
244 return session;
245}
246
Jan Kundráte0154282020-01-22 19:43:30 +0100247std::unique_ptr<Session> Session::connectKbdInteractive(const std::string& host, const uint16_t port, const std::string& user, const KbdInteractiveCb& callback)
248{
249 impl::ClientInit::instance();
250
251 std::lock_guard lk(impl::clientOptions);
252 auto cb_guard = make_unique_resource([user, &callback]() {
253 nc_client_ssh_set_username(user.c_str());
254 nc_client_ssh_set_auth_pref(NC_SSH_AUTH_INTERACTIVE, 5);
255 nc_client_ssh_set_auth_interactive_clb(impl::ssh_auth_interactive_cb, static_cast<void *>(&const_cast<KbdInteractiveCb&>(callback)));
256 }, []() {
257 nc_client_ssh_set_auth_interactive_clb(nullptr, nullptr);
258 nc_client_ssh_set_username(nullptr);
259 });
260
261 auto session = std::make_unique<Session>(nc_connect_ssh(host.c_str(), port, nullptr));
262 if (!session->m_session) {
263 throw std::runtime_error{"nc_connect_ssh failed"};
264 }
265 return session;
266}
267
Václav Kubernát7a9463f2020-10-30 08:57:59 +0100268std::unique_ptr<Session> Session::connectFd(const int source, const int sink)
269{
270 impl::ClientInit::instance();
271
272 auto session = std::make_unique<Session>(nc_connect_inout(source, sink, nullptr));
273 if (!session->m_session) {
274 throw std::runtime_error{"nc_connect_inout failed"};
275 }
276 return session;
277}
278
Václav Kubernátc31bd602019-03-07 11:44:48 +0100279std::unique_ptr<Session> Session::connectSocket(const std::string& path)
280{
281 impl::ClientInit::instance();
282
283 auto session = std::make_unique<Session>(nc_connect_unix(path.c_str(), nullptr));
284 if (!session->m_session) {
285 throw std::runtime_error{"nc_connect_unix failed"};
286 }
287 return session;
288}
289
290std::vector<std::string_view> Session::capabilities() const
291{
292 std::vector<std::string_view> res;
293 auto caps = nc_session_get_cpblts(m_session);
294 while (*caps) {
295 res.emplace_back(*caps);
296 ++caps;
297 }
298 return res;
299}
300
Jan Kundrát9138b162020-01-30 09:27:51 +0100301std::shared_ptr<libyang::Data_Node> Session::get(const std::optional<std::string>& filter)
Václav Kubernátc31bd602019-03-07 11:44:48 +0100302{
Jan Kundrát9138b162020-01-30 09:27:51 +0100303 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 +0100304 if (!rpc) {
305 throw std::runtime_error("Cannot create get RPC");
306 }
Jan Kundrát13666e32021-01-08 14:49:29 +0100307 return impl::do_get(this, std::move(rpc));
Václav Kubernátc31bd602019-03-07 11:44:48 +0100308}
309
310std::string Session::getSchema(const std::string_view identifier, const std::optional<std::string_view> version)
311{
312 auto rpc = impl::guarded(nc_rpc_getschema(identifier.data(), version ? version.value().data() : nullptr, nullptr, NC_PARAMTYPE_CONST));
313 if (!rpc) {
314 throw std::runtime_error("Cannot create get-schema RPC");
315 }
316 auto reply = impl::do_rpc_data(this, std::move(rpc));
317
318 auto node = libyang::create_new_Data_Node(reply->data)->dup_withsiblings(1);
319 auto set = node->find_path("data");
320 for (auto node : set->data()) {
321 if (node->schema()->nodetype() == LYS_ANYXML) {
322 libyang::Data_Node_Anydata anydata(node);
323 return anydata.value().str;
324 }
325 }
326 throw std::runtime_error("Got a reply to get-schema, but it didn't contain the required schema");
327}
328
329std::shared_ptr<libyang::Data_Node> Session::getConfig(const NC_DATASTORE datastore, const std::optional<const std::string> filter)
330{
331 auto rpc = impl::guarded(nc_rpc_getconfig(datastore, filter ? filter->c_str() : nullptr, NC_WD_ALL, NC_PARAMTYPE_CONST));
332 if (!rpc) {
333 throw std::runtime_error("Cannot create get-config RPC");
334 }
Jan Kundrát13666e32021-01-08 14:49:29 +0100335 return impl::do_get(this, std::move(rpc));
Václav Kubernátc31bd602019-03-07 11:44:48 +0100336}
337
338void Session::editConfig(const NC_DATASTORE datastore,
339 const NC_RPC_EDIT_DFLTOP defaultOperation,
340 const NC_RPC_EDIT_TESTOPT testOption,
341 const NC_RPC_EDIT_ERROPT errorOption,
342 const std::string& data)
343{
344 auto rpc = impl::guarded(nc_rpc_edit(datastore, defaultOperation, testOption, errorOption, data.c_str(), NC_PARAMTYPE_CONST));
345 if (!rpc) {
346 throw std::runtime_error("Cannot create edit-config RPC");
347 }
348 impl::do_rpc_ok(this, std::move(rpc));
349}
350
351void Session::copyConfigFromString(const NC_DATASTORE target, const std::string& data)
352{
353 auto rpc = impl::guarded(nc_rpc_copy(target, nullptr, target /* yeah, cannot be 0... */, data.c_str(), NC_WD_UNKNOWN, NC_PARAMTYPE_CONST));
354 if (!rpc) {
355 throw std::runtime_error("Cannot create copy-config RPC");
356 }
357 impl::do_rpc_ok(this, std::move(rpc));
358}
359
360void Session::commit()
361{
362 auto rpc = impl::guarded(nc_rpc_commit(1, /* "Optional confirm timeout" how do you optional an uint32_t? */ 0, nullptr, nullptr, NC_PARAMTYPE_CONST));
363 if (!rpc) {
364 throw std::runtime_error("Cannot create commit RPC");
365 }
366 impl::do_rpc_ok(this, std::move(rpc));
367}
368
369void Session::discard()
370{
371 auto rpc = impl::guarded(nc_rpc_discard());
372 if (!rpc) {
373 throw std::runtime_error("Cannot create discard RPC");
374 }
375 impl::do_rpc_ok(this, std::move(rpc));
376}
377
Václav Kubernáta8789602020-07-20 15:18:19 +0200378std::shared_ptr<libyang::Data_Node> Session::rpc_or_action(const std::string& xmlData)
Jan Kundrát59acc2f2020-01-23 15:12:59 +0100379{
380 auto rpc = impl::guarded(nc_rpc_act_generic_xml(xmlData.c_str(), NC_PARAMTYPE_CONST));
381 if (!rpc) {
382 throw std::runtime_error("Cannot create generic RPC");
383 }
384 auto reply = impl::do_rpc_data_or_ok(this, std::move(rpc));
385 if (reply) {
386 auto dataNode = libyang::create_new_Data_Node((*reply)->data);
387 return dataNode->dup_withsiblings(1);
388 } else {
389 return nullptr;
390 }
391}
392
Václav Kubernát7160a132020-04-03 02:11:01 +0200393void Session::copyConfig(const NC_DATASTORE source, const NC_DATASTORE destination)
394{
395 auto rpc = impl::guarded(nc_rpc_copy(destination, nullptr, source, nullptr, NC_WD_UNKNOWN, NC_PARAMTYPE_CONST));
396 if (!rpc) {
397 throw std::runtime_error("Cannot create copy-config RPC");
398 }
399 impl::do_rpc_ok(this, std::move(rpc));
400}
401
Václav Kubernátc31bd602019-03-07 11:44:48 +0100402ReportedError::ReportedError(const std::string& what)
403 : std::runtime_error(what)
404{
405}
406
407ReportedError::~ReportedError() = default;
408}
409}