blob: 2a55c7719ce8d9ca7bdcb2339ce97344f2c16ec9 [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"
33#include "session_server.h"
34#include "session_server_ch.h"
35
36volatile int exit_application = 0;
37
38static void
39sigint_handler(int signum)
40{
41 (void) signum;
42 /* notify the main loop if we should exit */
43 exit_application = 1;
44}
45
46static struct nc_server_reply *
47get_rpc(struct lyd_node *rpc, struct nc_session *session)
48{
49 const struct ly_ctx *ctx;
50 const char *xpath;
51 struct lyd_node *root = NULL, *root2 = NULL, *duplicate = NULL;
52 struct lyd_node *filter, *err;
53 struct lyd_meta *m, *type = NULL, *select = NULL;
54 struct ly_set *set = NULL;
55
56 ctx = nc_session_get_ctx(session);
57
58 /* load the ietf-yang-library data of the session, which represent this server's state data */
59 if (ly_ctx_get_yanglib_data(ctx, &root, "%u", ly_ctx_get_change_count(ctx))) {
60 err = nc_err(ctx, NC_ERR_OP_FAILED, NC_ERR_TYPE_APP);
61 goto error;
62 }
63
64 /* search for the optional filter in the RPC */
65 if (lyd_find_path(rpc, "filter", 0, &filter)) {
66 err = nc_err(ctx, NC_ERR_OP_FAILED, NC_ERR_TYPE_APP);
67 goto error;
68 }
69
70 if (filter) {
71 /* look for the expected filter attributes type and select */
72 LY_LIST_FOR(filter->meta, m) {
73 if (!strcmp(m->name, "type")) {
74 type = m;
75 }
76 if (!strcmp(m->name, "select")) {
77 select = m;
78 }
79 }
80
81 /* only XPath filter is supported */
82 if (!type || strcmp(lyd_get_meta_value(type), "xpath") || !select) {
83 err = nc_err(ctx, NC_ERR_OP_NOT_SUPPORTED, NC_ERR_TYPE_APP);
84 goto error;
85 }
86 xpath = lyd_get_meta_value(select);
87
88 /* find all the subtrees matching the filter */
89 if (lyd_find_xpath(root, xpath, &set)) {
90 err = nc_err(ctx, NC_ERR_OP_FAILED, NC_ERR_TYPE_APP);
91 goto error;
92 }
93
94 root2 = NULL;
95 for (uint32_t i = 0; i < set->count; i++) {
96 /* create a copy of the subtree with its parent nodes */
97 if (lyd_dup_single(set->dnodes[i], NULL, LYD_DUP_RECURSIVE | LYD_DUP_WITH_PARENTS, &duplicate)) {
98 err = nc_err(ctx, NC_ERR_OP_FAILED, NC_ERR_TYPE_APP);
99 goto error;
100 }
101
102 /* merge another top-level filtered subtree into the result */
103 while (duplicate->parent) {
104 duplicate = lyd_parent(duplicate);
105 }
106 if (lyd_merge_tree(&root2, duplicate, LYD_MERGE_DESTRUCT)) {
107 err = nc_err(ctx, NC_ERR_OP_FAILED, NC_ERR_TYPE_APP);
108 goto error;
109 }
110 duplicate = NULL;
111 }
112
113 /* replace the original full data with only the filtered data */
114 lyd_free_siblings(root);
115 root = root2;
116 root2 = NULL;
117 }
118
119 /* duplicate the rpc node without its input nodes so the output nodes can be appended */
120 if (lyd_dup_single(rpc, NULL, 0, &duplicate)) {
121 err = nc_err(ctx, NC_ERR_OP_FAILED, NC_ERR_TYPE_APP);
122 goto error;
123 }
124
125 /* create the get RPC anyxml "data" output node with the requested data */
126 if (lyd_new_any(duplicate, NULL, "data", root, 1, LYD_ANYDATA_DATATREE, 1, NULL)) {
127 err = nc_err(ctx, NC_ERR_OP_FAILED, NC_ERR_TYPE_APP);
128 goto error;
129 }
130
131 ly_set_free(set, NULL);
132
133 /* send data reply with the RPC output data */
134 return nc_server_reply_data(duplicate, NC_WD_UNKNOWN, NC_PARAMTYPE_FREE);
135
136error:
137 ly_set_free(set, NULL);
138 lyd_free_siblings(root);
139 lyd_free_siblings(duplicate);
140 lyd_free_siblings(root2);
141
142 /* send error reply with the specific NETCONF error */
143 return nc_server_reply_err(err);
144}
145
146static struct nc_server_reply *
147glob_rpc(struct lyd_node *rpc, struct nc_session *session)
148{
149 struct lyd_node *iter;
150 struct lyd_meta *m;
151
152 printf("Received RPC:\n");
153
154 /* iterate over all the nodes in the RPC */
155 LYD_TREE_DFS_BEGIN(rpc, iter) {
156 /* if the node has a value, then print its name and value */
157 if (iter->schema->nodetype & (LYD_NODE_TERM | LYD_NODE_ANY)) {
158 printf(" %s = \"%s\"\n", LYD_NAME(iter), lyd_get_value(iter));
159 /* then iterate through all the metadata, which may include the XPath filter */
160 LY_LIST_FOR(iter->meta, m) {
161 printf(" %s = \"%s\"\n", m->name, lyd_get_meta_value(m));
162 }
163 /* else print just the name */
164 } else if (iter->schema->nodetype == LYS_RPC) {
165 printf(" %s\n", LYD_NAME(iter));
166 }
167
168 LYD_TREE_DFS_END(rpc, iter);
169 }
170
171 /* if close-session RPC is received, then call library's default function to properly close the session */
172 if (!strcmp(LYD_NAME(rpc), "close-session") && !strcmp(lyd_owner_module(rpc)->name, "ietf-netconf")) {
173 return nc_clb_default_close_session(rpc, session);
174 }
175
176 /* if get-schema RPC is received, then use the library implementation of this RPC */
177 if (!strcmp(LYD_NAME(rpc), "get-schema") && !strcmp(lyd_owner_module(rpc)->name, "ietf-netconf-monitoring")) {
178 return nc_clb_default_get_schema(rpc, session);
179 }
180
181 if (!strcmp(LYD_NAME(rpc), "get") && !strcmp(lyd_owner_module(rpc)->name, "ietf-netconf")) {
182 return get_rpc(rpc, session);
183 }
184
185 /* return an okay reply to every other RPC */
186 return nc_server_reply_ok();
187}
188
189static void
190help_print()
191{
192 printf("Example usage:\n"
193 " server -u ./unix_socket\n"
194 "\n"
195 " Available options:\n"
196 " -h, --help\t \tPrint usage help.\n"
197 " -u, --unix\t<path>\tCreate a UNIX socket at the place specified by <path>.\n"
198 " -s, --ssh\t<path>\tCreate a SSH server with the host SSH key located at <path>.\n\n");
199}
200
201static int
202hostkey_callback(const char *name, void *user_data, char **privkey_path, char **privkey_data, NC_SSH_KEY_TYPE *privkey_type)
203{
204 /* return only known hostkey */
205 if (strcmp(name, "server_hostkey")) {
206 return 1;
207 }
208
209 /* the hostkey is in a file */
210 *privkey_path = strdup(user_data);
211 *privkey_data = NULL;
212 *privkey_type = NC_SSH_KEY_UNKNOWN;
213
214 return 0;
215}
216
217static int
218password_callback(const struct nc_session *session, const char *password, void *user_data)
219{
220 (void) user_data;
221 const char *username;
222
223 /* get username from the NETCONF session */
224 username = nc_session_get_username(session);
225
226 /* compare it with the defined username and password */
227 if (strcmp(username, SSH_USERNAME) || strcmp(password, SSH_PASSWORD)) {
228 return 1;
229 }
230
231 return 0;
232}
233
234static int
235init(struct ly_ctx **context, struct nc_pollsession **ps, const char *path, NC_TRANSPORT_IMPL server_type)
236{
237 struct lys_module *module;
238 int rc = 0;
239 const char *features[] = {"*", NULL};
240
241 /* initialize the server */
242 if (nc_server_init()) {
243 ERR_MSG_CLEANUP("Error occurred while initializing the server.\n");
244 }
245
246 if (server_type == NC_TI_UNIX) {
247 /* add a new UNIX socket endpoint with an arbitrary name main_unix */
248 if (nc_server_add_endpt("main_unix", NC_TI_UNIX)) {
249 ERR_MSG_CLEANUP("Couldn't add end point.\n");
250 }
251
252 /* set endpoint listening address to the path from the parameter */
253 if (nc_server_endpt_set_address("main_unix", path)) {
254 ERR_MSG_CLEANUP("Couldn't set address of end point.\n");
255 }
256 } else {
257 /* add a new SSH endpoint with an arbitrary name main_ssh */
258 if (nc_server_add_endpt("main_ssh", NC_TI_LIBSSH)) {
259 ERR_MSG_CLEANUP("Couldn't add end point.\n");
260 }
261
262 /* set generic hostkey callback which will be used for retrieving all the hostkeys */
263 nc_server_ssh_set_hostkey_clb(hostkey_callback, (void *)path, NULL);
264
265 /* set 'password' SSH authentication callback */
266 nc_server_ssh_set_passwd_auth_clb(password_callback, NULL, NULL);
267
268 /* add a new hostkey called server_hostkey, whose data will be retrieved by the hostkey callback */
269 nc_server_ssh_endpt_add_hostkey("main_ssh", "server_hostkey", -1);
270
271 /* set endpoint listening address to the defined IP address */
272 if (nc_server_endpt_set_address("main_ssh", SSH_ADDRESS)) {
273 ERR_MSG_CLEANUP("Couldn't set address of end point.\n");
274 }
275
276 /* set endpoint listening port to the defined one */
277 if (nc_server_endpt_set_port("main_ssh", SSH_PORT)) {
Michal Vasko5143f2e2022-12-12 07:37:38 +0100278 ERR_MSG_CLEANUP("Couldn't set port of end point.\n");
Roman Janota907cf932022-06-03 12:33:34 +0200279 }
280
281 /* allow only 'password' SSH authentication method for the endpoint */
282 if (nc_server_ssh_endpt_set_auth_methods("main_ssh", NC_SSH_AUTH_PASSWORD)) {
Michal Vasko5143f2e2022-12-12 07:37:38 +0100283 ERR_MSG_CLEANUP("Couldn't set authentication methods of end point.\n");
Roman Janota907cf932022-06-03 12:33:34 +0200284 }
285 }
286
287 /* create a libyang context that will determine which YANG modules will be supported by the server */
288 if (ly_ctx_new(MODULES_DIR, 0, context)) {
289 ERR_MSG_CLEANUP("Couldn't create new libyang context.\n");
290 }
291
292 /* support and load the base NETCONF ietf-netconf module with all its features enabled */
293 module = ly_ctx_load_module(*context, "ietf-netconf", NULL, features);
294 if (!module) {
295 ERR_MSG_CLEANUP("Couldn't load ietf-netconf module.\n");
296 }
297
298 /* support get-schema RPC for the server to be able to send YANG modules */
299 module = ly_ctx_load_module(*context, "ietf-netconf-monitoring", NULL, features);
300 if (!module) {
301 ERR_MSG_CLEANUP("Couldn't load ietf-netconf-monitoring module.\n");
302 }
303
304 /* create a new poll session structure, which is used for polling RPCs sent by clients */
305 *ps = nc_ps_new();
306 if (!*ps) {
307 ERR_MSG_CLEANUP("Couldn't create a poll session\n");
308 }
309
310 /* set the global RPC callback, which is called every time a new RPC is received */
311 nc_set_global_rpc_clb(glob_rpc);
312
313 /* upon receiving SIGINT the handler will notify the program that is should terminate */
314 signal(SIGINT, sigint_handler);
315
316cleanup:
317 return rc;
318}
319
320int
321main(int argc, char **argv)
322{
323 int r, opt, no_new_sessions, rc = 0;
324 struct ly_ctx *context = NULL;
325 struct nc_session *session, *new_session;
326 struct nc_pollsession *ps = NULL;
327 const char *unix_socket_path = NULL, *ssh_public_key_path = NULL;
328
329 struct option options[] = {
330 {"help", no_argument, NULL, 'h'},
331 {"unix", required_argument, NULL, 'u'},
332 {"ssh", required_argument, NULL, 's'},
333 {"debug", no_argument, NULL, 'd'},
334 {NULL, 0, NULL, 0}
335 };
336
337 if (argc == 1) {
338 help_print();
339 goto cleanup;
340 }
341
342 opterr = 0;
343
344 while ((opt = getopt_long(argc, argv, "hu:s:d", options, NULL)) != -1) {
345 switch (opt) {
346 case 'h':
347 help_print();
348 goto cleanup;
349
350 case 'u':
351 unix_socket_path = optarg;
352 if (init(&context, &ps, unix_socket_path, NC_TI_UNIX)) {
353 ERR_MSG_CLEANUP("Failed to initialize a UNIX socket\n");
354 }
355 printf("Using UNIX socket!\n");
356 break;
357
358 case 's':
359 ssh_public_key_path = optarg;
360 if (init(&context, &ps, ssh_public_key_path, NC_TI_LIBSSH)) {
361 ERR_MSG_CLEANUP("Failed to initialize a SSH server\n");
362 }
363 printf("Using SSH!\n");
364 break;
365
366 case 'd':
367 nc_verbosity(NC_VERB_DEBUG);
368 break;
369
370 default:
371 ERR_MSG_CLEANUP("Invalid option or missing argument\n");
372 }
373 }
374
375 while (!exit_application) {
376 no_new_sessions = 0;
377
378 /* try to accept new NETCONF sessions on all configured endpoints */
379 r = nc_accept(0, context, &session);
380
381 switch (r) {
382
383 /* session accepted and its hello message received */
384 case NC_MSG_HELLO:
385 printf("Connection established\n");
386
387 /* add the new session to the poll structure */
388 if (nc_ps_add_session(ps, session)) {
389 ERR_MSG_CLEANUP("Couldn't add session to poll\n");
390 }
391 break;
392
393 /* there were no new sessions */
394 case NC_MSG_WOULDBLOCK:
395 no_new_sessions = 1;
396 break;
397
398 /* session accepted, but its hello message was invalid */
399 case NC_MSG_BAD_HELLO:
400 printf("Parsing client hello message error.\n");
401 break;
402
403 /* something else went wrong */
404 case NC_MSG_ERROR:
405 /* accepting a session failed, but the server should continue handling RPCs on established sessions */
406 printf("Error while accepting a hello message.\n");
407 rc = 1;
408 break;
409 }
410
411 /* poll all the sessions in the structure and process a single event on a session which is then returned,
412 * in case it is a new RPC then the global RPC callback is also called */
413 r = nc_ps_poll(ps, 0, &new_session);
414
415 /* a fatal error occurred */
416 if (r & NC_PSPOLL_ERROR) {
417 ERR_MSG_CLEANUP("Error polling RPCs\n");
418 }
419
420 /* a session was terminated, so remove it from the ps structure and free it */
421 if (r & NC_PSPOLL_SESSION_TERM) {
422 r = nc_ps_del_session(ps, new_session);
423 assert(!r);
424 nc_session_free(new_session, NULL);
425 }
426
427 /* there were no new sessions and no new events on any established sessions,
428 * prevent active waiting by sleeping for a short period of time */
429 if (no_new_sessions && (r & (NC_PSPOLL_TIMEOUT | NC_PSPOLL_NOSESSIONS))) {
430 usleep(BACKOFF_TIMEOUT_USECS);
431 }
432
433 /* other set bits of the return value of nc_ps_poll() are not interesting in this example */
434 }
435
436cleanup:
437 /* free all the remaining sessions in the ps structure before destroying the context */
438 if (ps) {
439 nc_ps_clear(ps, 1, NULL);
440 }
441 nc_ps_free(ps);
442 nc_server_destroy();
443 ly_ctx_destroy(context);
444 return rc;
445}