-
Notifications
You must be signed in to change notification settings - Fork 157
Expand file tree
/
Copy pathsession_server.c
More file actions
4888 lines (4179 loc) · 150 KB
/
session_server.c
File metadata and controls
4888 lines (4179 loc) · 150 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(ly_yang_module_dir(), 0, ctx)) {
ERR(NULL, "Failed to create a new libyang context.");
ret = 1;
goto cleanup;
}
new_ctx = 1;
if (ly_ctx_set_searchdir(*ctx, nc_yang_module_dir())) {
ERR(NULL, "Failed to set searchdir for a context.");
ret = 1;
goto cleanup;
}
}
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.");
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.");
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.");
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.");
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.");
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, flags, 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;
}
/* make the socket non-blocking */
if (((flags = fcntl(sock, F_GETFL)) == -1) || (fcntl(sock, F_SETFL, flags | O_NONBLOCK) == -1)) {
ERR(NULL, "Fcntl failed (%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);
rc = 1;
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, flags;
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;
}
}
/* make the socket non-blocking */
if (((flags = fcntl(sock, F_GETFL)) == -1) || (fcntl(sock, F_SETFL, flags | O_NONBLOCK) == -1)) {
ERR(NULL, "Fcntl failed (%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
nc_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
nc_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
nc_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;
}
/**
* @brief Get the client's host information from the accepted socket address.
*
* @param[in] saddr sockaddr_storage.
* @param[in] client_sock Socket FD of the accepted connection.
* @param[out] client_address Hostname or IP address of the connecting client (must be freed by the caller).
* @param[out] client_port Port number of the connecting client, if any (0 for AF_UNIX).
* @return 0 on success, -1 on error.
*/
static int
nc_sock_host_get(const struct sockaddr_storage *saddr, int client_sock, char **client_address, uint16_t *client_port)
{
int rc = 0;
/* learn information about the client end */
if (saddr->ss_family == AF_UNIX) {
if ((rc = nc_sock_host_unix(client_sock, client_address))) {
goto cleanup;
}
*client_port = 0;
} else if (saddr->ss_family == AF_INET) {
if ((rc = nc_sock_host_inet((struct sockaddr_in *)saddr, client_address, client_port))) {
goto cleanup;
}
} else if (saddr->ss_family == AF_INET6) {
if ((rc = nc_sock_host_inet6((struct sockaddr_in6 *)saddr, client_address, client_port))) {
goto cleanup;
}
} else {
ERR(NULL, "Source host of an unknown protocol family.");
rc = -1;
goto cleanup;
}
cleanup:
return rc;
}
/**
* @brief Log the accepted connection.
*
* @param[in] saddr sockaddr_storage.
* @param[in] endpt Endpoint on which the connection was accepted (optional, used for logging).
* @param[in] bind Bind on which the connection was accepted.
* @param[in] client_address Hostname or IP address of the connecting client.
* @param[in] client_port Port number of the connecting client, if any.
* @return 0 on success, -1 on error.
*/
static int
nc_sock_log_accepted(const struct sockaddr_storage *saddr, const struct nc_endpt *endpt, const struct nc_bind *bind,
const char *client_address, uint16_t client_port)
{
char *unix_sockpath = NULL;
if (saddr->ss_family == AF_UNIX) {
/* UNIX socket, get the socket path for logging,
* UNIX socket connection can NOT be over call home (caller = client connect), so endpt is always available */
assert(endpt);
unix_sockpath = nc_server_unix_get_socket_path(endpt);
VRB(NULL, "Accepted a new connection on %s.", unix_sockpath ? unix_sockpath : "UNIX socket");
free(unix_sockpath);
} else if (saddr->ss_family == AF_INET) {
/* IPv4 socket */
VRB(NULL, "Accepted a new connection on %s:%" PRIu16 " from %s:%" PRIu16 ".", bind->address, bind->port,
client_address, client_port);
} else if (saddr->ss_family == AF_INET6) {
/* IPv6 socket */
VRB(NULL, "Accepted a new connection on [%s]:%" PRIu16 " from [%s]:%" PRIu16 ".", bind->address, bind->port,
client_address, client_port);
} else {
ERR(NULL, "Source host of an unknown protocol family.");
return -1;
}
return 0;
}
/**
* @brief Accept the first available connection on the given pollfds.
*
* @param[in] pfd Array of pollfds to check for incoming connections.
* @param[in] pfd_count Number of pollfds in the array.
* @param[out] client_sock Socket file descriptor of the accepted connection, -1 if no connection was accepted.
* @param[out] saddr sockaddr_storage to store the address of the connecting client.
* @param[out] saddr_len Length of the sockaddr_storage structure.
* @param[out] fd_idx Index of the pollfd on which the connection was accepted, valid only if client_sock is not -1.
* @return 0 on success, -1 on error (client_sock will be -1 on error or if no connection was accepted).
*/
static int
nc_sock_accept_first(struct pollfd *pfd, uint16_t pfd_count, int *client_sock,
struct sockaddr_storage *saddr, socklen_t *saddr_len, uint16_t *fd_idx)
{
int sock = -1;
uint16_t i;
*client_sock = -1;
for (i = 0; i < pfd_count; i++) {
if (pfd[i].revents & POLLIN) {
sock = accept(pfd[i].fd, (struct sockaddr *)saddr, saddr_len);
if (sock < 0) {
if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) {
/* another thread already accepted the connection, try another one */
continue;
}
ERR(NULL, "Accept failed (%s).", strerror(errno));
return -1;
}
/* successfully accepted a connection! */
break;
}
}
if (sock != -1) {
*client_sock = sock;
*fd_idx = i;
}
return 0;
}
/**
* @brief Accept a new connection on any of the given pollfds.
*
* Can be called by multiple threads. If there is only a single event, one thread will accept the connection,
* others will timeout.
*
* @param[in] pollfds FDs to poll for new connections.
* @param[in] pollfd_count Number of FDs in the pollfds array.
* @param[in] endpt_map Map of pollfd indices to endpoints (optional, used for logging).
* @param[in] bind_map Map of pollfd indices to binds (optional, used for logging).
* @param[in] timeout Timeout for accepting a connection.
* @param[out] host Hostname or IP address of the connecting client.
* @param[out] port Port number of the connecting client, if any.
* @param[out] fd_idx Index of the pollfd on which the connection was accepted.
* @param[out] sock Socket file descriptor of the accepted connection.
* @return 1 on success, 0 on timeout, -1 on error.
*/
static int
nc_sock_accept_pollfds(struct pollfd *pollfds, uint16_t pollfd_count, struct nc_endpt **endpt_map,
struct nc_bind **bind_map, int timeout, char **host, uint16_t *port,
uint16_t *fd_idx, int *sock)
{
uint16_t client_port = 0, matched_pollfd_idx = 0;
char *client_address = NULL;
struct sockaddr_storage client_saddr;
socklen_t saddr_len = sizeof(client_saddr);
struct nc_endpt *endpt;
struct nc_bind *bind;
int client_sock = -1, ret = 1, r, flags;
if (!pollfd_count) {
/* no FDs to poll, treat as a timeout */
ret = 0;
goto cleanup;
}
/* poll for a new connection */
r = nc_poll(pollfds, pollfd_count, timeout);
if (r < 1) {
/* either 0 (timeout) or -1 (error) */
ret = r;
goto cleanup;
}
/* try to accept the first available connection */
if ((r = nc_sock_accept_first(pollfds, pollfd_count, &client_sock, &client_saddr, &saddr_len, &matched_pollfd_idx))) {
ret = r;
goto cleanup;
}
if (client_sock == -1) {
/* all events were stolen by other threads, treat as a timeout */
ret = 0;
goto cleanup;
}
bind = bind_map[matched_pollfd_idx];
endpt = endpt_map ? endpt_map[matched_pollfd_idx] : NULL;
/* 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 cleanup;
}
/* learn information about the peer */
if ((r = nc_sock_host_get(&client_saddr, client_sock, &client_address, &client_port))) {
ret = r;
goto cleanup;
}
/* log the new accepted connection */
if ((r = nc_sock_log_accepted(&client_saddr, endpt, bind, client_address, client_port))) {
ret = r;
goto cleanup;
}
if (host) {
*host = client_address;
client_address = NULL;
}
if (port) {
*port = client_port;
}
if (fd_idx) {
*fd_idx = matched_pollfd_idx;
}
*sock = client_sock;
client_sock = -1;
cleanup:
free(client_address);
if (client_sock > -1) {
close(client_sock);
}
return ret;
}
/**
* @brief Accept a new connection on any of the server's listening binds.
*
* @param[in] config Server configuration.
* @param[in] timeout Timeout for accepting a connection.
* @param[out] host Hostname or IP address of the connecting client.
* @param[out] port Port number of the connecting client, if any.
* @param[out] idx Index of the endpoint on which the connection was accepted (optional).
* @param[out] sock Socket file descriptor of the accepted connection.
* @return 1 on success, 0 on timeout, -1 on error.
*/
static int
nc_server_accept_binds(struct nc_server_config *config, int timeout, char **host,
uint16_t *port, LY_ARRAY_COUNT_TYPE *idx, int *sock)
{
struct pollfd *pollfds = NULL;
uint16_t pollfd_count = 0, fd_idx = 0, bind_count = 0;
LY_ARRAY_COUNT_TYPE i;
struct nc_endpt *endpt;
struct nc_bind *bind;
int ret = 1;
struct nc_endpt **endpt_map = NULL;
struct nc_bind **bind_map = NULL;
/* count the number of valid binds and prepare the pollfd and map parallel arrays */
LY_ARRAY_FOR(config->endpts, i) {
bind_count += LY_ARRAY_COUNT(config->endpts[i].binds);
}
if (!bind_count) {
/* no binds to accept on, treat as a timeout */
ret = 0;
goto cleanup;
}
pollfds = malloc(bind_count * sizeof *pollfds);
NC_CHECK_ERRMEM_RET(!pollfds, -1);
endpt_map = malloc(bind_count * sizeof *endpt_map);
NC_CHECK_ERRMEM_GOTO(!endpt_map, ret = -1, cleanup);
bind_map = malloc(bind_count * sizeof *bind_map);
NC_CHECK_ERRMEM_GOTO(!bind_map, ret = -1, cleanup);
/* fill the arrays */
LY_ARRAY_FOR(config->endpts, struct nc_endpt, endpt) {
LY_ARRAY_FOR(endpt->binds, struct nc_bind, bind) {
if (bind->sock < 0) {
/* invalid socket */
continue;
}
pollfds[pollfd_count].fd = bind->sock;
pollfds[pollfd_count].events = POLLIN;
pollfds[pollfd_count].revents = 0;
endpt_map[pollfd_count] = endpt;
bind_map[pollfd_count] = bind;
++pollfd_count;
}
}
/* accept a new connection on any of the sockets */
ret = nc_sock_accept_pollfds(pollfds, pollfd_count, endpt_map, bind_map, timeout, host, port, &fd_idx, sock);
if (idx && (ret > 0)) {
*idx = endpt_map[fd_idx] - config->endpts;
}
cleanup:
free(pollfds);
free(endpt_map);
free(bind_map);
return ret;
}
int
nc_server_ch_accept_binds(struct nc_bind *binds, uint16_t bind_count, int timeout, char **host,
uint16_t *port, uint16_t *bind_idx, int *sock)
{
struct pollfd *pollfds = NULL;
uint16_t pollfd_count = 0, fd_idx = 0, i;
int ret = 1;
struct nc_bind **bind_map = NULL;
if (!bind_count) {
/* no binds to accept on, treat as a timeout */
ret = 0;
goto cleanup;
}
/* prepare the pollfd and map parallel arrays */
pollfds = malloc(bind_count * sizeof *pollfds);
NC_CHECK_ERRMEM_RET(!pollfds, -1);
bind_map = malloc(bind_count * sizeof *bind_map);
NC_CHECK_ERRMEM_GOTO(!bind_map, ret = -1, cleanup);
/* fill the arrays */