blob: bfa6ece882431559cbd33ea3e7be9918815f68fd [file] [log] [blame]
Roman Janota907cf932022-06-03 12:33:34 +02001/**
2 * @file server.c
3 * @author Roman Janota <xjanot04@fit.vutbr.cz>
4 * @brief libnetconf2 server example
5 *
6 * @copyright
7 * Copyright (c) 2022 CESNET, z.s.p.o.
8 *
9 * This source code is licensed under BSD 3-Clause License (the "License").
10 * You may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
12 *
13 * https://opensource.org/licenses/BSD-3-Clause
14 */
15
16#define _GNU_SOURCE
17#include "example.h"
18
19#include <assert.h>
20#include <getopt.h>
21#include <signal.h>
22#include <stdint.h>
23#include <stdio.h>
24#include <stdlib.h>
25#include <string.h>
26#include <unistd.h>
27
28#include <libyang/libyang.h>
Roman Janota907cf932022-06-03 12:33:34 +020029
30#include "log.h"
31#include "messages_server.h"
32#include "netconf.h"
romane028ef92023-02-24 16:33:08 +010033#include "server_config.h"
Roman Janota907cf932022-06-03 12:33:34 +020034#include "session_server.h"
35#include "session_server_ch.h"
36
37volatile int exit_application = 0;
romanc1d2b092023-02-02 08:58:27 +010038struct lyd_node *tree;
Roman Janota907cf932022-06-03 12:33:34 +020039
40static void
41sigint_handler(int signum)
42{
43 (void) signum;
44 /* notify the main loop if we should exit */
45 exit_application = 1;
46}
47
48static struct nc_server_reply *
49get_rpc(struct lyd_node *rpc, struct nc_session *session)
50{
51 const struct ly_ctx *ctx;
52 const char *xpath;
53 struct lyd_node *root = NULL, *root2 = NULL, *duplicate = NULL;
54 struct lyd_node *filter, *err;
55 struct lyd_meta *m, *type = NULL, *select = NULL;
56 struct ly_set *set = NULL;
romanc1d2b092023-02-02 08:58:27 +010057 LY_ERR ret;
Roman Janota907cf932022-06-03 12:33:34 +020058
59 ctx = nc_session_get_ctx(session);
60
61 /* load the ietf-yang-library data of the session, which represent this server's state data */
62 if (ly_ctx_get_yanglib_data(ctx, &root, "%u", ly_ctx_get_change_count(ctx))) {
63 err = nc_err(ctx, NC_ERR_OP_FAILED, NC_ERR_TYPE_APP);
64 goto error;
65 }
66
67 /* search for the optional filter in the RPC */
romanc1d2b092023-02-02 08:58:27 +010068 ret = lyd_find_path(rpc, "filter", 0, &filter);
69 if (ret && (ret != LY_ENOTFOUND)) {
Roman Janota907cf932022-06-03 12:33:34 +020070 err = nc_err(ctx, NC_ERR_OP_FAILED, NC_ERR_TYPE_APP);
71 goto error;
72 }
73
74 if (filter) {
75 /* look for the expected filter attributes type and select */
76 LY_LIST_FOR(filter->meta, m) {
77 if (!strcmp(m->name, "type")) {
78 type = m;
79 }
80 if (!strcmp(m->name, "select")) {
81 select = m;
82 }
83 }
84
85 /* only XPath filter is supported */
86 if (!type || strcmp(lyd_get_meta_value(type), "xpath") || !select) {
87 err = nc_err(ctx, NC_ERR_OP_NOT_SUPPORTED, NC_ERR_TYPE_APP);
88 goto error;
89 }
90 xpath = lyd_get_meta_value(select);
91
92 /* find all the subtrees matching the filter */
93 if (lyd_find_xpath(root, xpath, &set)) {
94 err = nc_err(ctx, NC_ERR_OP_FAILED, NC_ERR_TYPE_APP);
95 goto error;
96 }
97
98 root2 = NULL;
99 for (uint32_t i = 0; i < set->count; i++) {
100 /* create a copy of the subtree with its parent nodes */
101 if (lyd_dup_single(set->dnodes[i], NULL, LYD_DUP_RECURSIVE | LYD_DUP_WITH_PARENTS, &duplicate)) {
102 err = nc_err(ctx, NC_ERR_OP_FAILED, NC_ERR_TYPE_APP);
103 goto error;
104 }
105
106 /* merge another top-level filtered subtree into the result */
107 while (duplicate->parent) {
108 duplicate = lyd_parent(duplicate);
109 }
110 if (lyd_merge_tree(&root2, duplicate, LYD_MERGE_DESTRUCT)) {
111 err = nc_err(ctx, NC_ERR_OP_FAILED, NC_ERR_TYPE_APP);
112 goto error;
113 }
114 duplicate = NULL;
115 }
116
117 /* replace the original full data with only the filtered data */
118 lyd_free_siblings(root);
119 root = root2;
120 root2 = NULL;
121 }
122
123 /* duplicate the rpc node without its input nodes so the output nodes can be appended */
124 if (lyd_dup_single(rpc, NULL, 0, &duplicate)) {
125 err = nc_err(ctx, NC_ERR_OP_FAILED, NC_ERR_TYPE_APP);
126 goto error;
127 }
128
129 /* create the get RPC anyxml "data" output node with the requested data */
130 if (lyd_new_any(duplicate, NULL, "data", root, 1, LYD_ANYDATA_DATATREE, 1, NULL)) {
131 err = nc_err(ctx, NC_ERR_OP_FAILED, NC_ERR_TYPE_APP);
132 goto error;
133 }
134
135 ly_set_free(set, NULL);
136
137 /* send data reply with the RPC output data */
138 return nc_server_reply_data(duplicate, NC_WD_UNKNOWN, NC_PARAMTYPE_FREE);
139
140error:
141 ly_set_free(set, NULL);
142 lyd_free_siblings(root);
143 lyd_free_siblings(duplicate);
144 lyd_free_siblings(root2);
145
146 /* send error reply with the specific NETCONF error */
147 return nc_server_reply_err(err);
148}
149
150static struct nc_server_reply *
151glob_rpc(struct lyd_node *rpc, struct nc_session *session)
152{
153 struct lyd_node *iter;
154 struct lyd_meta *m;
155
156 printf("Received RPC:\n");
157
158 /* iterate over all the nodes in the RPC */
159 LYD_TREE_DFS_BEGIN(rpc, iter) {
160 /* if the node has a value, then print its name and value */
161 if (iter->schema->nodetype & (LYD_NODE_TERM | LYD_NODE_ANY)) {
162 printf(" %s = \"%s\"\n", LYD_NAME(iter), lyd_get_value(iter));
163 /* then iterate through all the metadata, which may include the XPath filter */
164 LY_LIST_FOR(iter->meta, m) {
165 printf(" %s = \"%s\"\n", m->name, lyd_get_meta_value(m));
166 }
167 /* else print just the name */
168 } else if (iter->schema->nodetype == LYS_RPC) {
169 printf(" %s\n", LYD_NAME(iter));
170 }
171
172 LYD_TREE_DFS_END(rpc, iter);
173 }
174
175 /* if close-session RPC is received, then call library's default function to properly close the session */
176 if (!strcmp(LYD_NAME(rpc), "close-session") && !strcmp(lyd_owner_module(rpc)->name, "ietf-netconf")) {
177 return nc_clb_default_close_session(rpc, session);
178 }
179
180 /* if get-schema RPC is received, then use the library implementation of this RPC */
181 if (!strcmp(LYD_NAME(rpc), "get-schema") && !strcmp(lyd_owner_module(rpc)->name, "ietf-netconf-monitoring")) {
182 return nc_clb_default_get_schema(rpc, session);
183 }
184
185 if (!strcmp(LYD_NAME(rpc), "get") && !strcmp(lyd_owner_module(rpc)->name, "ietf-netconf")) {
186 return get_rpc(rpc, session);
187 }
188
189 /* return an okay reply to every other RPC */
190 return nc_server_reply_ok();
191}
192
193static void
194help_print()
195{
196 printf("Example usage:\n"
197 " server -u ./unix_socket\n"
198 "\n"
199 " Available options:\n"
200 " -h, --help\t \tPrint usage help.\n"
201 " -u, --unix\t<path>\tCreate a UNIX socket at the place specified by <path>.\n"
202 " -s, --ssh\t<path>\tCreate a SSH server with the host SSH key located at <path>.\n\n");
203}
204
205static int
Roman Janota907cf932022-06-03 12:33:34 +0200206init(struct ly_ctx **context, struct nc_pollsession **ps, const char *path, NC_TRANSPORT_IMPL server_type)
207{
Roman Janota907cf932022-06-03 12:33:34 +0200208 int rc = 0;
romana08a05f2023-04-05 14:46:29 +0200209 const char *hostkey_path = TESTS_DIR "/data/server.key";
210 struct lyd_node *config = NULL;
romanc1d2b092023-02-02 08:58:27 +0100211
212 if (path) {
213 /* if a path is supplied, then use it */
romana08a05f2023-04-05 14:46:29 +0200214 hostkey_path = path;
romanc1d2b092023-02-02 08:58:27 +0100215 }
216
217 if (server_type == NC_TI_UNIX) {
218 ERR_MSG_CLEANUP("Only support SSH for now.\n");
219 }
220
221 /* create a libyang context that will determine which YANG modules will be supported by the server */
222 rc = ly_ctx_new(MODULES_DIR, 0, context);
223 if (rc) {
224 ERR_MSG_CLEANUP("Error while creating a new context.\n");
225 }
226
227 /* implement the base NETCONF modules */
228 rc = nc_server_init_ctx(context);
229 if (rc) {
230 ERR_MSG_CLEANUP("Error while initializing context.\n");
231 }
232
233 /* load all required modules for configuration, so the configuration of the server can be done */
234 rc = nc_server_config_load_modules(context);
235 if (rc) {
236 ERR_MSG_CLEANUP("Error loading modules required for configuration of the server.\n");
237 }
238
romana08a05f2023-04-05 14:46:29 +0200239 /* this is where the YANG configuration data gets generated,
240 * start by creating hostkey configuration data */
roman3f9b65c2023-06-05 14:26:58 +0200241 rc = nc_server_config_new_ssh_hostkey(*context, "endpt", "hostkey", hostkey_path, NULL, &config);
romanc1d2b092023-02-02 08:58:27 +0100242 if (rc) {
romana08a05f2023-04-05 14:46:29 +0200243 ERR_MSG_CLEANUP("Error creating new hostkey configuration data.\n");
244 }
245
246 /* create address and port configuration data */
roman3f9b65c2023-06-05 14:26:58 +0200247 rc = nc_server_config_new_address_port(*context, "endpt", NC_TI_LIBSSH, SSH_ADDRESS, SSH_PORT, &config);
romana08a05f2023-04-05 14:46:29 +0200248 if (rc) {
249 ERR_MSG_CLEANUP("Error creating new address and port configuration data.\n");
250 }
251
252 /* create client authentication configuration data */
roman3f9b65c2023-06-05 14:26:58 +0200253 rc = nc_server_config_new_ssh_client_auth_password(*context, "endpt", SSH_USERNAME, SSH_PASSWORD, &config);
romana08a05f2023-04-05 14:46:29 +0200254 if (rc) {
255 ERR_MSG_CLEANUP("Error creating client authentication configuration data.\n");
256 }
257
258 /* apply the created configuration data */
romanf6f37a52023-05-25 14:27:51 +0200259 rc = nc_server_config_setup_diff(config);
romana08a05f2023-04-05 14:46:29 +0200260 if (rc) {
261 ERR_MSG_CLEANUP("Application of configuration data failed.\n");
romanc1d2b092023-02-02 08:58:27 +0100262 }
Roman Janota907cf932022-06-03 12:33:34 +0200263
264 /* initialize the server */
265 if (nc_server_init()) {
266 ERR_MSG_CLEANUP("Error occurred while initializing the server.\n");
267 }
268
Roman Janota907cf932022-06-03 12:33:34 +0200269 /* create a new poll session structure, which is used for polling RPCs sent by clients */
270 *ps = nc_ps_new();
271 if (!*ps) {
272 ERR_MSG_CLEANUP("Couldn't create a poll session\n");
273 }
274
275 /* set the global RPC callback, which is called every time a new RPC is received */
276 nc_set_global_rpc_clb(glob_rpc);
277
278 /* upon receiving SIGINT the handler will notify the program that is should terminate */
279 signal(SIGINT, sigint_handler);
280
281cleanup:
romana08a05f2023-04-05 14:46:29 +0200282 lyd_free_all(config);
Roman Janota907cf932022-06-03 12:33:34 +0200283 return rc;
284}
285
286int
287main(int argc, char **argv)
288{
289 int r, opt, no_new_sessions, rc = 0;
290 struct ly_ctx *context = NULL;
291 struct nc_session *session, *new_session;
292 struct nc_pollsession *ps = NULL;
romana08a05f2023-04-05 14:46:29 +0200293 const char *unix_socket_path = NULL, *hostkey_path = NULL;
Roman Janota907cf932022-06-03 12:33:34 +0200294
295 struct option options[] = {
296 {"help", no_argument, NULL, 'h'},
297 {"unix", required_argument, NULL, 'u'},
298 {"ssh", required_argument, NULL, 's'},
299 {"debug", no_argument, NULL, 'd'},
300 {NULL, 0, NULL, 0}
301 };
302
303 if (argc == 1) {
304 help_print();
305 goto cleanup;
306 }
307
308 opterr = 0;
309
romanc1d2b092023-02-02 08:58:27 +0100310 while ((opt = getopt_long(argc, argv, ":s:hu:d", options, NULL)) != -1) {
Roman Janota907cf932022-06-03 12:33:34 +0200311 switch (opt) {
312 case 'h':
313 help_print();
314 goto cleanup;
315
316 case 'u':
317 unix_socket_path = optarg;
318 if (init(&context, &ps, unix_socket_path, NC_TI_UNIX)) {
319 ERR_MSG_CLEANUP("Failed to initialize a UNIX socket\n");
320 }
321 printf("Using UNIX socket!\n");
322 break;
323
324 case 's':
romana08a05f2023-04-05 14:46:29 +0200325 hostkey_path = optarg;
326 if (init(&context, &ps, hostkey_path, NC_TI_LIBSSH)) {
Roman Janota907cf932022-06-03 12:33:34 +0200327 ERR_MSG_CLEANUP("Failed to initialize a SSH server\n");
romanc1d2b092023-02-02 08:58:27 +0100328 goto cleanup;
Roman Janota907cf932022-06-03 12:33:34 +0200329 }
330 printf("Using SSH!\n");
331 break;
332
333 case 'd':
334 nc_verbosity(NC_VERB_DEBUG);
335 break;
336
romanc1d2b092023-02-02 08:58:27 +0100337 case ':':
338 if (optopt == 's') {
339 if (init(&context, &ps, NULL, NC_TI_LIBSSH)) {
340 ERR_MSG_CLEANUP("Failed to initialize a SSH server\n");
341 goto cleanup;
342 }
343 printf("Using SSH!\n");
344 break;
345 } else {
346 ERR_MSG_CLEANUP("Invalid option or missing argument\n");
347 }
348
Roman Janota907cf932022-06-03 12:33:34 +0200349 default:
350 ERR_MSG_CLEANUP("Invalid option or missing argument\n");
351 }
352 }
353
354 while (!exit_application) {
355 no_new_sessions = 0;
356
357 /* try to accept new NETCONF sessions on all configured endpoints */
358 r = nc_accept(0, context, &session);
359
360 switch (r) {
361
362 /* session accepted and its hello message received */
363 case NC_MSG_HELLO:
364 printf("Connection established\n");
365
366 /* add the new session to the poll structure */
367 if (nc_ps_add_session(ps, session)) {
368 ERR_MSG_CLEANUP("Couldn't add session to poll\n");
369 }
370 break;
371
372 /* there were no new sessions */
373 case NC_MSG_WOULDBLOCK:
374 no_new_sessions = 1;
375 break;
376
377 /* session accepted, but its hello message was invalid */
378 case NC_MSG_BAD_HELLO:
379 printf("Parsing client hello message error.\n");
380 break;
381
382 /* something else went wrong */
383 case NC_MSG_ERROR:
384 /* accepting a session failed, but the server should continue handling RPCs on established sessions */
385 printf("Error while accepting a hello message.\n");
386 rc = 1;
387 break;
388 }
389
390 /* poll all the sessions in the structure and process a single event on a session which is then returned,
391 * in case it is a new RPC then the global RPC callback is also called */
392 r = nc_ps_poll(ps, 0, &new_session);
393
394 /* a fatal error occurred */
395 if (r & NC_PSPOLL_ERROR) {
396 ERR_MSG_CLEANUP("Error polling RPCs\n");
397 }
398
399 /* a session was terminated, so remove it from the ps structure and free it */
400 if (r & NC_PSPOLL_SESSION_TERM) {
401 r = nc_ps_del_session(ps, new_session);
402 assert(!r);
403 nc_session_free(new_session, NULL);
404 }
405
406 /* there were no new sessions and no new events on any established sessions,
407 * prevent active waiting by sleeping for a short period of time */
408 if (no_new_sessions && (r & (NC_PSPOLL_TIMEOUT | NC_PSPOLL_NOSESSIONS))) {
409 usleep(BACKOFF_TIMEOUT_USECS);
410 }
411
412 /* other set bits of the return value of nc_ps_poll() are not interesting in this example */
413 }
414
415cleanup:
416 /* free all the remaining sessions in the ps structure before destroying the context */
417 if (ps) {
418 nc_ps_clear(ps, 1, NULL);
419 }
420 nc_ps_free(ps);
421 nc_server_destroy();
romanc1d2b092023-02-02 08:58:27 +0100422 lyd_free_all(tree);
Roman Janota907cf932022-06-03 12:33:34 +0200423 ly_ctx_destroy(context);
424 return rc;
425}