blob: 1ff83de1212d62cd32b3d8247245e32feacef9a0 [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átc31bd602019-03-07 11:44:48 +0100241std::unique_ptr<Session> Session::connectSocket(const std::string& path)
242{
243 impl::ClientInit::instance();
244
245 auto session = std::make_unique<Session>(nc_connect_unix(path.c_str(), nullptr));
246 if (!session->m_session) {
247 throw std::runtime_error{"nc_connect_unix failed"};
248 }
249 return session;
250}
251
252std::vector<std::string_view> Session::capabilities() const
253{
254 std::vector<std::string_view> res;
255 auto caps = nc_session_get_cpblts(m_session);
256 while (*caps) {
257 res.emplace_back(*caps);
258 ++caps;
259 }
260 return res;
261}
262
Jan Kundrát9138b162020-01-30 09:27:51 +0100263std::shared_ptr<libyang::Data_Node> Session::get(const std::optional<std::string>& filter)
Václav Kubernátc31bd602019-03-07 11:44:48 +0100264{
Jan Kundrát9138b162020-01-30 09:27:51 +0100265 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 +0100266 if (!rpc) {
267 throw std::runtime_error("Cannot create get RPC");
268 }
269 auto reply = impl::do_rpc_data(this, std::move(rpc));
Jan Kundráta099fb92020-02-03 08:51:56 +0100270 auto dataNode = libyang::create_new_Data_Node(reply->data);
Václav Kubernátc31bd602019-03-07 11:44:48 +0100271 // TODO: can we do without copying?
272 // If we just default-construct a new node (or use the create_new_Data_Node) and then set reply->data to nullptr,
273 // there are mem leaks and even libnetconf2 complains loudly.
Jan Kundráta099fb92020-02-03 08:51:56 +0100274 return dataNode ? dataNode->dup_withsiblings(1) : nullptr;
Václav Kubernátc31bd602019-03-07 11:44:48 +0100275}
276
277std::string Session::getSchema(const std::string_view identifier, const std::optional<std::string_view> version)
278{
279 auto rpc = impl::guarded(nc_rpc_getschema(identifier.data(), version ? version.value().data() : nullptr, nullptr, NC_PARAMTYPE_CONST));
280 if (!rpc) {
281 throw std::runtime_error("Cannot create get-schema RPC");
282 }
283 auto reply = impl::do_rpc_data(this, std::move(rpc));
284
285 auto node = libyang::create_new_Data_Node(reply->data)->dup_withsiblings(1);
286 auto set = node->find_path("data");
287 for (auto node : set->data()) {
288 if (node->schema()->nodetype() == LYS_ANYXML) {
289 libyang::Data_Node_Anydata anydata(node);
290 return anydata.value().str;
291 }
292 }
293 throw std::runtime_error("Got a reply to get-schema, but it didn't contain the required schema");
294}
295
296std::shared_ptr<libyang::Data_Node> Session::getConfig(const NC_DATASTORE datastore, const std::optional<const std::string> filter)
297{
298 auto rpc = impl::guarded(nc_rpc_getconfig(datastore, filter ? filter->c_str() : nullptr, NC_WD_ALL, NC_PARAMTYPE_CONST));
299 if (!rpc) {
300 throw std::runtime_error("Cannot create get-config RPC");
301 }
302 auto reply = impl::do_rpc_data(this, std::move(rpc));
Václav Kubernátc31bd602019-03-07 11:44:48 +0100303 auto dataNode = libyang::create_new_Data_Node(reply->data);
Jan Kundrátf09a0922020-02-03 08:52:32 +0100304 // TODO: can we do without copying? See Session::get() for details.
305 return dataNode ? dataNode->dup_withsiblings(1) : nullptr;
Václav Kubernátc31bd602019-03-07 11:44:48 +0100306}
307
308void Session::editConfig(const NC_DATASTORE datastore,
309 const NC_RPC_EDIT_DFLTOP defaultOperation,
310 const NC_RPC_EDIT_TESTOPT testOption,
311 const NC_RPC_EDIT_ERROPT errorOption,
312 const std::string& data)
313{
314 auto rpc = impl::guarded(nc_rpc_edit(datastore, defaultOperation, testOption, errorOption, data.c_str(), NC_PARAMTYPE_CONST));
315 if (!rpc) {
316 throw std::runtime_error("Cannot create edit-config RPC");
317 }
318 impl::do_rpc_ok(this, std::move(rpc));
319}
320
321void Session::copyConfigFromString(const NC_DATASTORE target, const std::string& data)
322{
323 auto rpc = impl::guarded(nc_rpc_copy(target, nullptr, target /* yeah, cannot be 0... */, data.c_str(), NC_WD_UNKNOWN, NC_PARAMTYPE_CONST));
324 if (!rpc) {
325 throw std::runtime_error("Cannot create copy-config RPC");
326 }
327 impl::do_rpc_ok(this, std::move(rpc));
328}
329
330void Session::commit()
331{
332 auto rpc = impl::guarded(nc_rpc_commit(1, /* "Optional confirm timeout" how do you optional an uint32_t? */ 0, nullptr, nullptr, NC_PARAMTYPE_CONST));
333 if (!rpc) {
334 throw std::runtime_error("Cannot create commit RPC");
335 }
336 impl::do_rpc_ok(this, std::move(rpc));
337}
338
339void Session::discard()
340{
341 auto rpc = impl::guarded(nc_rpc_discard());
342 if (!rpc) {
343 throw std::runtime_error("Cannot create discard RPC");
344 }
345 impl::do_rpc_ok(this, std::move(rpc));
346}
347
Václav Kubernáta8789602020-07-20 15:18:19 +0200348std::shared_ptr<libyang::Data_Node> Session::rpc_or_action(const std::string& xmlData)
Jan Kundrát59acc2f2020-01-23 15:12:59 +0100349{
350 auto rpc = impl::guarded(nc_rpc_act_generic_xml(xmlData.c_str(), NC_PARAMTYPE_CONST));
351 if (!rpc) {
352 throw std::runtime_error("Cannot create generic RPC");
353 }
354 auto reply = impl::do_rpc_data_or_ok(this, std::move(rpc));
355 if (reply) {
356 auto dataNode = libyang::create_new_Data_Node((*reply)->data);
357 return dataNode->dup_withsiblings(1);
358 } else {
359 return nullptr;
360 }
361}
362
Václav Kubernát7160a132020-04-03 02:11:01 +0200363void Session::copyConfig(const NC_DATASTORE source, const NC_DATASTORE destination)
364{
365 auto rpc = impl::guarded(nc_rpc_copy(destination, nullptr, source, nullptr, NC_WD_UNKNOWN, NC_PARAMTYPE_CONST));
366 if (!rpc) {
367 throw std::runtime_error("Cannot create copy-config RPC");
368 }
369 impl::do_rpc_ok(this, std::move(rpc));
370}
371
Václav Kubernátc31bd602019-03-07 11:44:48 +0100372ReportedError::ReportedError(const std::string& what)
373 : std::runtime_error(what)
374{
375}
376
377ReportedError::~ReportedError() = default;
378}
379}