blob: fde9561f58b66151ced4b724c4caec61a9641ba7 [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*);
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
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}
183}
184
185namespace client {
186
Václav Kubernáte2e15ee2020-02-05 17:38:13 +0100187void setLogLevel(NC_VERB_LEVEL level)
188{
189 nc_verbosity(level);
190}
191
192void setLogCallback(const client::LogCb& callback)
193{
194 impl::logCallback = callback;
195 nc_set_print_clb(impl::logViaCallback);
196}
197
Václav Kubernátc31bd602019-03-07 11:44:48 +0100198struct nc_session* Session::session_internal()
199{
200 return m_session;
201}
202
Václav Kubernát1d50a5b2020-02-03 16:44:22 +0100203libyang::S_Context Session::libyangContext()
204{
205 return std::make_shared<libyang::Context>(nc_session_get_ctx(m_session), nullptr);
206}
207
Václav Kubernátc31bd602019-03-07 11:44:48 +0100208Session::Session(struct nc_session* session)
209 : m_session(session)
210{
211 impl::ClientInit::instance();
212}
213
214Session::~Session()
215{
216 ::nc_session_free(m_session, nullptr);
217}
218
219std::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)
220{
221 impl::ClientInit::instance();
222
223 {
224 // FIXME: this is still horribly not enough. libnetconf *must* provide us with something better.
225 std::lock_guard lk(impl::clientOptions);
226 nc_client_ssh_set_username(user.c_str());
227 nc_client_ssh_set_auth_pref(NC_SSH_AUTH_PUBLICKEY, 5);
228 nc_client_ssh_add_keypair(pubPath.c_str(), privPath.c_str());
229 }
230 auto session = std::make_unique<Session>(nc_connect_ssh(host.c_str(), port, nullptr));
231 if (!session->m_session) {
232 throw std::runtime_error{"nc_connect_ssh failed"};
233 }
234 return session;
235}
236
Jan Kundráte0154282020-01-22 19:43:30 +0100237std::unique_ptr<Session> Session::connectKbdInteractive(const std::string& host, const uint16_t port, const std::string& user, const KbdInteractiveCb& callback)
238{
239 impl::ClientInit::instance();
240
241 std::lock_guard lk(impl::clientOptions);
242 auto cb_guard = make_unique_resource([user, &callback]() {
243 nc_client_ssh_set_username(user.c_str());
244 nc_client_ssh_set_auth_pref(NC_SSH_AUTH_INTERACTIVE, 5);
245 nc_client_ssh_set_auth_interactive_clb(impl::ssh_auth_interactive_cb, static_cast<void *>(&const_cast<KbdInteractiveCb&>(callback)));
246 }, []() {
247 nc_client_ssh_set_auth_interactive_clb(nullptr, nullptr);
248 nc_client_ssh_set_username(nullptr);
249 });
250
251 auto session = std::make_unique<Session>(nc_connect_ssh(host.c_str(), port, nullptr));
252 if (!session->m_session) {
253 throw std::runtime_error{"nc_connect_ssh failed"};
254 }
255 return session;
256}
257
Václav Kubernát7a9463f2020-10-30 08:57:59 +0100258std::unique_ptr<Session> Session::connectFd(const int source, const int sink)
259{
260 impl::ClientInit::instance();
261
262 auto session = std::make_unique<Session>(nc_connect_inout(source, sink, nullptr));
263 if (!session->m_session) {
264 throw std::runtime_error{"nc_connect_inout failed"};
265 }
266 return session;
267}
268
Václav Kubernátc31bd602019-03-07 11:44:48 +0100269std::unique_ptr<Session> Session::connectSocket(const std::string& path)
270{
271 impl::ClientInit::instance();
272
273 auto session = std::make_unique<Session>(nc_connect_unix(path.c_str(), nullptr));
274 if (!session->m_session) {
275 throw std::runtime_error{"nc_connect_unix failed"};
276 }
277 return session;
278}
279
280std::vector<std::string_view> Session::capabilities() const
281{
282 std::vector<std::string_view> res;
283 auto caps = nc_session_get_cpblts(m_session);
284 while (*caps) {
285 res.emplace_back(*caps);
286 ++caps;
287 }
288 return res;
289}
290
Jan Kundrát9138b162020-01-30 09:27:51 +0100291std::shared_ptr<libyang::Data_Node> Session::get(const std::optional<std::string>& filter)
Václav Kubernátc31bd602019-03-07 11:44:48 +0100292{
Jan Kundrát9138b162020-01-30 09:27:51 +0100293 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 +0100294 if (!rpc) {
295 throw std::runtime_error("Cannot create get RPC");
296 }
297 auto reply = impl::do_rpc_data(this, std::move(rpc));
Jan Kundráta099fb92020-02-03 08:51:56 +0100298 auto dataNode = libyang::create_new_Data_Node(reply->data);
Václav Kubernátc31bd602019-03-07 11:44:48 +0100299 // TODO: can we do without copying?
300 // If we just default-construct a new node (or use the create_new_Data_Node) and then set reply->data to nullptr,
301 // there are mem leaks and even libnetconf2 complains loudly.
Jan Kundráta099fb92020-02-03 08:51:56 +0100302 return dataNode ? dataNode->dup_withsiblings(1) : nullptr;
Václav Kubernátc31bd602019-03-07 11:44:48 +0100303}
304
305std::string Session::getSchema(const std::string_view identifier, const std::optional<std::string_view> version)
306{
307 auto rpc = impl::guarded(nc_rpc_getschema(identifier.data(), version ? version.value().data() : nullptr, nullptr, NC_PARAMTYPE_CONST));
308 if (!rpc) {
309 throw std::runtime_error("Cannot create get-schema RPC");
310 }
311 auto reply = impl::do_rpc_data(this, std::move(rpc));
312
313 auto node = libyang::create_new_Data_Node(reply->data)->dup_withsiblings(1);
314 auto set = node->find_path("data");
315 for (auto node : set->data()) {
316 if (node->schema()->nodetype() == LYS_ANYXML) {
317 libyang::Data_Node_Anydata anydata(node);
318 return anydata.value().str;
319 }
320 }
321 throw std::runtime_error("Got a reply to get-schema, but it didn't contain the required schema");
322}
323
324std::shared_ptr<libyang::Data_Node> Session::getConfig(const NC_DATASTORE datastore, const std::optional<const std::string> filter)
325{
326 auto rpc = impl::guarded(nc_rpc_getconfig(datastore, filter ? filter->c_str() : nullptr, NC_WD_ALL, NC_PARAMTYPE_CONST));
327 if (!rpc) {
328 throw std::runtime_error("Cannot create get-config RPC");
329 }
330 auto reply = impl::do_rpc_data(this, std::move(rpc));
Václav Kubernátc31bd602019-03-07 11:44:48 +0100331 auto dataNode = libyang::create_new_Data_Node(reply->data);
Jan Kundrátf09a0922020-02-03 08:52:32 +0100332 // TODO: can we do without copying? See Session::get() for details.
333 return dataNode ? dataNode->dup_withsiblings(1) : nullptr;
Václav Kubernátc31bd602019-03-07 11:44:48 +0100334}
335
336void Session::editConfig(const NC_DATASTORE datastore,
337 const NC_RPC_EDIT_DFLTOP defaultOperation,
338 const NC_RPC_EDIT_TESTOPT testOption,
339 const NC_RPC_EDIT_ERROPT errorOption,
340 const std::string& data)
341{
342 auto rpc = impl::guarded(nc_rpc_edit(datastore, defaultOperation, testOption, errorOption, data.c_str(), NC_PARAMTYPE_CONST));
343 if (!rpc) {
344 throw std::runtime_error("Cannot create edit-config RPC");
345 }
346 impl::do_rpc_ok(this, std::move(rpc));
347}
348
349void Session::copyConfigFromString(const NC_DATASTORE target, const std::string& data)
350{
351 auto rpc = impl::guarded(nc_rpc_copy(target, nullptr, target /* yeah, cannot be 0... */, data.c_str(), NC_WD_UNKNOWN, NC_PARAMTYPE_CONST));
352 if (!rpc) {
353 throw std::runtime_error("Cannot create copy-config RPC");
354 }
355 impl::do_rpc_ok(this, std::move(rpc));
356}
357
358void Session::commit()
359{
360 auto rpc = impl::guarded(nc_rpc_commit(1, /* "Optional confirm timeout" how do you optional an uint32_t? */ 0, nullptr, nullptr, NC_PARAMTYPE_CONST));
361 if (!rpc) {
362 throw std::runtime_error("Cannot create commit RPC");
363 }
364 impl::do_rpc_ok(this, std::move(rpc));
365}
366
367void Session::discard()
368{
369 auto rpc = impl::guarded(nc_rpc_discard());
370 if (!rpc) {
371 throw std::runtime_error("Cannot create discard RPC");
372 }
373 impl::do_rpc_ok(this, std::move(rpc));
374}
375
Václav Kubernáta8789602020-07-20 15:18:19 +0200376std::shared_ptr<libyang::Data_Node> Session::rpc_or_action(const std::string& xmlData)
Jan Kundrát59acc2f2020-01-23 15:12:59 +0100377{
378 auto rpc = impl::guarded(nc_rpc_act_generic_xml(xmlData.c_str(), NC_PARAMTYPE_CONST));
379 if (!rpc) {
380 throw std::runtime_error("Cannot create generic RPC");
381 }
382 auto reply = impl::do_rpc_data_or_ok(this, std::move(rpc));
383 if (reply) {
384 auto dataNode = libyang::create_new_Data_Node((*reply)->data);
385 return dataNode->dup_withsiblings(1);
386 } else {
387 return nullptr;
388 }
389}
390
Václav Kubernát7160a132020-04-03 02:11:01 +0200391void Session::copyConfig(const NC_DATASTORE source, const NC_DATASTORE destination)
392{
393 auto rpc = impl::guarded(nc_rpc_copy(destination, nullptr, source, nullptr, NC_WD_UNKNOWN, NC_PARAMTYPE_CONST));
394 if (!rpc) {
395 throw std::runtime_error("Cannot create copy-config RPC");
396 }
397 impl::do_rpc_ok(this, std::move(rpc));
398}
399
Václav Kubernátc31bd602019-03-07 11:44:48 +0100400ReportedError::ReportedError(const std::string& what)
401 : std::runtime_error(what)
402{
403}
404
405ReportedError::~ReportedError() = default;
406}
407}