blob: 794f5b1d052375d4263f68c3c90eed2a504174aa [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átc31bd602019-03-07 11:44:48 +010016#include "netconf-client.h"
Jan Kundráte0154282020-01-22 19:43:30 +010017#include "UniqueResource.h"
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átc31bd602019-03-07 11:44:48 +010070template <auto fn>
71using deleter_from_fn = std::integral_constant<decltype(fn), fn>;
72
73template <typename T>
74struct deleter_type_for {
75 using func_type = void (*)(T*);
76};
77
78template <typename T>
79struct deleter_for {
80};
81
82template <>
83struct deleter_for<struct nc_rpc> {
84 static constexpr void (*free)(struct nc_rpc*) = deleter_from_fn<nc_rpc_free>();
85};
86template <>
87struct deleter_for<struct nc_reply> {
88 static constexpr void (*free)(struct nc_reply*) = deleter_from_fn<nc_reply_free>();
89};
90template <>
91struct deleter_for<struct nc_reply_data> {
92 static constexpr void (*free)(struct nc_reply_data*) = deleter_from_fn<custom_free_nc_reply_data>();
93};
94template <>
95struct deleter_for<struct nc_reply_error> {
96 static constexpr void (*free)(struct nc_reply_error*) = deleter_from_fn<custom_free_nc_reply_error>();
97};
98
99template <typename T>
100using unique_ptr_for = std::unique_ptr<T, decltype(deleter_for<T>::free)>;
101
102template <typename T>
103auto guarded(T* ptr)
104{
105 return unique_ptr_for<T>(ptr, deleter_for<T>::free);
106}
107
108unique_ptr_for<struct nc_reply> do_rpc(client::Session* session, unique_ptr_for<struct nc_rpc>&& rpc)
109{
110 uint64_t msgid;
111 NC_MSG_TYPE msgtype;
112
113 msgtype = nc_send_rpc(session->session_internal(), rpc.get(), 1000, &msgid);
114 if (msgtype == NC_MSG_ERROR) {
115 throw std::runtime_error{"Failed to send RPC"};
116 }
117 if (msgtype == NC_MSG_WOULDBLOCK) {
118 throw std::runtime_error{"Timeout sending an RPC"};
119 }
120
121 struct nc_reply* raw_reply;
122 while (true) {
123 msgtype = nc_recv_reply(session->session_internal(), rpc.get(), msgid, 20000, LYD_OPT_DESTRUCT | LYD_OPT_NOSIBLINGS, &raw_reply);
124 auto reply = guarded(raw_reply);
125 raw_reply = nullptr;
126
127 switch (msgtype) {
128 case NC_MSG_ERROR:
129 throw std::runtime_error{"Failed to receive an RPC reply"};
130 case NC_MSG_WOULDBLOCK:
131 throw std::runtime_error{"Timed out waiting for RPC reply"};
132 case NC_MSG_REPLY_ERR_MSGID:
133 throw std::runtime_error{"Received a wrong reply -- msgid mismatch"};
134 case NC_MSG_NOTIF:
135 continue;
136 default:
137 return reply;
138 }
139 }
140 __builtin_unreachable();
141}
142
143client::ReportedError make_error(unique_ptr_for<struct nc_reply>&& reply)
144{
145 if (reply->type != NC_RPL_ERROR) {
146 throw std::logic_error{"Cannot extract an error from a non-error server reply"};
147 }
148
149 auto errorReply = guarded(reinterpret_cast<struct nc_reply_error*>(reply.release()));
150
151 // TODO: capture the error details, not just that human-readable string
152 std::ostringstream ss;
153 ss << "Server error:" << std::endl;
154 for (uint32_t i = 0; i < errorReply->count; ++i) {
155 const auto e = errorReply->err[i];
156 ss << " #" << i << ": " << e.message;
157 if (e.path) {
158 ss << " (XPath " << e.path << ")";
159 }
160 ss << std::endl;
161 }
162 return client::ReportedError{ss.str()};
163}
164
Jan Kundráta2a44142020-01-24 01:31:54 +0100165std::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 +0100166{
167 auto x = do_rpc(session, std::move(rpc));
168
169 switch (x->type) {
170 case NC_RPL_DATA:
171 return guarded(reinterpret_cast<struct nc_reply_data*>(x.release()));
172 case NC_RPL_OK:
Jan Kundráta2a44142020-01-24 01:31:54 +0100173 return std::nullopt;
Václav Kubernátc31bd602019-03-07 11:44:48 +0100174 case NC_RPL_ERROR:
175 throw make_error(std::move(x));
176 default:
177 throw std::runtime_error{"Unhandled reply type"};
178 }
Jan Kundráta2a44142020-01-24 01:31:54 +0100179
180}
181
182unique_ptr_for<struct nc_reply_data> do_rpc_data(client::Session* session, unique_ptr_for<struct nc_rpc>&& rpc)
183{
184 auto x = do_rpc_data_or_ok(session, std::move(rpc));
185 if (!x) {
186 throw std::runtime_error{"Received OK instead of a data reply"};
187 }
188 return std::move(*x);
Václav Kubernátc31bd602019-03-07 11:44:48 +0100189}
190
191void do_rpc_ok(client::Session* session, unique_ptr_for<struct nc_rpc>&& rpc)
192{
Jan Kundráta2a44142020-01-24 01:31:54 +0100193 auto x = do_rpc_data_or_ok(session, std::move(rpc));
194 if (x) {
Václav Kubernátc31bd602019-03-07 11:44:48 +0100195 throw std::runtime_error{"Unexpected DATA reply"};
Václav Kubernátc31bd602019-03-07 11:44:48 +0100196 }
197}
198}
199
200namespace client {
201
202struct nc_session* Session::session_internal()
203{
204 return m_session;
205}
206
207Session::Session(struct nc_session* session)
208 : m_session(session)
209{
210 impl::ClientInit::instance();
211}
212
213Session::~Session()
214{
215 ::nc_session_free(m_session, nullptr);
216}
217
218std::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)
219{
220 impl::ClientInit::instance();
221
222 {
223 // FIXME: this is still horribly not enough. libnetconf *must* provide us with something better.
224 std::lock_guard lk(impl::clientOptions);
225 nc_client_ssh_set_username(user.c_str());
226 nc_client_ssh_set_auth_pref(NC_SSH_AUTH_PUBLICKEY, 5);
227 nc_client_ssh_add_keypair(pubPath.c_str(), privPath.c_str());
228 }
229 auto session = std::make_unique<Session>(nc_connect_ssh(host.c_str(), port, nullptr));
230 if (!session->m_session) {
231 throw std::runtime_error{"nc_connect_ssh failed"};
232 }
233 return session;
234}
235
Jan Kundráte0154282020-01-22 19:43:30 +0100236std::unique_ptr<Session> Session::connectKbdInteractive(const std::string& host, const uint16_t port, const std::string& user, const KbdInteractiveCb& callback)
237{
238 impl::ClientInit::instance();
239
240 std::lock_guard lk(impl::clientOptions);
241 auto cb_guard = make_unique_resource([user, &callback]() {
242 nc_client_ssh_set_username(user.c_str());
243 nc_client_ssh_set_auth_pref(NC_SSH_AUTH_INTERACTIVE, 5);
244 nc_client_ssh_set_auth_interactive_clb(impl::ssh_auth_interactive_cb, static_cast<void *>(&const_cast<KbdInteractiveCb&>(callback)));
245 }, []() {
246 nc_client_ssh_set_auth_interactive_clb(nullptr, nullptr);
247 nc_client_ssh_set_username(nullptr);
248 });
249
250 auto session = std::make_unique<Session>(nc_connect_ssh(host.c_str(), port, nullptr));
251 if (!session->m_session) {
252 throw std::runtime_error{"nc_connect_ssh failed"};
253 }
254 return session;
255}
256
Václav Kubernátc31bd602019-03-07 11:44:48 +0100257std::unique_ptr<Session> Session::connectSocket(const std::string& path)
258{
259 impl::ClientInit::instance();
260
261 auto session = std::make_unique<Session>(nc_connect_unix(path.c_str(), nullptr));
262 if (!session->m_session) {
263 throw std::runtime_error{"nc_connect_unix failed"};
264 }
265 return session;
266}
267
268std::vector<std::string_view> Session::capabilities() const
269{
270 std::vector<std::string_view> res;
271 auto caps = nc_session_get_cpblts(m_session);
272 while (*caps) {
273 res.emplace_back(*caps);
274 ++caps;
275 }
276 return res;
277}
278
Jan Kundrát9138b162020-01-30 09:27:51 +0100279std::shared_ptr<libyang::Data_Node> Session::get(const std::optional<std::string>& filter)
Václav Kubernátc31bd602019-03-07 11:44:48 +0100280{
Jan Kundrát9138b162020-01-30 09:27:51 +0100281 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 +0100282 if (!rpc) {
283 throw std::runtime_error("Cannot create get RPC");
284 }
285 auto reply = impl::do_rpc_data(this, std::move(rpc));
Jan Kundráta099fb92020-02-03 08:51:56 +0100286 auto dataNode = libyang::create_new_Data_Node(reply->data);
Václav Kubernátc31bd602019-03-07 11:44:48 +0100287 // TODO: can we do without copying?
288 // If we just default-construct a new node (or use the create_new_Data_Node) and then set reply->data to nullptr,
289 // there are mem leaks and even libnetconf2 complains loudly.
Jan Kundráta099fb92020-02-03 08:51:56 +0100290 return dataNode ? dataNode->dup_withsiblings(1) : nullptr;
Václav Kubernátc31bd602019-03-07 11:44:48 +0100291}
292
293std::string Session::getSchema(const std::string_view identifier, const std::optional<std::string_view> version)
294{
295 auto rpc = impl::guarded(nc_rpc_getschema(identifier.data(), version ? version.value().data() : nullptr, nullptr, NC_PARAMTYPE_CONST));
296 if (!rpc) {
297 throw std::runtime_error("Cannot create get-schema RPC");
298 }
299 auto reply = impl::do_rpc_data(this, std::move(rpc));
300
301 auto node = libyang::create_new_Data_Node(reply->data)->dup_withsiblings(1);
302 auto set = node->find_path("data");
303 for (auto node : set->data()) {
304 if (node->schema()->nodetype() == LYS_ANYXML) {
305 libyang::Data_Node_Anydata anydata(node);
306 return anydata.value().str;
307 }
308 }
309 throw std::runtime_error("Got a reply to get-schema, but it didn't contain the required schema");
310}
311
312std::shared_ptr<libyang::Data_Node> Session::getConfig(const NC_DATASTORE datastore, const std::optional<const std::string> filter)
313{
314 auto rpc = impl::guarded(nc_rpc_getconfig(datastore, filter ? filter->c_str() : nullptr, NC_WD_ALL, NC_PARAMTYPE_CONST));
315 if (!rpc) {
316 throw std::runtime_error("Cannot create get-config RPC");
317 }
318 auto reply = impl::do_rpc_data(this, std::move(rpc));
Václav Kubernátc31bd602019-03-07 11:44:48 +0100319 auto dataNode = libyang::create_new_Data_Node(reply->data);
Jan Kundrátf09a0922020-02-03 08:52:32 +0100320 // TODO: can we do without copying? See Session::get() for details.
321 return dataNode ? dataNode->dup_withsiblings(1) : nullptr;
Václav Kubernátc31bd602019-03-07 11:44:48 +0100322}
323
324void Session::editConfig(const NC_DATASTORE datastore,
325 const NC_RPC_EDIT_DFLTOP defaultOperation,
326 const NC_RPC_EDIT_TESTOPT testOption,
327 const NC_RPC_EDIT_ERROPT errorOption,
328 const std::string& data)
329{
330 auto rpc = impl::guarded(nc_rpc_edit(datastore, defaultOperation, testOption, errorOption, data.c_str(), NC_PARAMTYPE_CONST));
331 if (!rpc) {
332 throw std::runtime_error("Cannot create edit-config RPC");
333 }
334 impl::do_rpc_ok(this, std::move(rpc));
335}
336
337void Session::copyConfigFromString(const NC_DATASTORE target, const std::string& data)
338{
339 auto rpc = impl::guarded(nc_rpc_copy(target, nullptr, target /* yeah, cannot be 0... */, data.c_str(), NC_WD_UNKNOWN, NC_PARAMTYPE_CONST));
340 if (!rpc) {
341 throw std::runtime_error("Cannot create copy-config RPC");
342 }
343 impl::do_rpc_ok(this, std::move(rpc));
344}
345
346void Session::commit()
347{
348 auto rpc = impl::guarded(nc_rpc_commit(1, /* "Optional confirm timeout" how do you optional an uint32_t? */ 0, nullptr, nullptr, NC_PARAMTYPE_CONST));
349 if (!rpc) {
350 throw std::runtime_error("Cannot create commit RPC");
351 }
352 impl::do_rpc_ok(this, std::move(rpc));
353}
354
355void Session::discard()
356{
357 auto rpc = impl::guarded(nc_rpc_discard());
358 if (!rpc) {
359 throw std::runtime_error("Cannot create discard RPC");
360 }
361 impl::do_rpc_ok(this, std::move(rpc));
362}
363
Jan Kundrát59acc2f2020-01-23 15:12:59 +0100364std::shared_ptr<libyang::Data_Node> Session::rpc(const std::string& xmlData)
365{
366 auto rpc = impl::guarded(nc_rpc_act_generic_xml(xmlData.c_str(), NC_PARAMTYPE_CONST));
367 if (!rpc) {
368 throw std::runtime_error("Cannot create generic RPC");
369 }
370 auto reply = impl::do_rpc_data_or_ok(this, std::move(rpc));
371 if (reply) {
372 auto dataNode = libyang::create_new_Data_Node((*reply)->data);
373 return dataNode->dup_withsiblings(1);
374 } else {
375 return nullptr;
376 }
377}
378
Václav Kubernátc31bd602019-03-07 11:44:48 +0100379ReportedError::ReportedError(const std::string& what)
380 : std::runtime_error(what)
381{
382}
383
384ReportedError::~ReportedError() = default;
385}
386}