blob: 713aecb727349981ea3d216a6ab8dc2a8caa6294 [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
roman3adc7c02023-10-25 11:10:58 +0200206init(struct ly_ctx **context, struct nc_pollsession **ps)
Roman Janota907cf932022-06-03 12:33:34 +0200207{
Roman Janota907cf932022-06-03 12:33:34 +0200208 int rc = 0;
romana08a05f2023-04-05 14:46:29 +0200209 struct lyd_node *config = NULL;
romanc1d2b092023-02-02 08:58:27 +0100210
romanc1d2b092023-02-02 08:58:27 +0100211 /* create a libyang context that will determine which YANG modules will be supported by the server */
212 rc = ly_ctx_new(MODULES_DIR, 0, context);
213 if (rc) {
214 ERR_MSG_CLEANUP("Error while creating a new context.\n");
215 }
216
217 /* implement the base NETCONF modules */
218 rc = nc_server_init_ctx(context);
219 if (rc) {
220 ERR_MSG_CLEANUP("Error while initializing context.\n");
221 }
222
223 /* load all required modules for configuration, so the configuration of the server can be done */
224 rc = nc_server_config_load_modules(context);
225 if (rc) {
226 ERR_MSG_CLEANUP("Error loading modules required for configuration of the server.\n");
227 }
228
roman3adc7c02023-10-25 11:10:58 +0200229 /* apply the YANG data stored in config.json */
230 rc = nc_server_config_setup_path(*context, EXAMPLES_DIR "/config.json");
romana08a05f2023-04-05 14:46:29 +0200231 if (rc) {
232 ERR_MSG_CLEANUP("Application of configuration data failed.\n");
romanc1d2b092023-02-02 08:58:27 +0100233 }
Roman Janota907cf932022-06-03 12:33:34 +0200234
235 /* initialize the server */
236 if (nc_server_init()) {
237 ERR_MSG_CLEANUP("Error occurred while initializing the server.\n");
238 }
239
Roman Janota907cf932022-06-03 12:33:34 +0200240 /* create a new poll session structure, which is used for polling RPCs sent by clients */
241 *ps = nc_ps_new();
242 if (!*ps) {
243 ERR_MSG_CLEANUP("Couldn't create a poll session\n");
244 }
245
246 /* set the global RPC callback, which is called every time a new RPC is received */
247 nc_set_global_rpc_clb(glob_rpc);
248
249 /* upon receiving SIGINT the handler will notify the program that is should terminate */
250 signal(SIGINT, sigint_handler);
251
252cleanup:
romana08a05f2023-04-05 14:46:29 +0200253 lyd_free_all(config);
Roman Janota907cf932022-06-03 12:33:34 +0200254 return rc;
255}
256
257int
258main(int argc, char **argv)
259{
260 int r, opt, no_new_sessions, rc = 0;
261 struct ly_ctx *context = NULL;
262 struct nc_session *session, *new_session;
263 struct nc_pollsession *ps = NULL;
Roman Janota907cf932022-06-03 12:33:34 +0200264
265 struct option options[] = {
266 {"help", no_argument, NULL, 'h'},
Roman Janota907cf932022-06-03 12:33:34 +0200267 {"debug", no_argument, NULL, 'd'},
268 {NULL, 0, NULL, 0}
269 };
270
Roman Janota907cf932022-06-03 12:33:34 +0200271 opterr = 0;
272
roman3adc7c02023-10-25 11:10:58 +0200273 while ((opt = getopt_long(argc, argv, "hd", options, NULL)) != -1) {
Roman Janota907cf932022-06-03 12:33:34 +0200274 switch (opt) {
275 case 'h':
276 help_print();
277 goto cleanup;
278
Roman Janota907cf932022-06-03 12:33:34 +0200279 case 'd':
280 nc_verbosity(NC_VERB_DEBUG);
281 break;
282
283 default:
284 ERR_MSG_CLEANUP("Invalid option or missing argument\n");
285 }
286 }
287
roman3adc7c02023-10-25 11:10:58 +0200288 /* initialize the server */
289 r = init(&context, &ps);
290 if (r) {
291 ERR_MSG_CLEANUP("Initializing the server failed.");
292 }
293
294 printf("Listening for new connections!\n");
295
Roman Janota907cf932022-06-03 12:33:34 +0200296 while (!exit_application) {
297 no_new_sessions = 0;
298
299 /* try to accept new NETCONF sessions on all configured endpoints */
300 r = nc_accept(0, context, &session);
301
302 switch (r) {
303
304 /* session accepted and its hello message received */
305 case NC_MSG_HELLO:
306 printf("Connection established\n");
307
308 /* add the new session to the poll structure */
309 if (nc_ps_add_session(ps, session)) {
310 ERR_MSG_CLEANUP("Couldn't add session to poll\n");
311 }
312 break;
313
314 /* there were no new sessions */
315 case NC_MSG_WOULDBLOCK:
316 no_new_sessions = 1;
317 break;
318
319 /* session accepted, but its hello message was invalid */
320 case NC_MSG_BAD_HELLO:
321 printf("Parsing client hello message error.\n");
322 break;
323
324 /* something else went wrong */
325 case NC_MSG_ERROR:
326 /* accepting a session failed, but the server should continue handling RPCs on established sessions */
327 printf("Error while accepting a hello message.\n");
328 rc = 1;
329 break;
330 }
331
332 /* poll all the sessions in the structure and process a single event on a session which is then returned,
333 * in case it is a new RPC then the global RPC callback is also called */
334 r = nc_ps_poll(ps, 0, &new_session);
335
336 /* a fatal error occurred */
337 if (r & NC_PSPOLL_ERROR) {
338 ERR_MSG_CLEANUP("Error polling RPCs\n");
339 }
340
341 /* a session was terminated, so remove it from the ps structure and free it */
342 if (r & NC_PSPOLL_SESSION_TERM) {
343 r = nc_ps_del_session(ps, new_session);
344 assert(!r);
345 nc_session_free(new_session, NULL);
346 }
347
348 /* there were no new sessions and no new events on any established sessions,
349 * prevent active waiting by sleeping for a short period of time */
350 if (no_new_sessions && (r & (NC_PSPOLL_TIMEOUT | NC_PSPOLL_NOSESSIONS))) {
351 usleep(BACKOFF_TIMEOUT_USECS);
352 }
353
354 /* other set bits of the return value of nc_ps_poll() are not interesting in this example */
355 }
356
357cleanup:
358 /* free all the remaining sessions in the ps structure before destroying the context */
359 if (ps) {
360 nc_ps_clear(ps, 1, NULL);
361 }
362 nc_ps_free(ps);
363 nc_server_destroy();
romanc1d2b092023-02-02 08:58:27 +0100364 lyd_free_all(tree);
Roman Janota907cf932022-06-03 12:33:34 +0200365 ly_ctx_destroy(context);
366 return rc;
367}