blob: c0e7cc574a0d5e5af799e5ebee5bd3bd8aaa5d1c [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
romanc1d2b092023-02-02 08:58:27 +010030#include "config_server.h"
Roman Janota907cf932022-06-03 12:33:34 +020031#include "log.h"
32#include "messages_server.h"
33#include "netconf.h"
34#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;
romanc1d2b092023-02-02 08:58:27 +0100209 const char *config_file_path = EXAMPLES_DIR "/config.xml";
210
211 if (path) {
212 /* if a path is supplied, then use it */
213 config_file_path = path;
214 }
215
216 if (server_type == NC_TI_UNIX) {
217 ERR_MSG_CLEANUP("Only support SSH for now.\n");
218 }
219
220 /* create a libyang context that will determine which YANG modules will be supported by the server */
221 rc = ly_ctx_new(MODULES_DIR, 0, context);
222 if (rc) {
223 ERR_MSG_CLEANUP("Error while creating a new context.\n");
224 }
225
226 /* implement the base NETCONF modules */
227 rc = nc_server_init_ctx(context);
228 if (rc) {
229 ERR_MSG_CLEANUP("Error while initializing context.\n");
230 }
231
232 /* load all required modules for configuration, so the configuration of the server can be done */
233 rc = nc_server_config_load_modules(context);
234 if (rc) {
235 ERR_MSG_CLEANUP("Error loading modules required for configuration of the server.\n");
236 }
237
238 /* parse YANG data from a file, configure the server based on the parsed YANG configuration data */
239 rc = nc_server_config_setup_path(*context, config_file_path);
240 if (rc) {
241 ERR_MSG_CLEANUP("Error setting the path to the configuration data.\n");
242 }
Roman Janota907cf932022-06-03 12:33:34 +0200243
244 /* initialize the server */
245 if (nc_server_init()) {
246 ERR_MSG_CLEANUP("Error occurred while initializing the server.\n");
247 }
248
Roman Janota907cf932022-06-03 12:33:34 +0200249 /* create a new poll session structure, which is used for polling RPCs sent by clients */
250 *ps = nc_ps_new();
251 if (!*ps) {
252 ERR_MSG_CLEANUP("Couldn't create a poll session\n");
253 }
254
255 /* set the global RPC callback, which is called every time a new RPC is received */
256 nc_set_global_rpc_clb(glob_rpc);
257
258 /* upon receiving SIGINT the handler will notify the program that is should terminate */
259 signal(SIGINT, sigint_handler);
260
261cleanup:
262 return rc;
263}
264
265int
266main(int argc, char **argv)
267{
268 int r, opt, no_new_sessions, rc = 0;
269 struct ly_ctx *context = NULL;
270 struct nc_session *session, *new_session;
271 struct nc_pollsession *ps = NULL;
romanc1d2b092023-02-02 08:58:27 +0100272 const char *unix_socket_path = NULL, *config_file_path = NULL;
Roman Janota907cf932022-06-03 12:33:34 +0200273
274 struct option options[] = {
275 {"help", no_argument, NULL, 'h'},
276 {"unix", required_argument, NULL, 'u'},
277 {"ssh", required_argument, NULL, 's'},
278 {"debug", no_argument, NULL, 'd'},
279 {NULL, 0, NULL, 0}
280 };
281
282 if (argc == 1) {
283 help_print();
284 goto cleanup;
285 }
286
287 opterr = 0;
288
romanc1d2b092023-02-02 08:58:27 +0100289 while ((opt = getopt_long(argc, argv, ":s:hu:d", options, NULL)) != -1) {
Roman Janota907cf932022-06-03 12:33:34 +0200290 switch (opt) {
291 case 'h':
292 help_print();
293 goto cleanup;
294
295 case 'u':
296 unix_socket_path = optarg;
297 if (init(&context, &ps, unix_socket_path, NC_TI_UNIX)) {
298 ERR_MSG_CLEANUP("Failed to initialize a UNIX socket\n");
299 }
300 printf("Using UNIX socket!\n");
301 break;
302
303 case 's':
romanc1d2b092023-02-02 08:58:27 +0100304 config_file_path = optarg;
305 if (init(&context, &ps, config_file_path, NC_TI_LIBSSH)) {
Roman Janota907cf932022-06-03 12:33:34 +0200306 ERR_MSG_CLEANUP("Failed to initialize a SSH server\n");
romanc1d2b092023-02-02 08:58:27 +0100307 goto cleanup;
Roman Janota907cf932022-06-03 12:33:34 +0200308 }
309 printf("Using SSH!\n");
310 break;
311
312 case 'd':
313 nc_verbosity(NC_VERB_DEBUG);
314 break;
315
romanc1d2b092023-02-02 08:58:27 +0100316 case ':':
317 if (optopt == 's') {
318 if (init(&context, &ps, NULL, NC_TI_LIBSSH)) {
319 ERR_MSG_CLEANUP("Failed to initialize a SSH server\n");
320 goto cleanup;
321 }
322 printf("Using SSH!\n");
323 break;
324 } else {
325 ERR_MSG_CLEANUP("Invalid option or missing argument\n");
326 }
327
Roman Janota907cf932022-06-03 12:33:34 +0200328 default:
329 ERR_MSG_CLEANUP("Invalid option or missing argument\n");
330 }
331 }
332
333 while (!exit_application) {
334 no_new_sessions = 0;
335
336 /* try to accept new NETCONF sessions on all configured endpoints */
337 r = nc_accept(0, context, &session);
338
339 switch (r) {
340
341 /* session accepted and its hello message received */
342 case NC_MSG_HELLO:
343 printf("Connection established\n");
344
345 /* add the new session to the poll structure */
346 if (nc_ps_add_session(ps, session)) {
347 ERR_MSG_CLEANUP("Couldn't add session to poll\n");
348 }
349 break;
350
351 /* there were no new sessions */
352 case NC_MSG_WOULDBLOCK:
353 no_new_sessions = 1;
354 break;
355
356 /* session accepted, but its hello message was invalid */
357 case NC_MSG_BAD_HELLO:
358 printf("Parsing client hello message error.\n");
359 break;
360
361 /* something else went wrong */
362 case NC_MSG_ERROR:
363 /* accepting a session failed, but the server should continue handling RPCs on established sessions */
364 printf("Error while accepting a hello message.\n");
365 rc = 1;
366 break;
367 }
368
369 /* poll all the sessions in the structure and process a single event on a session which is then returned,
370 * in case it is a new RPC then the global RPC callback is also called */
371 r = nc_ps_poll(ps, 0, &new_session);
372
373 /* a fatal error occurred */
374 if (r & NC_PSPOLL_ERROR) {
375 ERR_MSG_CLEANUP("Error polling RPCs\n");
376 }
377
378 /* a session was terminated, so remove it from the ps structure and free it */
379 if (r & NC_PSPOLL_SESSION_TERM) {
380 r = nc_ps_del_session(ps, new_session);
381 assert(!r);
382 nc_session_free(new_session, NULL);
383 }
384
385 /* there were no new sessions and no new events on any established sessions,
386 * prevent active waiting by sleeping for a short period of time */
387 if (no_new_sessions && (r & (NC_PSPOLL_TIMEOUT | NC_PSPOLL_NOSESSIONS))) {
388 usleep(BACKOFF_TIMEOUT_USECS);
389 }
390
391 /* other set bits of the return value of nc_ps_poll() are not interesting in this example */
392 }
393
394cleanup:
395 /* free all the remaining sessions in the ps structure before destroying the context */
396 if (ps) {
397 nc_ps_clear(ps, 1, NULL);
398 }
399 nc_ps_free(ps);
400 nc_server_destroy();
romanc1d2b092023-02-02 08:58:27 +0100401 lyd_free_all(tree);
Roman Janota907cf932022-06-03 12:33:34 +0200402 ly_ctx_destroy(context);
403 return rc;
404}