-
Notifications
You must be signed in to change notification settings - Fork 156
Expand file tree
/
Copy pathsession_server.c
More file actions
4662 lines (3982 loc) · 141 KB
/
session_server.c
File metadata and controls
4662 lines (3982 loc) · 141 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file session_server.c
* @author Michal Vasko <mvasko@cesnet.cz>
* @brief libnetconf2 server session manipulation functions
*
* @copyright
* Copyright (c) 2015 - 2024 CESNET, z.s.p.o.
*
* This source code is licensed under BSD 3-Clause License (the "License").
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*/
#define _GNU_SOURCE /* threads */
#include <arpa/inet.h>
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <pthread.h>
#include <pwd.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/un.h>
#include <time.h>
#include <unistd.h>
#include "compat.h"
#include "config.h"
#include "log_p.h"
#include "messages_p.h"
#include "messages_server.h"
#include "server_config.h"
#include "session.h"
#include "session_p.h"
#include "session_server.h"
#include "session_server_ch.h"
#ifdef NC_ENABLED_SSH_TLS
#include "session_wrapper.h"
#include <curl/curl.h>
#include <libssh/libssh.h>
#endif /* NC_ENABLED_SSH_TLS */
struct nc_server_opts server_opts = {
.hello_lock = PTHREAD_RWLOCK_INITIALIZER,
.config_lock = PTHREAD_RWLOCK_INITIALIZER,
.config_update_lock = PTHREAD_MUTEX_INITIALIZER,
};
static nc_rpc_clb global_rpc_clb = NULL;
#ifdef NC_ENABLED_SSH_TLS
/**
* @brief Get a CH client with the given @p name .
*
* @note The configuration read lock must be held.
*
* @param[in] name Name of the CH client to find.
* @return CH client, NULL if not found.
*/
static struct nc_ch_client *
nc_server_ch_client_get(const char *name)
{
struct nc_ch_client *client = NULL;
assert(name);
LY_ARRAY_FOR(server_opts.config.ch_clients, struct nc_ch_client, client) {
if (client->name && !strcmp(client->name, name)) {
return client;
}
}
return NULL;
}
#endif /* NC_ENABLED_SSH_TLS */
int
nc_server_endpt_get(const char *name, struct nc_endpt **endpt)
{
struct nc_endpt *ep;
*endpt = NULL;
LY_ARRAY_FOR(server_opts.config.endpts, struct nc_endpt, ep) {
if (ep->name && !strcmp(ep->name, name)) {
*endpt = ep;
return 0;
}
}
ERR(NULL, "Endpoint \"%s\" not found in the configuration.", name);
return 1;
}
API void
nc_session_set_term_reason(struct nc_session *session, NC_SESSION_TERM_REASON reason)
{
if (!session) {
ERRARG(session, "session");
return;
} else if (!reason) {
ERRARG(session, "reason");
return;
}
if ((reason != NC_SESSION_TERM_KILLED) && (session->term_reason == NC_SESSION_TERM_KILLED)) {
session->killed_by = 0;
}
session->term_reason = reason;
}
API void
nc_session_set_killed_by(struct nc_session *session, uint32_t sid)
{
if (!session || (session->term_reason != NC_SESSION_TERM_KILLED)) {
ERRARG(session, "session");
return;
} else if (!sid) {
ERRARG(session, "sid");
return;
}
session->killed_by = sid;
}
API void
nc_session_set_status(struct nc_session *session, NC_STATUS status)
{
if (!session) {
ERRARG(session, "session");
return;
} else if (!status) {
ERRARG(session, "status");
return;
}
session->status = status;
}
API int
nc_server_init_ctx(struct ly_ctx **ctx)
{
int new_ctx = 0, i, ret = 0;
struct lys_module *module;
/* all features */
const char *ietf_netconf_features[] = {"writable-running", "candidate", "rollback-on-error", "validate", "startup", "url", "xpath", "confirmed-commit", NULL};
/* all features (module has no features) */
const char *ietf_netconf_monitoring_features[] = {NULL};
NC_CHECK_ARG_RET(NULL, ctx, 1);
if (!*ctx) {
/* context not given, create a new one */
if (ly_ctx_new(NC_SERVER_SEARCH_DIR, 0, ctx)) {
ERR(NULL, "Couldn't create new libyang context.\n");
ret = 1;
goto cleanup;
}
new_ctx = 1;
}
if (new_ctx) {
/* new context created, implement both modules */
if (!ly_ctx_load_module(*ctx, "ietf-netconf", NULL, ietf_netconf_features)) {
ERR(NULL, "Loading module \"ietf-netconf\" failed.\n");
ret = 1;
goto cleanup;
}
if (!ly_ctx_load_module(*ctx, "ietf-netconf-monitoring", NULL, ietf_netconf_monitoring_features)) {
ERR(NULL, "Loading module \"ietf-netconf-monitoring\" failed.\n");
ret = 1;
goto cleanup;
}
goto cleanup;
}
module = ly_ctx_get_module_implemented(*ctx, "ietf-netconf");
if (module) {
/* ietf-netconf module is present, check features */
for (i = 0; ietf_netconf_features[i]; i++) {
if (lys_feature_value(module, ietf_netconf_features[i])) {
/* feature not found, enable all of them */
if (!ly_ctx_load_module(*ctx, "ietf-netconf", NULL, ietf_netconf_features)) {
ERR(NULL, "Loading module \"ietf-netconf\" failed.\n");
ret = 1;
goto cleanup;
}
break;
}
}
} else {
/* ietf-netconf module not found, add it */
if (!ly_ctx_load_module(*ctx, "ietf-netconf", NULL, ietf_netconf_features)) {
ERR(NULL, "Loading module \"ietf-netconf\" failed.\n");
ret = 1;
goto cleanup;
}
}
module = ly_ctx_get_module_implemented(*ctx, "ietf-netconf-monitoring");
if (!module) {
/* ietf-netconf-monitoring module not found, add it */
if (!ly_ctx_load_module(*ctx, "ietf-netconf-monitoring", NULL, ietf_netconf_monitoring_features)) {
ERR(NULL, "Loading module \"ietf-netconf-monitoring\" failed.\n");
ret = 1;
goto cleanup;
}
}
cleanup:
if (new_ctx && ret) {
ly_ctx_destroy(*ctx);
*ctx = NULL;
}
return ret;
}
#ifdef NC_ENABLED_SSH_TLS
API void
nc_server_ch_set_dispatch_data(nc_server_ch_session_acquire_ctx_cb acquire_ctx_cb,
nc_server_ch_session_release_ctx_cb release_ctx_cb, void *ctx_cb_data, nc_server_ch_new_session_cb new_session_cb,
void *new_session_cb_data)
{
NC_CHECK_ARG_RET(NULL, acquire_ctx_cb, release_ctx_cb, new_session_cb, );
/* CONFIG WRITE LOCK */
if (nc_rwlock_lock(&server_opts.config_lock, NC_RWLOCK_WRITE, NC_CONFIG_LOCK_TIMEOUT, __func__) != 1) {
return;
}
server_opts.ch_dispatch_data.acquire_ctx_cb = acquire_ctx_cb;
server_opts.ch_dispatch_data.release_ctx_cb = release_ctx_cb;
server_opts.ch_dispatch_data.ctx_cb_data = ctx_cb_data;
server_opts.ch_dispatch_data.new_session_cb = new_session_cb;
server_opts.ch_dispatch_data.new_session_cb_data = new_session_cb_data;
/* CONFIG WRITE UNLOCK */
nc_rwlock_unlock(&server_opts.config_lock, __func__);
}
API void
nc_server_ch_set_new_session_fail_cb(nc_server_ch_new_session_fail_cb new_session_fail_cb,
void *new_session_fail_cb_data)
{
/* CONFIG WRITE LOCK */
if (nc_rwlock_lock(&server_opts.config_lock, NC_RWLOCK_WRITE, NC_CONFIG_LOCK_TIMEOUT, __func__) != 1) {
return;
}
server_opts.ch_dispatch_data.new_session_fail_cb = new_session_fail_cb;
server_opts.ch_dispatch_data.new_session_fail_cb_data = new_session_fail_cb_data;
/* CONFIG WRITE UNLOCK */
nc_rwlock_unlock(&server_opts.config_lock, __func__);
}
#endif
int
nc_sock_bind_inet(int sock, const char *address, uint16_t port, int is_ipv4)
{
struct sockaddr_storage saddr;
struct sockaddr_in *saddr4;
struct sockaddr_in6 *saddr6;
memset(&saddr, 0, sizeof(struct sockaddr_storage));
if (is_ipv4) {
saddr4 = (struct sockaddr_in *)&saddr;
saddr4->sin_family = AF_INET;
saddr4->sin_port = htons(port);
/* determine the address */
if (!address) {
/* set the implicit default IPv4 address */
address = "0.0.0.0";
}
if (inet_pton(AF_INET, address, &saddr4->sin_addr) != 1) {
ERR(NULL, "Failed to convert IPv4 address \"%s\".", address);
return -1;
}
if (bind(sock, (struct sockaddr *)saddr4, sizeof(struct sockaddr_in)) == -1) {
ERR(NULL, "Could not bind %s:%" PRIu16 " (%s).", address, port, strerror(errno));
return -1;
}
} else {
saddr6 = (struct sockaddr_in6 *)&saddr;
saddr6->sin6_family = AF_INET6;
saddr6->sin6_port = htons(port);
/* determine the address */
if (!address) {
/* set the implicit default IPv6 address */
address = "::";
}
if (inet_pton(AF_INET6, address, &saddr6->sin6_addr) != 1) {
ERR(NULL, "Failed to convert IPv6 address \"%s\".", address);
return -1;
}
if (bind(sock, (struct sockaddr *)saddr6, sizeof(struct sockaddr_in6)) == -1) {
ERR(NULL, "Could not bind [%s]:%" PRIu16 " (%s).", address, port, strerror(errno));
return -1;
}
}
return 0;
}
int
nc_sock_listen_inet(const char *address, uint16_t port)
{
int opt;
int is_ipv4, sock;
if (!strchr(address, ':')) {
is_ipv4 = 1;
} else {
is_ipv4 = 0;
}
sock = socket((is_ipv4 ? AF_INET : AF_INET6), SOCK_STREAM, 0);
if (sock == -1) {
ERR(NULL, "Failed to create socket (%s).", strerror(errno));
goto fail;
}
/* these options will be inherited by accepted sockets */
opt = 1;
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof opt) == -1) {
ERR(NULL, "Could not set SO_REUSEADDR socket option (%s).", strerror(errno));
goto fail;
}
if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1) {
ERR(NULL, "Could not set TCP_NODELAY socket option (%s).", strerror(errno));
goto fail;
}
/* bind the socket */
if (nc_sock_bind_inet(sock, address, port, is_ipv4)) {
goto fail;
}
if (listen(sock, NC_REVERSE_QUEUE) == -1) {
ERR(NULL, "Unable to start listening on \"%s\" port %d (%s).", address, port, strerror(errno));
goto fail;
}
return sock;
fail:
if (sock > -1) {
close(sock);
}
return -1;
}
/**
* @brief Construct the full path to the UNIX socket.
*
* @param[in] filename Name of the socket file.
* @param[out] path Constructed full path to the UNIX socket (must be freed by the caller).
* @return 0 on success, 1 on error.
*/
static int
nc_session_unix_construct_socket_path(const char *filename, char **path)
{
int rc = 0, is_prefix, is_subdir, is_exact;
char *full_path = NULL, *real_base_dir = NULL, *last_slash = NULL, *sock_dir_path = NULL;
char *real_target_dir = NULL;
struct sockaddr_un sun;
size_t dir_len, base_len;
const char *dir = server_opts.unix_socket_dir;
if (!dir) {
ERR(NULL, "Cannot construct UNIX socket path \"%s\""
" (no base directory set, see nc_set_unix_socket_dir()).", filename);
return 1;
}
if (filename[0] == '/') {
ERR(NULL, "Cannot construct UNIX socket path \"%s\" (absolute path not allowed).", filename);
return 1;
}
/* construct the path to the UNIX socket */
if (asprintf(&full_path, "%s/%s", dir, filename) == -1) {
ERRMEM;
rc = 1;
goto cleanup;
}
if (strlen(full_path) > sizeof(sun.sun_path) - 1) {
ERR(NULL, "Socket path \"%s\" is too long.", full_path);
goto cleanup;
}
/* ensure the socket path is within the base directory */
if (!(real_base_dir = realpath(dir, NULL))) {
ERR(NULL, "realpath() failed for UNIX socket base directory \"%s\" (%s).", dir, strerror(errno));
rc = 1;
goto cleanup;
}
/* find the last slash in the constructed path */
last_slash = strrchr(full_path, '/');
if (last_slash) {
/* extract the directory part of the socket path */
dir_len = last_slash - full_path;
sock_dir_path = strndup(full_path, dir_len);
NC_CHECK_ERRMEM_GOTO(!sock_dir_path, rc = 1, cleanup);
if (!(real_target_dir = realpath(sock_dir_path, NULL))) {
ERR(NULL, "realpath() failed for UNIX socket path directory \"%s\" (%s).", sock_dir_path,
strerror(errno));
rc = 1;
goto cleanup;
}
} else {
/* should not happen as we always add dir/filename */
real_target_dir = strdup(real_base_dir);
NC_CHECK_ERRMEM_GOTO(!real_target_dir, rc = 1, cleanup);
}
base_len = strlen(real_base_dir);
/* check the relationship between both paths */
is_prefix = (strncmp(real_base_dir, real_target_dir, base_len) == 0);
is_exact = (real_target_dir[base_len] == '\0');
is_subdir = (real_target_dir[base_len] == '/');
/* special case if base is '/' */
if ((base_len == 1) && (real_base_dir[0] == '/')) {
is_subdir = 1;
}
if (!is_prefix || (!is_exact && !is_subdir)) {
ERR(NULL, "UNIX socket path \"%s\" escapes the base directory \"%s\".", full_path, dir);
rc = 1;
goto cleanup;
}
/* transfer ownership */
*path = full_path;
full_path = NULL;
cleanup:
free(real_base_dir);
free(real_target_dir);
free(sock_dir_path);
free(full_path);
return rc;
}
char *
nc_server_unix_get_socket_path(const struct nc_endpt *endpt)
{
LY_ARRAY_COUNT_TYPE i;
const char *p = NULL;
char *path = NULL;
/* check the endpoints options for type of socket path */
if (endpt->opts.unix->path_type == NC_UNIX_SOCKET_PATH_FILE) {
/* UNIX socket endpoints always have only one bind, get its address */
p = endpt->binds[0].address;
/* it is relative, we need to construct the full path */
if (nc_session_unix_construct_socket_path(p, &path)) {
return NULL;
}
} else if (endpt->opts.unix->path_type == NC_UNIX_SOCKET_PATH_HIDDEN) {
/* search the mappings, no need to construct the path */
LY_ARRAY_FOR(server_opts.unix_paths, i) {
if (!strcmp(server_opts.unix_paths[i].endpt_name, endpt->name)) {
p = server_opts.unix_paths[i].path;
break;
}
}
if (!p) {
ERR(NULL, "UNIX socket path mapping for endpoint \"%s\" not found.", endpt->name);
return NULL;
}
path = strdup(p);
NC_CHECK_ERRMEM_RET(!path, NULL);
} else {
ERRINT;
}
return path;
}
/**
* @brief Create a listening socket (AF_UNIX).
*
* @param[in] address Path to the UNIX socket.
* @param[in] opts The server options (unix permissions).
* @return Listening socket, -1 on error.
*/
static int
nc_sock_listen_unix(const char *address, const struct nc_server_unix_opts *opts)
{
struct sockaddr_un sun;
int sock = -1;
if (!address) {
ERR(NULL, "No socket path set.");
goto fail;
} else if (strlen(address) > sizeof(sun.sun_path) - 1) {
ERR(NULL, "Socket path \"%s\" is longer than maximum length %d.", address, (int)(sizeof(sun.sun_path) - 1));
goto fail;
}
sock = socket(AF_UNIX, SOCK_STREAM, 0);
if (sock == -1) {
ERR(NULL, "Failed to create socket (%s).", strerror(errno));
goto fail;
}
memset(&sun, 0, sizeof(sun));
sun.sun_family = AF_UNIX;
snprintf(sun.sun_path, sizeof(sun.sun_path) - 1, "%s", address);
unlink(sun.sun_path);
if (bind(sock, (struct sockaddr *)&sun, sizeof(sun)) == -1) {
ERR(NULL, "Could not bind \"%s\" (%s).", address, strerror(errno));
goto fail;
}
if (opts->mode != (mode_t)-1) {
if (chmod(sun.sun_path, opts->mode) < 0) {
ERR(NULL, "Failed to set unix socket permissions (%s).", strerror(errno));
goto fail;
}
}
if ((opts->uid != (uid_t)-1) || (opts->gid != (gid_t)-1)) {
if (chown(sun.sun_path, opts->uid, opts->gid) < 0) {
ERR(NULL, "Failed to set unix socket uid/gid (%s).", strerror(errno));
goto fail;
}
}
if (listen(sock, NC_REVERSE_QUEUE) == -1) {
ERR(NULL, "Unable to start listening on \"%s\" (%s).", address, strerror(errno));
goto fail;
}
return sock;
fail:
if (sock > -1) {
close(sock);
}
return -1;
}
/**
* @brief Evaluate socket name for AF_UNIX socket.
* @param[in] acc_sock_fd is file descriptor for the accepted socket (a nonnegative).
* @param[out] host is pointer to char* to which the socket name will be set. It must not be NULL.
* @return 0 in case of success. Call free function for parameter host to avoid a memory leak.
* @return 0 if the stream socket is unnamed. Parameter host is set to NULL.
* @return -1 in case of error. Parameter host is set to NULL.
*/
static int
sock_host_unix(int acc_sock_fd, char **host)
{
char *sun_path;
struct sockaddr_storage saddr;
socklen_t addr_len;
*host = NULL;
saddr.ss_family = AF_UNIX;
addr_len = sizeof(saddr);
if (getsockname(acc_sock_fd, (struct sockaddr *)&saddr, &addr_len)) {
ERR(NULL, "getsockname failed (%s).", strerror(errno));
return -1;
}
sun_path = ((struct sockaddr_un *)&saddr)->sun_path;
if (!sun_path) {
/* stream socket is unnamed */
return 0;
}
NC_CHECK_ERRMEM_RET(!(*host = strdup(sun_path)), -1);
return 0;
}
/**
* @brief Evaluate socket name and port number for AF_INET socket.
* @param[in] addr is pointing to structure filled by accept function which was successful.
* @param[out] host is pointer to char* to which the socket name will be set. It must not be NULL.
* @param[out] port is pointer to uint16_t to which the port number will be set. It must not be NULL.
* @return 0 in case of success. Call free function for parameter host to avoid a memory leak.
* @return -1 in case of error. Parameter host is set to NULL and port is unchanged.
*/
static int
sock_host_inet(const struct sockaddr_in *addr, char **host, uint16_t *port)
{
*host = malloc(INET_ADDRSTRLEN);
NC_CHECK_ERRMEM_RET(!(*host), -1);
if (!inet_ntop(AF_INET, &addr->sin_addr, *host, INET_ADDRSTRLEN)) {
ERR(NULL, "inet_ntop failed (%s).", strerror(errno));
free(*host);
*host = NULL;
return -1;
}
*port = ntohs(addr->sin_port);
return 0;
}
/**
* @brief Evaluate socket name and port number for AF_INET6 socket.
* @param[in] addr is pointing to structure filled by accept function which was successful.
* @param[out] host is pointer to char* to which the socket name will be set. It must not be NULL.
* @param[out] port is pointer to uint16_t to which the port number will be set. It must not be NULL.
* @return 0 in case of success. Call free function for parameter host to avoid a memory leak.
* @return -1 in case of error. Parameter host is set to the NULL and port is unchanged.
*/
static int
sock_host_inet6(const struct sockaddr_in6 *addr, char **host, uint16_t *port)
{
*host = malloc(INET6_ADDRSTRLEN);
NC_CHECK_ERRMEM_RET(!(*host), -1);
if (!inet_ntop(AF_INET6, &addr->sin6_addr, *host, INET6_ADDRSTRLEN)) {
ERR(NULL, "inet_ntop failed (%s).", strerror(errno));
free(*host);
*host = NULL;
return -1;
}
*port = ntohs(addr->sin6_port);
return 0;
}
int
nc_sock_accept_binds(struct nc_endpt *endpt, struct nc_bind *binds, uint16_t bind_count,
pthread_mutex_t *bind_lock, int timeout, char **host, uint16_t *port, uint16_t *idx, int *sock)
{
uint16_t i, j, pfd_count, client_port;
char *client_address, *sockpath = NULL;
struct pollfd *pfd;
struct sockaddr_storage saddr;
socklen_t saddr_len = sizeof(saddr);
int ret, client_sock, server_sock = -1, flags;
pfd = malloc(bind_count * sizeof *pfd);
NC_CHECK_ERRMEM_RET(!pfd, -1);
/* LOCK */
if (nc_mutex_lock(bind_lock, timeout, __func__) != 1) {
free(pfd);
return -1;
}
for (i = 0, pfd_count = 0; i < bind_count; ++i) {
if (binds[i].sock < 0) {
/* invalid socket */
continue;
}
if (binds[i].pollin) {
binds[i].pollin = 0;
/* leftover pollin */
server_sock = binds[i].sock;
break;
}
pfd[pfd_count].fd = binds[i].sock;
pfd[pfd_count].events = POLLIN;
pfd[pfd_count].revents = 0;
++pfd_count;
}
if (server_sock == -1) {
/* poll for a new connection */
ret = nc_poll(pfd, pfd_count, timeout);
if (ret < 1) {
free(pfd);
/* UNLOCK */
nc_mutex_unlock(bind_lock, __func__);
return ret;
}
for (i = 0, j = 0; j < pfd_count; ++i, ++j) {
/* adjust i so that indices in binds and pfd always match */
while (binds[i].sock != pfd[j].fd) {
++i;
}
if (pfd[j].revents & POLLIN) {
--ret;
if (!ret) {
/* the last socket with an event, use it */
server_sock = pfd[j].fd;
break;
} else {
/* just remember the event for next time */
binds[i].pollin = 1;
}
}
}
}
free(pfd);
if (server_sock == -1) {
ERRINT;
/* UNLOCK */
nc_mutex_unlock(bind_lock, __func__);
return -1;
}
/* accept connection */
client_sock = accept(server_sock, (struct sockaddr *)&saddr, &saddr_len);
if (client_sock < 0) {
ERR(NULL, "Accept failed (%s).", strerror(errno));
/* UNLOCK */
nc_mutex_unlock(bind_lock, __func__);
return -1;
}
/* make the socket non-blocking */
if (((flags = fcntl(client_sock, F_GETFL)) == -1) || (fcntl(client_sock, F_SETFL, flags | O_NONBLOCK) == -1)) {
ERR(NULL, "Fcntl failed (%s).", strerror(errno));
goto fail;
}
/* learn information about the client end */
if (saddr.ss_family == AF_UNIX) {
if (sock_host_unix(client_sock, &client_address)) {
goto fail;
}
client_port = 0;
} else if (saddr.ss_family == AF_INET) {
if (sock_host_inet((struct sockaddr_in *)&saddr, &client_address, &client_port)) {
goto fail;
}
} else if (saddr.ss_family == AF_INET6) {
if (sock_host_inet6((struct sockaddr_in6 *)&saddr, &client_address, &client_port)) {
goto fail;
}
} else {
ERR(NULL, "Source host of an unknown protocol family.");
goto fail;
}
if (saddr.ss_family == AF_UNIX) {
if (endpt) {
sockpath = nc_server_unix_get_socket_path(endpt);
}
VRB(NULL, "Accepted a connection on %s.", sockpath ? sockpath : "UNIX socket");
free(sockpath);
} else {
VRB(NULL, "Accepted a connection on %s:%u from %s:%u.", binds[i].address, binds[i].port, client_address, client_port);
}
if (host) {
*host = client_address;
} else {
free(client_address);
}
if (port) {
*port = client_port;
}
if (idx) {
*idx = i;
}
/* UNLOCK */
nc_mutex_unlock(bind_lock, __func__);
*sock = client_sock;
return 1;
fail:
close(client_sock);
/* UNLOCK */
nc_mutex_unlock(bind_lock, __func__);
return -1;
}
API struct nc_server_reply *
nc_clb_default_get_schema(struct lyd_node *rpc, struct nc_session *session)
{
const char *identifier = NULL, *revision = NULL, *format = NULL;
char *model_data = NULL;
struct ly_out *out;
const struct lys_module *module = NULL, *nm_mod;
const struct lysp_submodule *submodule = NULL;
struct lyd_node *child, *err, *data = NULL;
LYS_OUTFORMAT outformat = 0;
LY_ERR lyrc;
nm_mod = ly_ctx_get_module_implemented(session->ctx, "ietf-netconf-monitoring");
if (!nm_mod) {
err = nc_err(session->ctx, NC_ERR_OP_FAILED, NC_ERR_TYPE_APP);
nc_err_set_msg(err, "Module \"ietf-netconf-monitoring\" not found in the session context.", "en");
goto error;
}
LY_LIST_FOR(lyd_child(rpc), child) {
if (!strcmp(child->schema->name, "identifier")) {
identifier = lyd_get_value(child);
} else if (!strcmp(child->schema->name, "version")) {
revision = lyd_get_value(child);
if (revision && (revision[0] == '\0')) {
revision = NULL;
}
} else if (!strcmp(child->schema->name, "format")) {
format = lyd_get_value(child);
}
}
VRB(session, "Module \"%s@%s\" was requested.", identifier, revision ? revision : "<any>");
/* check revision */
if (revision && (strlen(revision) != 10) && strcmp(revision, "1.0")) {
err = nc_err(session->ctx, NC_ERR_INVALID_VALUE, NC_ERR_TYPE_APP);
nc_err_set_msg(err, "The requested version is not supported.", "en");
goto error;
}
if (revision) {
/* get specific module */
module = ly_ctx_get_module(session->ctx, identifier, revision);
if (!module) {
submodule = ly_ctx_get_submodule(session->ctx, identifier, revision);
}
} else {
/* try to get implemented, then latest module */
module = ly_ctx_get_module_implemented(session->ctx, identifier);
if (!module) {
module = ly_ctx_get_module_latest(session->ctx, identifier);
}
if (!module) {
submodule = ly_ctx_get_submodule_latest(session->ctx, identifier);
}
}
if (!module && !submodule) {
err = nc_err(session->ctx, NC_ERR_INVALID_VALUE, NC_ERR_TYPE_APP);
nc_err_set_msg(err, "The requested module was not found.", "en");
goto error;
}
/* check format */
if (!format || !strcmp(format, "ietf-netconf-monitoring:yang")) {
outformat = LYS_OUT_YANG;
} else if (!strcmp(format, "ietf-netconf-monitoring:yin")) {
outformat = LYS_OUT_YIN;
} else {
err = nc_err(session->ctx, NC_ERR_INVALID_VALUE, NC_ERR_TYPE_APP);
nc_err_set_msg(err, "The requested format is not supported.", "en");
goto error;
}
/* print */
ly_out_new_memory(&model_data, 0, &out);
if (module) {
lyrc = lys_print_module(out, module, outformat, 0, 0);
} else {
lyrc = lys_print_submodule(out, submodule, outformat, 0, 0);
}
ly_out_free(out, NULL, 0);
if (lyrc) {
err = nc_err(session->ctx, NC_ERR_OP_FAILED, NC_ERR_TYPE_APP);
nc_err_set_msg(err, ly_last_logmsg(), "en");
goto error;
}
/* create reply */
if (lyd_new_inner(NULL, nm_mod, "get-schema", 0, &data)) {
err = nc_err(session->ctx, NC_ERR_OP_FAILED, NC_ERR_TYPE_APP);
nc_err_set_msg(err, ly_last_logmsg(), "en");
goto error;
}
if (lyd_new_any(data, NULL, "data", NULL, model_data, 0, LYD_NEW_ANY_USE_VALUE | LYD_NEW_VAL_OUTPUT, NULL)) {
err = nc_err(session->ctx, NC_ERR_OP_FAILED, NC_ERR_TYPE_APP);
nc_err_set_msg(err, ly_last_logmsg(), "en");
goto error;
}
return nc_server_reply_data(data, NC_WD_EXPLICIT, NC_PARAMTYPE_FREE);
error:
free(model_data);
lyd_free_tree(data);
return nc_server_reply_err(err);
}
API struct nc_server_reply *
nc_clb_default_close_session(struct lyd_node *UNUSED(rpc), struct nc_session *session)
{
session->term_reason = NC_SESSION_TERM_CLOSED;
return nc_server_reply_ok();
}
/**
* @brief Initialize a context with default RPC callbacks if none are set.
*
* @param[in] ctx Context to initialize.
*/
static void
nc_server_init_cb_ctx(const struct ly_ctx *ctx)
{
struct lysc_node *rpc;
if (global_rpc_clb) {
/* expect it to handle these RPCs as well */
return;
}
/* set default <get-schema> callback if not specified */
rpc = NULL;
if (ly_ctx_get_module_implemented(ctx, "ietf-netconf-monitoring")) {
rpc = (struct lysc_node *)lys_find_path(ctx, NULL, "/ietf-netconf-monitoring:get-schema", 0);
}
if (rpc && !rpc->priv) {
rpc->priv = nc_clb_default_get_schema;
}
/* set default <close-session> callback if not specified */
rpc = (struct lysc_node *)lys_find_path(ctx, NULL, "/ietf-netconf:close-session", 0);
if (rpc && !rpc->priv) {
rpc->priv = nc_clb_default_close_session;
}
}
#ifdef NC_ENABLED_SSH_TLS
/**
* @brief Open the keylog file for writing TLS secrets.
*/
static void
nc_server_keylog_file_open(void)
{
char *keylog_file_name;
keylog_file_name = getenv(NC_TLS_KEYLOGFILE_ENV);
if (!keylog_file_name) {
return;
}
server_opts.tls_keylog_file = fopen(keylog_file_name, "a");
if (!server_opts.tls_keylog_file) {
WRN(NULL, "Failed to open keylog file \"%s\".", keylog_file_name);
}
}
#endif
/**
* @brief Initialize a rwlock.
*
* @param[in] rwlock RW lock to initialize.
* @return errno.
*/
static int
nc_server_init_rwlock(pthread_rwlock_t *rwlock)
{
#ifdef HAVE_PTHREAD_RWLOCKATTR_SETKIND_NP
int rc = 0;
pthread_rwlockattr_t attr;
if ((rc = pthread_rwlockattr_init(&attr))) {
ERR(NULL, "%s: failed to init attribute (%s).", __func__, strerror(rc));
return rc;
}