blob: 5b3fa4d6aeaca18102048a8f84dc7dcb09ba120e [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
23/** @short Initialization of the libnetconf2 library client
24
25Just a safe wrapper over nc_client_init and nc_client_destroy, really.
26*/
27class ClientInit {
28 ClientInit()
29 {
30 nc_client_init();
31 nc_verbosity(NC_VERB_DEBUG);
32 }
33
34 ~ClientInit()
35 {
36 nc_client_destroy();
37 }
38
39public:
40 static ClientInit& instance()
41 {
42 static ClientInit lib;
43 return lib;
44 }
45
46 ClientInit(const ClientInit&) = delete;
47 ClientInit(ClientInit&&) = delete;
48 ClientInit& operator=(const ClientInit&) = delete;
49 ClientInit& operator=(ClientInit&&) = delete;
50};
51
52static std::mutex clientOptions;
53
54inline void custom_free_nc_reply_data(nc_reply_data* reply)
55{
56 nc_reply_free(reinterpret_cast<nc_reply*>(reply));
57}
58inline void custom_free_nc_reply_error(nc_reply_error* reply)
59{
60 nc_reply_free(reinterpret_cast<nc_reply*>(reply));
61}
62
Jan Kundráte0154282020-01-22 19:43:30 +010063char *ssh_auth_interactive_cb(const char *auth_name, const char *instruction, const char *prompt, int echo, void *priv)
64{
65 const auto cb = static_cast<const client::KbdInteractiveCb*>(priv);
66 auto res = (*cb)(auth_name, instruction, prompt, echo);
67 return ::strdup(res.c_str());
68}
69
Václav Kubernátdd00eeb2020-06-19 11:13:35 +020070template <typename Type> using deleter_type_for = void (*)(Type*);
71template <typename Type> deleter_type_for<Type> deleter_for;
72
73template <> const auto deleter_for<nc_rpc> = nc_rpc_free;
74template <> const auto deleter_for<nc_reply> = nc_reply_free;
75template <> const auto deleter_for<nc_reply_data> = custom_free_nc_reply_data;
76template <> const auto deleter_for<nc_reply_error> = custom_free_nc_reply_error;
Václav Kubernátc31bd602019-03-07 11:44:48 +010077
78template <typename T>
Václav Kubernátdd00eeb2020-06-19 11:13:35 +020079using unique_ptr_for = std::unique_ptr<T, decltype(deleter_for<T>)>;
Václav Kubernátc31bd602019-03-07 11:44:48 +010080
81template <typename T>
82auto guarded(T* ptr)
83{
Václav Kubernátdd00eeb2020-06-19 11:13:35 +020084 return unique_ptr_for<T>(ptr, deleter_for<T>);
Václav Kubernátc31bd602019-03-07 11:44:48 +010085}
86
87unique_ptr_for<struct nc_reply> do_rpc(client::Session* session, unique_ptr_for<struct nc_rpc>&& rpc)
88{
89 uint64_t msgid;
90 NC_MSG_TYPE msgtype;
91
92 msgtype = nc_send_rpc(session->session_internal(), rpc.get(), 1000, &msgid);
93 if (msgtype == NC_MSG_ERROR) {
94 throw std::runtime_error{"Failed to send RPC"};
95 }
96 if (msgtype == NC_MSG_WOULDBLOCK) {
97 throw std::runtime_error{"Timeout sending an RPC"};
98 }
99
100 struct nc_reply* raw_reply;
101 while (true) {
102 msgtype = nc_recv_reply(session->session_internal(), rpc.get(), msgid, 20000, LYD_OPT_DESTRUCT | LYD_OPT_NOSIBLINGS, &raw_reply);
103 auto reply = guarded(raw_reply);
104 raw_reply = nullptr;
105
106 switch (msgtype) {
107 case NC_MSG_ERROR:
108 throw std::runtime_error{"Failed to receive an RPC reply"};
109 case NC_MSG_WOULDBLOCK:
110 throw std::runtime_error{"Timed out waiting for RPC reply"};
111 case NC_MSG_REPLY_ERR_MSGID:
112 throw std::runtime_error{"Received a wrong reply -- msgid mismatch"};
113 case NC_MSG_NOTIF:
114 continue;
115 default:
116 return reply;
117 }
118 }
119 __builtin_unreachable();
120}
121
122client::ReportedError make_error(unique_ptr_for<struct nc_reply>&& reply)
123{
124 if (reply->type != NC_RPL_ERROR) {
125 throw std::logic_error{"Cannot extract an error from a non-error server reply"};
126 }
127
128 auto errorReply = guarded(reinterpret_cast<struct nc_reply_error*>(reply.release()));
129
130 // TODO: capture the error details, not just that human-readable string
131 std::ostringstream ss;
132 ss << "Server error:" << std::endl;
133 for (uint32_t i = 0; i < errorReply->count; ++i) {
134 const auto e = errorReply->err[i];
135 ss << " #" << i << ": " << e.message;
136 if (e.path) {
137 ss << " (XPath " << e.path << ")";
138 }
139 ss << std::endl;
140 }
141 return client::ReportedError{ss.str()};
142}
143
Jan Kundráta2a44142020-01-24 01:31:54 +0100144std::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 +0100145{
146 auto x = do_rpc(session, std::move(rpc));
147
148 switch (x->type) {
149 case NC_RPL_DATA:
150 return guarded(reinterpret_cast<struct nc_reply_data*>(x.release()));
151 case NC_RPL_OK:
Jan Kundráta2a44142020-01-24 01:31:54 +0100152 return std::nullopt;
Václav Kubernátc31bd602019-03-07 11:44:48 +0100153 case NC_RPL_ERROR:
154 throw make_error(std::move(x));
155 default:
156 throw std::runtime_error{"Unhandled reply type"};
157 }
Jan Kundráta2a44142020-01-24 01:31:54 +0100158
159}
160
161unique_ptr_for<struct nc_reply_data> do_rpc_data(client::Session* session, unique_ptr_for<struct nc_rpc>&& rpc)
162{
163 auto x = do_rpc_data_or_ok(session, std::move(rpc));
164 if (!x) {
165 throw std::runtime_error{"Received OK instead of a data reply"};
166 }
167 return std::move(*x);
Václav Kubernátc31bd602019-03-07 11:44:48 +0100168}
169
170void do_rpc_ok(client::Session* session, unique_ptr_for<struct nc_rpc>&& rpc)
171{
Jan Kundráta2a44142020-01-24 01:31:54 +0100172 auto x = do_rpc_data_or_ok(session, std::move(rpc));
173 if (x) {
Václav Kubernátc31bd602019-03-07 11:44:48 +0100174 throw std::runtime_error{"Unexpected DATA reply"};
Václav Kubernátc31bd602019-03-07 11:44:48 +0100175 }
176}
177}
178
179namespace client {
180
181struct nc_session* Session::session_internal()
182{
183 return m_session;
184}
185
Václav Kubernát1d50a5b2020-02-03 16:44:22 +0100186libyang::S_Context Session::libyangContext()
187{
188 return std::make_shared<libyang::Context>(nc_session_get_ctx(m_session), nullptr);
189}
190
Václav Kubernátc31bd602019-03-07 11:44:48 +0100191Session::Session(struct nc_session* session)
192 : m_session(session)
193{
194 impl::ClientInit::instance();
195}
196
197Session::~Session()
198{
199 ::nc_session_free(m_session, nullptr);
200}
201
202std::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)
203{
204 impl::ClientInit::instance();
205
206 {
207 // FIXME: this is still horribly not enough. libnetconf *must* provide us with something better.
208 std::lock_guard lk(impl::clientOptions);
209 nc_client_ssh_set_username(user.c_str());
210 nc_client_ssh_set_auth_pref(NC_SSH_AUTH_PUBLICKEY, 5);
211 nc_client_ssh_add_keypair(pubPath.c_str(), privPath.c_str());
212 }
213 auto session = std::make_unique<Session>(nc_connect_ssh(host.c_str(), port, nullptr));
214 if (!session->m_session) {
215 throw std::runtime_error{"nc_connect_ssh failed"};
216 }
217 return session;
218}
219
Jan Kundráte0154282020-01-22 19:43:30 +0100220std::unique_ptr<Session> Session::connectKbdInteractive(const std::string& host, const uint16_t port, const std::string& user, const KbdInteractiveCb& callback)
221{
222 impl::ClientInit::instance();
223
224 std::lock_guard lk(impl::clientOptions);
225 auto cb_guard = make_unique_resource([user, &callback]() {
226 nc_client_ssh_set_username(user.c_str());
227 nc_client_ssh_set_auth_pref(NC_SSH_AUTH_INTERACTIVE, 5);
228 nc_client_ssh_set_auth_interactive_clb(impl::ssh_auth_interactive_cb, static_cast<void *>(&const_cast<KbdInteractiveCb&>(callback)));
229 }, []() {
230 nc_client_ssh_set_auth_interactive_clb(nullptr, nullptr);
231 nc_client_ssh_set_username(nullptr);
232 });
233
234 auto session = std::make_unique<Session>(nc_connect_ssh(host.c_str(), port, nullptr));
235 if (!session->m_session) {
236 throw std::runtime_error{"nc_connect_ssh failed"};
237 }
238 return session;
239}
240
Václav Kubernát7a9463f2020-10-30 08:57:59 +0100241std::unique_ptr<Session> Session::connectFd(const int source, const int sink)
242{
243 impl::ClientInit::instance();
244
245 auto session = std::make_unique<Session>(nc_connect_inout(source, sink, nullptr));
246 if (!session->m_session) {
247 throw std::runtime_error{"nc_connect_inout failed"};
248 }
249 return session;
250}
251
Václav Kubernátc31bd602019-03-07 11:44:48 +0100252std::unique_ptr<Session> Session::connectSocket(const std::string& path)
253{
254 impl::ClientInit::instance();
255
256 auto session = std::make_unique<Session>(nc_connect_unix(path.c_str(), nullptr));
257 if (!session->m_session) {
258 throw std::runtime_error{"nc_connect_unix failed"};
259 }
260 return session;
261}
262
263std::vector<std::string_view> Session::capabilities() const
264{
265 std::vector<std::string_view> res;
266 auto caps = nc_session_get_cpblts(m_session);
267 while (*caps) {
268 res.emplace_back(*caps);
269 ++caps;
270 }
271 return res;
272}
273
Jan Kundrát9138b162020-01-30 09:27:51 +0100274std::shared_ptr<libyang::Data_Node> Session::get(const std::optional<std::string>& filter)
Václav Kubernátc31bd602019-03-07 11:44:48 +0100275{
Jan Kundrát9138b162020-01-30 09:27:51 +0100276 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 +0100277 if (!rpc) {
278 throw std::runtime_error("Cannot create get RPC");
279 }
280 auto reply = impl::do_rpc_data(this, std::move(rpc));
Jan Kundráta099fb92020-02-03 08:51:56 +0100281 auto dataNode = libyang::create_new_Data_Node(reply->data);
Václav Kubernátc31bd602019-03-07 11:44:48 +0100282 // TODO: can we do without copying?
283 // If we just default-construct a new node (or use the create_new_Data_Node) and then set reply->data to nullptr,
284 // there are mem leaks and even libnetconf2 complains loudly.
Jan Kundráta099fb92020-02-03 08:51:56 +0100285 return dataNode ? dataNode->dup_withsiblings(1) : nullptr;
Václav Kubernátc31bd602019-03-07 11:44:48 +0100286}
287
288std::string Session::getSchema(const std::string_view identifier, const std::optional<std::string_view> version)
289{
290 auto rpc = impl::guarded(nc_rpc_getschema(identifier.data(), version ? version.value().data() : nullptr, nullptr, NC_PARAMTYPE_CONST));
291 if (!rpc) {
292 throw std::runtime_error("Cannot create get-schema RPC");
293 }
294 auto reply = impl::do_rpc_data(this, std::move(rpc));
295
296 auto node = libyang::create_new_Data_Node(reply->data)->dup_withsiblings(1);
297 auto set = node->find_path("data");
298 for (auto node : set->data()) {
299 if (node->schema()->nodetype() == LYS_ANYXML) {
300 libyang::Data_Node_Anydata anydata(node);
301 return anydata.value().str;
302 }
303 }
304 throw std::runtime_error("Got a reply to get-schema, but it didn't contain the required schema");
305}
306
307std::shared_ptr<libyang::Data_Node> Session::getConfig(const NC_DATASTORE datastore, const std::optional<const std::string> filter)
308{
309 auto rpc = impl::guarded(nc_rpc_getconfig(datastore, filter ? filter->c_str() : nullptr, NC_WD_ALL, NC_PARAMTYPE_CONST));
310 if (!rpc) {
311 throw std::runtime_error("Cannot create get-config RPC");
312 }
313 auto reply = impl::do_rpc_data(this, std::move(rpc));
Václav Kubernátc31bd602019-03-07 11:44:48 +0100314 auto dataNode = libyang::create_new_Data_Node(reply->data);
Jan Kundrátf09a0922020-02-03 08:52:32 +0100315 // TODO: can we do without copying? See Session::get() for details.
316 return dataNode ? dataNode->dup_withsiblings(1) : nullptr;
Václav Kubernátc31bd602019-03-07 11:44:48 +0100317}
318
319void Session::editConfig(const NC_DATASTORE datastore,
320 const NC_RPC_EDIT_DFLTOP defaultOperation,
321 const NC_RPC_EDIT_TESTOPT testOption,
322 const NC_RPC_EDIT_ERROPT errorOption,
323 const std::string& data)
324{
325 auto rpc = impl::guarded(nc_rpc_edit(datastore, defaultOperation, testOption, errorOption, data.c_str(), NC_PARAMTYPE_CONST));
326 if (!rpc) {
327 throw std::runtime_error("Cannot create edit-config RPC");
328 }
329 impl::do_rpc_ok(this, std::move(rpc));
330}
331
332void Session::copyConfigFromString(const NC_DATASTORE target, const std::string& data)
333{
334 auto rpc = impl::guarded(nc_rpc_copy(target, nullptr, target /* yeah, cannot be 0... */, data.c_str(), NC_WD_UNKNOWN, NC_PARAMTYPE_CONST));
335 if (!rpc) {
336 throw std::runtime_error("Cannot create copy-config RPC");
337 }
338 impl::do_rpc_ok(this, std::move(rpc));
339}
340
341void Session::commit()
342{
343 auto rpc = impl::guarded(nc_rpc_commit(1, /* "Optional confirm timeout" how do you optional an uint32_t? */ 0, nullptr, nullptr, NC_PARAMTYPE_CONST));
344 if (!rpc) {
345 throw std::runtime_error("Cannot create commit RPC");
346 }
347 impl::do_rpc_ok(this, std::move(rpc));
348}
349
350void Session::discard()
351{
352 auto rpc = impl::guarded(nc_rpc_discard());
353 if (!rpc) {
354 throw std::runtime_error("Cannot create discard RPC");
355 }
356 impl::do_rpc_ok(this, std::move(rpc));
357}
358
Václav Kubernáta8789602020-07-20 15:18:19 +0200359std::shared_ptr<libyang::Data_Node> Session::rpc_or_action(const std::string& xmlData)
Jan Kundrát59acc2f2020-01-23 15:12:59 +0100360{
361 auto rpc = impl::guarded(nc_rpc_act_generic_xml(xmlData.c_str(), NC_PARAMTYPE_CONST));
362 if (!rpc) {
363 throw std::runtime_error("Cannot create generic RPC");
364 }
365 auto reply = impl::do_rpc_data_or_ok(this, std::move(rpc));
366 if (reply) {
367 auto dataNode = libyang::create_new_Data_Node((*reply)->data);
368 return dataNode->dup_withsiblings(1);
369 } else {
370 return nullptr;
371 }
372}
373
Václav Kubernát7160a132020-04-03 02:11:01 +0200374void Session::copyConfig(const NC_DATASTORE source, const NC_DATASTORE destination)
375{
376 auto rpc = impl::guarded(nc_rpc_copy(destination, nullptr, source, nullptr, NC_WD_UNKNOWN, NC_PARAMTYPE_CONST));
377 if (!rpc) {
378 throw std::runtime_error("Cannot create copy-config RPC");
379 }
380 impl::do_rpc_ok(this, std::move(rpc));
381}
382
Václav Kubernátc31bd602019-03-07 11:44:48 +0100383ReportedError::ReportedError(const std::string& what)
384 : std::runtime_error(what)
385{
386}
387
388ReportedError::~ReportedError() = default;
389}
390}