blob: 0685db67d0f8dff265317901021a172ba635991e [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átcfdb9222021-07-07 22:36:24 +020010#include <libyang-cpp/Context.hpp>
11#include <libyang-cpp/DataNode.hpp>
Václav Kubernátc31bd602019-03-07 11:44:48 +010012#include <mutex>
13extern "C" {
14#include <nc_client.h>
15}
16#include <sstream>
Václav Kubernát26b56082020-02-03 18:28:56 +010017#include "UniqueResource.hpp"
Václav Kubernátb4e5b182020-11-16 19:55:09 +010018#include "netconf-client.hpp"
Václav Kubernátc31bd602019-03-07 11:44:48 +010019
20namespace libnetconf {
21
22namespace impl {
23
Václav Kubernáte2e15ee2020-02-05 17:38:13 +010024static client::LogCb logCallback;
25
26static void logViaCallback(NC_VERB_LEVEL level, const char* message)
27{
28 logCallback(level, message);
29}
30
31
Václav Kubernátc31bd602019-03-07 11:44:48 +010032/** @short Initialization of the libnetconf2 library client
33
34Just a safe wrapper over nc_client_init and nc_client_destroy, really.
35*/
36class ClientInit {
37 ClientInit()
38 {
39 nc_client_init();
Václav Kubernátc31bd602019-03-07 11:44:48 +010040 }
41
42 ~ClientInit()
43 {
44 nc_client_destroy();
45 }
46
47public:
48 static ClientInit& instance()
49 {
50 static ClientInit lib;
51 return lib;
52 }
53
54 ClientInit(const ClientInit&) = delete;
55 ClientInit(ClientInit&&) = delete;
56 ClientInit& operator=(const ClientInit&) = delete;
57 ClientInit& operator=(ClientInit&&) = delete;
58};
59
60static std::mutex clientOptions;
61
Václav Kubernátb4e5b182020-11-16 19:55:09 +010062char* 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 +010063{
64 const auto cb = static_cast<const client::KbdInteractiveCb*>(priv);
65 auto res = (*cb)(auth_name, instruction, prompt, echo);
66 return ::strdup(res.c_str());
67}
68
Václav Kubernátcfdb9222021-07-07 22:36:24 +020069auto guarded(nc_rpc* ptr)
Václav Kubernátc31bd602019-03-07 11:44:48 +010070{
Václav Kubernátcfdb9222021-07-07 22:36:24 +020071 return std::unique_ptr<nc_rpc, decltype(&nc_rpc_free)>(ptr, nc_rpc_free);
Václav Kubernátc31bd602019-03-07 11:44:48 +010072}
73
Václav Kubernátcfdb9222021-07-07 22:36:24 +020074namespace {
75const auto getData_path = "/ietf-netconf-nmda:get-data/data";
76const auto get_path = "/ietf-netconf:get/data";
77}
78
79using managed_rpc = std::invoke_result_t<decltype(guarded), nc_rpc*>;
80
81std::optional<libyang::DataNode> do_rpc(client::Session* session, managed_rpc&& rpc, const char* dataIdentifier)
Václav Kubernátc31bd602019-03-07 11:44:48 +010082{
83 uint64_t msgid;
84 NC_MSG_TYPE msgtype;
85
86 msgtype = nc_send_rpc(session->session_internal(), rpc.get(), 1000, &msgid);
87 if (msgtype == NC_MSG_ERROR) {
88 throw std::runtime_error{"Failed to send RPC"};
89 }
90 if (msgtype == NC_MSG_WOULDBLOCK) {
91 throw std::runtime_error{"Timeout sending an RPC"};
92 }
93
Václav Kubernátcfdb9222021-07-07 22:36:24 +020094 lyd_node* raw_reply;
95 lyd_node* envp;
Václav Kubernátc31bd602019-03-07 11:44:48 +010096 while (true) {
Václav Kubernátcfdb9222021-07-07 22:36:24 +020097 msgtype = nc_recv_reply(session->session_internal(), rpc.get(), msgid, 20000, &envp, &raw_reply);
98 auto replyInfo = libyang::wrapRawNode(envp);
Václav Kubernátc31bd602019-03-07 11:44:48 +010099
100 switch (msgtype) {
101 case NC_MSG_ERROR:
102 throw std::runtime_error{"Failed to receive an RPC reply"};
103 case NC_MSG_WOULDBLOCK:
104 throw std::runtime_error{"Timed out waiting for RPC reply"};
105 case NC_MSG_REPLY_ERR_MSGID:
106 throw std::runtime_error{"Received a wrong reply -- msgid mismatch"};
107 case NC_MSG_NOTIF:
108 continue;
109 default:
Václav Kubernátcfdb9222021-07-07 22:36:24 +0200110 if (!raw_reply) { // <ok> reply, or empty data node, or error
111 std::string msg;
112 for (const auto& child : replyInfo.child()->siblings()) {
113 if (child.asOpaque().name().name == "rpc-error") {
114 for (const auto& error : child.childrenDfs()) {
115 if (error.asOpaque().name().name == "error-message") {
116 msg += "Error: ";
117 msg += error.asOpaque().value();
118 }
119
120 if (error.asOpaque().name().name == "error-path") {
121 msg += "Path: ";
122 msg += error.asOpaque().value();
123 }
124
125 if (error.asOpaque().name().name == "error-type") {
126 msg += "Type: ";
127 msg += error.asOpaque().value();
128 }
129
130 if (error.asOpaque().name().name == "error-tag") {
131 msg += "Tag: ";
132 msg += error.asOpaque().value();
133 }
134
135 if (error.asOpaque().name().name == "error-app-tag") {
136 msg += "App-tag: ";
137 msg += error.asOpaque().value();
138 }
139 }
140
141 msg += "\n";
142 }
143 }
144
145 if (!msg.empty()) {
146 throw client::ReportedError{msg};
147 }
148
149 return std::nullopt;
150 }
151 auto wrapped = libyang::wrapRawNode(raw_reply);
152
153 // If we have a dataIdentifier, then we'll need to look for it.
154 // Some operations don't have that, and then the result data are just the wrapped node.
155 if (!dataIdentifier) {
156 return wrapped;
157 }
158
159 auto anydataValue = wrapped.findPath(dataIdentifier, libyang::OutputNodes::Yes)->asAny().releaseValue();
160
161 // If there's no anydata value, then that means we get empty (but valid) data.
162 if (!anydataValue) {
163 return std::nullopt;
164 }
165
166 return std::get<libyang::DataNode>(*anydataValue);
Václav Kubernátc31bd602019-03-07 11:44:48 +0100167 }
168 }
169 __builtin_unreachable();
170}
171
Václav Kubernátcfdb9222021-07-07 22:36:24 +0200172void do_rpc_ok(client::Session* session, managed_rpc&& rpc)
Václav Kubernátc31bd602019-03-07 11:44:48 +0100173{
Václav Kubernátcfdb9222021-07-07 22:36:24 +0200174 auto x = do_rpc(session, std::move(rpc), nullptr);
Jan Kundráta2a44142020-01-24 01:31:54 +0100175 if (x) {
Václav Kubernátc31bd602019-03-07 11:44:48 +0100176 throw std::runtime_error{"Unexpected DATA reply"};
Václav Kubernátc31bd602019-03-07 11:44:48 +0100177 }
178}
179}
180
181namespace client {
182
Václav Kubernáte2e15ee2020-02-05 17:38:13 +0100183void setLogLevel(NC_VERB_LEVEL level)
184{
185 nc_verbosity(level);
186}
187
188void setLogCallback(const client::LogCb& callback)
189{
190 impl::logCallback = callback;
191 nc_set_print_clb(impl::logViaCallback);
192}
193
Václav Kubernátc31bd602019-03-07 11:44:48 +0100194struct nc_session* Session::session_internal()
195{
196 return m_session;
197}
198
Václav Kubernátcfdb9222021-07-07 22:36:24 +0200199libyang::Context Session::libyangContext()
Václav Kubernát1d50a5b2020-02-03 16:44:22 +0100200{
Václav Kubernátcfdb9222021-07-07 22:36:24 +0200201 return libyang::createUnmanagedContext(const_cast<ly_ctx*>(nc_session_get_ctx(m_session)), nullptr);
Václav Kubernát1d50a5b2020-02-03 16:44:22 +0100202}
203
Václav Kubernátc31bd602019-03-07 11:44:48 +0100204Session::Session(struct nc_session* session)
205 : m_session(session)
206{
207 impl::ClientInit::instance();
208}
209
210Session::~Session()
211{
212 ::nc_session_free(m_session, nullptr);
213}
214
215std::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)
216{
217 impl::ClientInit::instance();
218
219 {
220 // FIXME: this is still horribly not enough. libnetconf *must* provide us with something better.
221 std::lock_guard lk(impl::clientOptions);
222 nc_client_ssh_set_username(user.c_str());
223 nc_client_ssh_set_auth_pref(NC_SSH_AUTH_PUBLICKEY, 5);
224 nc_client_ssh_add_keypair(pubPath.c_str(), privPath.c_str());
225 }
226 auto session = std::make_unique<Session>(nc_connect_ssh(host.c_str(), port, nullptr));
227 if (!session->m_session) {
228 throw std::runtime_error{"nc_connect_ssh failed"};
229 }
230 return session;
231}
232
Jan Kundráte0154282020-01-22 19:43:30 +0100233std::unique_ptr<Session> Session::connectKbdInteractive(const std::string& host, const uint16_t port, const std::string& user, const KbdInteractiveCb& callback)
234{
235 impl::ClientInit::instance();
236
237 std::lock_guard lk(impl::clientOptions);
238 auto cb_guard = make_unique_resource([user, &callback]() {
239 nc_client_ssh_set_username(user.c_str());
240 nc_client_ssh_set_auth_pref(NC_SSH_AUTH_INTERACTIVE, 5);
241 nc_client_ssh_set_auth_interactive_clb(impl::ssh_auth_interactive_cb, static_cast<void *>(&const_cast<KbdInteractiveCb&>(callback)));
242 }, []() {
243 nc_client_ssh_set_auth_interactive_clb(nullptr, nullptr);
244 nc_client_ssh_set_username(nullptr);
245 });
246
247 auto session = std::make_unique<Session>(nc_connect_ssh(host.c_str(), port, nullptr));
248 if (!session->m_session) {
249 throw std::runtime_error{"nc_connect_ssh failed"};
250 }
251 return session;
252}
253
Václav Kubernát7a9463f2020-10-30 08:57:59 +0100254std::unique_ptr<Session> Session::connectFd(const int source, const int sink)
255{
256 impl::ClientInit::instance();
257
258 auto session = std::make_unique<Session>(nc_connect_inout(source, sink, nullptr));
259 if (!session->m_session) {
260 throw std::runtime_error{"nc_connect_inout failed"};
261 }
262 return session;
263}
264
Václav Kubernátc31bd602019-03-07 11:44:48 +0100265std::unique_ptr<Session> Session::connectSocket(const std::string& path)
266{
267 impl::ClientInit::instance();
268
269 auto session = std::make_unique<Session>(nc_connect_unix(path.c_str(), nullptr));
270 if (!session->m_session) {
271 throw std::runtime_error{"nc_connect_unix failed"};
272 }
273 return session;
274}
275
276std::vector<std::string_view> Session::capabilities() const
277{
278 std::vector<std::string_view> res;
279 auto caps = nc_session_get_cpblts(m_session);
280 while (*caps) {
281 res.emplace_back(*caps);
282 ++caps;
283 }
284 return res;
285}
286
Václav Kubernátcfdb9222021-07-07 22:36:24 +0200287std::optional<libyang::DataNode> Session::get(const std::optional<std::string>& filter)
Václav Kubernátc31bd602019-03-07 11:44:48 +0100288{
Jan Kundrát9138b162020-01-30 09:27:51 +0100289 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 +0100290 if (!rpc) {
291 throw std::runtime_error("Cannot create get RPC");
292 }
Václav Kubernátcfdb9222021-07-07 22:36:24 +0200293 return impl::do_rpc(this, std::move(rpc), impl::get_path);
Václav Kubernátc31bd602019-03-07 11:44:48 +0100294}
295
Václav Kubernátd860d982021-01-08 13:46:02 +0100296const char* datastoreToString(NmdaDatastore datastore)
297{
298 switch (datastore) {
299 case NmdaDatastore::Startup:
300 return "ietf-datastores:startup";
301 case NmdaDatastore::Running:
302 return "ietf-datastores:running";
Václav Kubernát1fcfa9c2021-02-22 03:22:08 +0100303 case NmdaDatastore::Candidate:
304 return "ietf-datastores:candidate";
Václav Kubernátd860d982021-01-08 13:46:02 +0100305 case NmdaDatastore::Operational:
306 return "ietf-datastores:operational";
307 }
308 __builtin_unreachable();
309}
310
Václav Kubernátcfdb9222021-07-07 22:36:24 +0200311std::optional<libyang::DataNode> Session::getData(const NmdaDatastore datastore, const std::optional<std::string>& filter)
Václav Kubernátd860d982021-01-08 13:46:02 +0100312{
313 auto rpc = impl::guarded(nc_rpc_getdata(datastoreToString(datastore), filter ? filter->c_str() : nullptr, nullptr, nullptr, 0, 0, 0, 0, NC_WD_ALL, NC_PARAMTYPE_CONST));
314 if (!rpc) {
315 throw std::runtime_error("Cannot create get RPC");
316 }
Václav Kubernátcfdb9222021-07-07 22:36:24 +0200317 return impl::do_rpc(this, std::move(rpc), impl::getData_path);
Václav Kubernátd860d982021-01-08 13:46:02 +0100318}
319
Václav Kubernát1fcfa9c2021-02-22 03:22:08 +0100320void Session::editData(const NmdaDatastore datastore, const std::string& data)
321{
322 auto rpc = impl::guarded(nc_rpc_editdata(datastoreToString(datastore), NC_RPC_EDIT_DFLTOP_MERGE, data.c_str(), NC_PARAMTYPE_CONST));
323 if (!rpc) {
324 throw std::runtime_error("Cannot create get RPC");
325 }
326 return impl::do_rpc_ok(this, std::move(rpc));
327}
328
Václav Kubernátc31bd602019-03-07 11:44:48 +0100329void Session::editConfig(const NC_DATASTORE datastore,
330 const NC_RPC_EDIT_DFLTOP defaultOperation,
331 const NC_RPC_EDIT_TESTOPT testOption,
332 const NC_RPC_EDIT_ERROPT errorOption,
333 const std::string& data)
334{
335 auto rpc = impl::guarded(nc_rpc_edit(datastore, defaultOperation, testOption, errorOption, data.c_str(), NC_PARAMTYPE_CONST));
336 if (!rpc) {
337 throw std::runtime_error("Cannot create edit-config RPC");
338 }
339 impl::do_rpc_ok(this, std::move(rpc));
340}
341
342void Session::copyConfigFromString(const NC_DATASTORE target, const std::string& data)
343{
344 auto rpc = impl::guarded(nc_rpc_copy(target, nullptr, target /* yeah, cannot be 0... */, data.c_str(), NC_WD_UNKNOWN, NC_PARAMTYPE_CONST));
345 if (!rpc) {
346 throw std::runtime_error("Cannot create copy-config RPC");
347 }
348 impl::do_rpc_ok(this, std::move(rpc));
349}
350
351void Session::commit()
352{
Jan Kundrát2400fff2021-01-19 09:44:59 +0100353 auto rpc = impl::guarded(nc_rpc_commit(0, /* "Optional confirm timeout" how do you optional an uint32_t? */ 0, nullptr, nullptr, NC_PARAMTYPE_CONST));
Václav Kubernátc31bd602019-03-07 11:44:48 +0100354 if (!rpc) {
355 throw std::runtime_error("Cannot create commit RPC");
356 }
357 impl::do_rpc_ok(this, std::move(rpc));
358}
359
360void Session::discard()
361{
362 auto rpc = impl::guarded(nc_rpc_discard());
363 if (!rpc) {
364 throw std::runtime_error("Cannot create discard RPC");
365 }
366 impl::do_rpc_ok(this, std::move(rpc));
367}
368
Václav Kubernátcfdb9222021-07-07 22:36:24 +0200369std::optional<libyang::DataNode> Session::rpc_or_action(const std::string& xmlData)
Jan Kundrát59acc2f2020-01-23 15:12:59 +0100370{
371 auto rpc = impl::guarded(nc_rpc_act_generic_xml(xmlData.c_str(), NC_PARAMTYPE_CONST));
372 if (!rpc) {
373 throw std::runtime_error("Cannot create generic RPC");
374 }
Václav Kubernátcfdb9222021-07-07 22:36:24 +0200375
376 return impl::do_rpc(this, std::move(rpc), nullptr);
Jan Kundrát59acc2f2020-01-23 15:12:59 +0100377}
378
Václav Kubernát7160a132020-04-03 02:11:01 +0200379void Session::copyConfig(const NC_DATASTORE source, const NC_DATASTORE destination)
380{
381 auto rpc = impl::guarded(nc_rpc_copy(destination, nullptr, source, nullptr, NC_WD_UNKNOWN, NC_PARAMTYPE_CONST));
382 if (!rpc) {
383 throw std::runtime_error("Cannot create copy-config RPC");
384 }
385 impl::do_rpc_ok(this, std::move(rpc));
386}
387
Václav Kubernátc31bd602019-03-07 11:44:48 +0100388ReportedError::ReportedError(const std::string& what)
389 : std::runtime_error(what)
390{
391}
392
393ReportedError::~ReportedError() = default;
394}
395}