blob: 83e71c7bd87d36b8f0770230e5e938314861ae9e [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 */
Michal Vasko58791da2024-02-26 13:52:59 +0100130 if (lyd_new_any(duplicate, NULL, "data", root, LYD_ANYDATA_DATATREE, LYD_NEW_ANY_USE_VALUE | LYD_NEW_VAL_OUTPUT, NULL)) {
Roman Janota907cf932022-06-03 12:33:34 +0200131 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"
Roytak396f7272024-03-27 15:00:20 +0100201 " -u, --unix\t<path>\tCreate a UNIX socket endpoint at the place specified by <path>.\n\n");
Roman Janota907cf932022-06-03 12:33:34 +0200202}
203
204static int
Roytak396f7272024-03-27 15:00:20 +0100205init(const char *unix_socket_path, struct ly_ctx **context, struct nc_pollsession **ps)
Roman Janota907cf932022-06-03 12:33:34 +0200206{
Roman Janota907cf932022-06-03 12:33:34 +0200207 int rc = 0;
romana08a05f2023-04-05 14:46:29 +0200208 struct lyd_node *config = NULL;
romanc1d2b092023-02-02 08:58:27 +0100209
romanc1d2b092023-02-02 08:58:27 +0100210 /* create a libyang context that will determine which YANG modules will be supported by the server */
211 rc = ly_ctx_new(MODULES_DIR, 0, context);
212 if (rc) {
213 ERR_MSG_CLEANUP("Error while creating a new context.\n");
214 }
215
216 /* implement the base NETCONF modules */
217 rc = nc_server_init_ctx(context);
218 if (rc) {
219 ERR_MSG_CLEANUP("Error while initializing context.\n");
220 }
221
222 /* load all required modules for configuration, so the configuration of the server can be done */
223 rc = nc_server_config_load_modules(context);
224 if (rc) {
225 ERR_MSG_CLEANUP("Error loading modules required for configuration of the server.\n");
226 }
227
roman3adc7c02023-10-25 11:10:58 +0200228 /* apply the YANG data stored in config.json */
229 rc = nc_server_config_setup_path(*context, EXAMPLES_DIR "/config.json");
romana08a05f2023-04-05 14:46:29 +0200230 if (rc) {
231 ERR_MSG_CLEANUP("Application of configuration data failed.\n");
romanc1d2b092023-02-02 08:58:27 +0100232 }
Roman Janota907cf932022-06-03 12:33:34 +0200233
234 /* initialize the server */
235 if (nc_server_init()) {
236 ERR_MSG_CLEANUP("Error occurred while initializing the server.\n");
237 }
238
Roytak396f7272024-03-27 15:00:20 +0100239 /* create unix socket endpoint if path was set */
240 if (unix_socket_path) {
241 rc = nc_server_add_endpt_unix_socket_listen("unix-socket-endpt", unix_socket_path, -1, -1, -1);
242 if (rc) {
243 ERR_MSG_CLEANUP("Creating UNIX socket endpoint failed.\n");
244 }
245 }
246
Roman Janota907cf932022-06-03 12:33:34 +0200247 /* create a new poll session structure, which is used for polling RPCs sent by clients */
248 *ps = nc_ps_new();
249 if (!*ps) {
250 ERR_MSG_CLEANUP("Couldn't create a poll session\n");
251 }
252
253 /* set the global RPC callback, which is called every time a new RPC is received */
254 nc_set_global_rpc_clb(glob_rpc);
255
256 /* upon receiving SIGINT the handler will notify the program that is should terminate */
257 signal(SIGINT, sigint_handler);
258
259cleanup:
romana08a05f2023-04-05 14:46:29 +0200260 lyd_free_all(config);
Roman Janota907cf932022-06-03 12:33:34 +0200261 return rc;
262}
263
264int
265main(int argc, char **argv)
266{
267 int r, opt, no_new_sessions, rc = 0;
268 struct ly_ctx *context = NULL;
269 struct nc_session *session, *new_session;
270 struct nc_pollsession *ps = NULL;
Roytak396f7272024-03-27 15:00:20 +0100271 const char *unix_socket_path = NULL;
Roman Janota907cf932022-06-03 12:33:34 +0200272
273 struct option options[] = {
274 {"help", no_argument, NULL, 'h'},
Roman Janota907cf932022-06-03 12:33:34 +0200275 {"debug", no_argument, NULL, 'd'},
Roytak396f7272024-03-27 15:00:20 +0100276 {"unix", required_argument, NULL, 'u'},
Roman Janota907cf932022-06-03 12:33:34 +0200277 {NULL, 0, NULL, 0}
278 };
279
Roman Janota907cf932022-06-03 12:33:34 +0200280 opterr = 0;
281
Roytak396f7272024-03-27 15:00:20 +0100282 while ((opt = getopt_long(argc, argv, "hdu:", options, NULL)) != -1) {
Roman Janota907cf932022-06-03 12:33:34 +0200283 switch (opt) {
284 case 'h':
285 help_print();
286 goto cleanup;
287
Roman Janota907cf932022-06-03 12:33:34 +0200288 case 'd':
289 nc_verbosity(NC_VERB_DEBUG);
290 break;
291
Roytak396f7272024-03-27 15:00:20 +0100292 case 'u':
293 unix_socket_path = optarg;
294 break;
295
Roman Janota907cf932022-06-03 12:33:34 +0200296 default:
297 ERR_MSG_CLEANUP("Invalid option or missing argument\n");
298 }
299 }
300
roman3adc7c02023-10-25 11:10:58 +0200301 /* initialize the server */
Roytak396f7272024-03-27 15:00:20 +0100302 r = init(unix_socket_path, &context, &ps);
roman3adc7c02023-10-25 11:10:58 +0200303 if (r) {
304 ERR_MSG_CLEANUP("Initializing the server failed.");
305 }
306
307 printf("Listening for new connections!\n");
308
Roman Janota907cf932022-06-03 12:33:34 +0200309 while (!exit_application) {
310 no_new_sessions = 0;
311
312 /* try to accept new NETCONF sessions on all configured endpoints */
313 r = nc_accept(0, context, &session);
314
315 switch (r) {
316
317 /* session accepted and its hello message received */
318 case NC_MSG_HELLO:
319 printf("Connection established\n");
320
321 /* add the new session to the poll structure */
322 if (nc_ps_add_session(ps, session)) {
323 ERR_MSG_CLEANUP("Couldn't add session to poll\n");
324 }
325 break;
326
327 /* there were no new sessions */
328 case NC_MSG_WOULDBLOCK:
329 no_new_sessions = 1;
330 break;
331
332 /* session accepted, but its hello message was invalid */
333 case NC_MSG_BAD_HELLO:
334 printf("Parsing client hello message error.\n");
335 break;
336
337 /* something else went wrong */
338 case NC_MSG_ERROR:
339 /* accepting a session failed, but the server should continue handling RPCs on established sessions */
340 printf("Error while accepting a hello message.\n");
341 rc = 1;
342 break;
343 }
344
345 /* poll all the sessions in the structure and process a single event on a session which is then returned,
346 * in case it is a new RPC then the global RPC callback is also called */
347 r = nc_ps_poll(ps, 0, &new_session);
348
349 /* a fatal error occurred */
350 if (r & NC_PSPOLL_ERROR) {
351 ERR_MSG_CLEANUP("Error polling RPCs\n");
352 }
353
354 /* a session was terminated, so remove it from the ps structure and free it */
355 if (r & NC_PSPOLL_SESSION_TERM) {
356 r = nc_ps_del_session(ps, new_session);
357 assert(!r);
358 nc_session_free(new_session, NULL);
359 }
360
361 /* there were no new sessions and no new events on any established sessions,
362 * prevent active waiting by sleeping for a short period of time */
363 if (no_new_sessions && (r & (NC_PSPOLL_TIMEOUT | NC_PSPOLL_NOSESSIONS))) {
364 usleep(BACKOFF_TIMEOUT_USECS);
365 }
366
367 /* other set bits of the return value of nc_ps_poll() are not interesting in this example */
368 }
369
370cleanup:
371 /* free all the remaining sessions in the ps structure before destroying the context */
372 if (ps) {
373 nc_ps_clear(ps, 1, NULL);
374 }
375 nc_ps_free(ps);
376 nc_server_destroy();
romanc1d2b092023-02-02 08:58:27 +0100377 lyd_free_all(tree);
Roman Janota907cf932022-06-03 12:33:34 +0200378 ly_ctx_destroy(context);
379 return rc;
380}