This repository has been archived by the owner on Mar 1, 2023. It is now read-only.
forked from open-iscsi/open-isns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
socket.c
2486 lines (2110 loc) · 56.4 KB
/
socket.c
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
/*
* Socket handling code
*
* Copyright (C) 2007 Olaf Kirch <[email protected]>
*/
#include <sys/socket.h>
#include <poll.h>
#include <sys/time.h>
#include <sys/un.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <stdio.h>
#include <stdarg.h>
#include <time.h>
#include <unistd.h>
#include <errno.h>
#include <netdb.h>
#include <fcntl.h>
#include "config.h"
#include <libisns/buffer.h>
#include <libisns/isns.h>
#include "socket.h"
#include "security.h"
#include <libisns/util.h>
#ifndef SOCK_DEBUG_VERBOSE
#define SOCK_DEBUG_VERBOSE 0
#endif
#ifndef AI_ADDRCONFIG
# define AI_ADDRCONFIG 0
#endif
#ifndef AI_V4MAPPED
# define AI_V4MAPPED 0
#endif
enum {
ISNS_MSG_DISCARD,
ISNS_MSG_DONE,
ISNS_MSG_RETURN
};
static isns_socket_t *__isns_create_socket(struct addrinfo *src,
struct addrinfo *dst,
int sock_type);
static isns_socket_t *__isns_create_socket_from_fd(int, int);
static struct addrinfo *isns_get_address_list(const char *, const char *,
int, int, int);
static void release_addrinfo(struct addrinfo *);
static void isns_net_dgram_recv(isns_socket_t *);
static void isns_net_dgram_xmit(isns_socket_t *);
static void isns_net_stream_accept(isns_socket_t *);
static void isns_net_stream_recv(isns_socket_t *);
static void isns_net_stream_xmit(isns_socket_t *);
static void isns_net_stream_hup(isns_socket_t *);
static void isns_net_stream_error(isns_socket_t *, int);
static void isns_net_stream_reconnect(isns_socket_t *);
static void isns_net_stream_disconnect(isns_socket_t *);
static isns_socket_t *isns_net_alloc(int);
static int isns_socket_open(isns_socket_t *);
static int isns_socket_queue_message(isns_socket_t *, isns_message_t *);
static int isns_socket_retransmit_queued(isns_socket_t *);
static ISNS_LIST_DECLARE(all_sockets);
#define debug_verbose(args ...) do { \
if (SOCK_DEBUG_VERBOSE >= 1) isns_debug_socket(args); \
} while (0)
#define debug_verbose2(args ...) do { \
if (SOCK_DEBUG_VERBOSE >= 2) isns_debug_socket(args); \
} while (0)
/*
* Helper function for looking at incoming PDUs
*/
static inline buf_t *
isns_socket_next_pdu(isns_socket_t *sock)
{
buf_t *bp = sock->is_recv_buf;
unsigned int avail;
struct isns_hdr *hdr;
uint32_t pdu_len = 0;
if (bp == NULL)
return NULL;
avail = buf_avail(bp);
if (avail < sizeof(*hdr))
return NULL;
hdr = buf_head(bp);
pdu_len = sizeof(*hdr) + ntohs(hdr->i_length);
if (avail < pdu_len)
return NULL;
/* Check for presence of authentication block */
if (hdr->i_flags & htons(ISNS_F_AUTHBLK_PRESENT)) {
uint32_t *authblk, authlen;
authblk = (uint32_t *) ((char *) hdr + pdu_len);
if (avail < pdu_len + ISNS_AUTHBLK_SIZE)
return NULL;
authlen = ntohl(authblk[1]);
if (authlen < 20 || authlen > ISNS_MAX_MESSAGE) {
/* The authblock is garbage.
* The only reliable way to signal such a problem
* is by dropping the connection.
*/
isns_error("socket error: bad auth block\n");
sock->is_state = ISNS_SOCK_DEAD;
return NULL;
}
pdu_len += authlen;
if (avail < pdu_len)
return NULL;
}
return buf_split(&sock->is_recv_buf, pdu_len);
}
/*
* Try to assemble the message from PDUs
*/
static inline int
isns_msg_complete(struct isns_partial_msg *msg)
{
buf_t *msg_buf, **chain, *bp;
/* Return if we haven't seen first and last frag */
if (((~msg->imp_flags) & (ISNS_F_FIRST_PDU|ISNS_F_LAST_PDU)))
return 0;
/* Simple - unfragmented case: just move
* the PDU on the chain to the payload */
if (msg->imp_first_seq == msg->imp_last_seq) {
msg->imp_payload = msg->imp_chain;
buf_pull(msg->imp_payload, sizeof(struct isns_hdr));
msg->imp_chain = NULL;
return 1;
}
/* Do we have all fragments? */
if (msg->imp_last_seq - msg->imp_first_seq + 1
!= msg->imp_pdu_count)
return 0;
msg_buf = buf_alloc(msg->imp_msg_size);
chain = &msg->imp_chain;
while ((bp = *chain) != NULL) {
/* Pull the header off */
buf_pull(bp, sizeof(struct isns_hdr));
buf_put(msg_buf, buf_head(bp), buf_avail(bp));
*chain = bp->next;
buf_free(bp);
}
return 0;
}
/*
* Clear the "partial" part of the message
*/
static void
__isns_msg_clear_partial(struct isns_partial_msg *msg)
{
buf_list_free(msg->imp_chain);
msg->imp_chain = NULL;
}
/*
* Add an authentication block to an outgoing PDU
*/
#ifdef WITH_SECURITY
static int
isns_pdu_seal(isns_security_t *ctx, buf_t *pdu)
{
struct isns_authblk auth;
isns_principal_t *self;
if (!(self = ctx->is_self)) {
isns_error("Cannot sign PDU: no sender identity for socket\n");
return 0;
}
auth.iab_bsd = ctx->is_type;
auth.iab_timestamp = time(NULL);
auth.iab_spi = self->is_name;
auth.iab_spi_len = strlen(self->is_name);
if (!isns_security_sign(ctx, self, pdu, &auth)) {
isns_error("Cannot sign PDU: error creating signature\n");
return 0;
}
auth.iab_length = ISNS_AUTHBLK_SIZE +
auth.iab_spi_len +
auth.iab_sig_len;
if (!isns_authblock_encode(pdu, &auth))
return 0;
isns_debug_message("Successfully signed message (authlen=%u, spilen=%u, siglen=%u)\n",
auth.iab_length, auth.iab_spi_len, auth.iab_sig_len);
return 1;
}
/*
* Authenticate a PDU
*
* The RFC is doing a bit of handwaving around the
* authentication issue. For example, it never
* spells out exactly which parts of the message
* are included in the SHA1 hash to be signed.
*
* It also says that the auth block "is identical in format
* to the SLP authentication block", but all fields
* are twice as wide.
*
* There's not even an error code to tell the client
* we were unable to authenticate him :-(
*
* Interoperability problems, here I come...
*/
static int
isns_pdu_authenticate(isns_security_t *sec,
struct isns_partial_msg *msg, buf_t *bp)
{
struct isns_hdr *hdr = buf_head(bp);
unsigned int pdu_len, avail;
struct isns_authblk authblk;
isns_principal_t * peer = NULL;
buf_t auth_buf;
isns_debug_auth("Message has authblock; trying to authenticate\n");
/* In the TCP path, we checked this before, but
* better safe than sorry. */
avail = buf_avail(bp);
pdu_len = sizeof(*hdr) + ntohs(hdr->i_length);
if (avail < pdu_len + ISNS_AUTHBLK_SIZE) {
isns_debug_auth("authblock truncated\n");
return 0;
}
/* Get the auth block */
buf_set(&auth_buf, buf_head(bp) + pdu_len, avail - pdu_len);
if (!isns_authblock_decode(&auth_buf, &authblk)) {
isns_debug_auth("error decoding authblock\n");
return 0;
}
/* Truncate the buffer (this just sets the
* tail pointer, but doesn't free memory */
if (!buf_truncate(bp, pdu_len)) {
isns_debug_auth("buf_truncate failed - cosmic particles?\n");
return 0;
}
/* If the socket doesn't have a security context,
* just ignore the auth block. */
if (sec == NULL) {
msg->imp_header.i_flags &= ~ISNS_F_AUTHBLK_PRESENT;
return 1;
}
if (authblk.iab_bsd != sec->is_type)
goto failed;
peer = isns_get_principal(sec, authblk.iab_spi, authblk.iab_spi_len);
if (peer == NULL) {
/* If the admin allows unknown peers, we must make
* sure, however, to not allow an unauthenticated
* PDU to be inserted into an authenticated message.
*/
if (isns_config.ic_auth.allow_unknown_peers
&& msg->imp_security == NULL) {
isns_debug_message(
"Accepting unknown peer spi=\"%.*s\" as "
"anonymous peer\n",
authblk.iab_spi_len, authblk.iab_spi);
return 1;
}
isns_debug_message(
"Unable to create security peer for spi=%.*s\n",
authblk.iab_spi_len, authblk.iab_spi);
goto failed;
}
if (!isns_security_verify(sec, peer, bp, &authblk)) {
/* Authentication failed */
goto failed;
}
/* The RFC doesn't say how to deal with fragmented
* messages with different BSDs or SPIs.
* kickban seems the right approach.
* We discard this segment rather than failing
* the entire message.
*/
if (msg->imp_chain == NULL) {
msg->imp_security = peer;
peer->is_users++;
} else if (msg->imp_security != peer) {
goto failed;
}
isns_principal_free(peer);
return 1;
failed:
isns_principal_free(peer);
return 0;
}
#else /* WITH_SECURITY */
static int
isns_pdu_authenticate(__attribute__((unused))isns_security_t *sec,
__attribute__((unused))struct isns_partial_msg *msg,
__attribute__((unused))buf_t *bp)
{
return 0;
}
#endif
/*
* Enqueue an incoming PDU on the socket.
*
* A single iSNS message may be split up into
* several PDUs, so we need to perform
* reassembly here.
*
* This function also verifies the authentication
* block, if present.
*/
static void
isns_pdu_enqueue(isns_socket_t *sock,
struct sockaddr_storage *addr, socklen_t alen,
buf_t *segment, struct_cmsgcred_t *creds)
{
isns_message_queue_t *q = &sock->is_partial;
struct isns_partial_msg *msg;
buf_t **chain, *bp;
struct isns_hdr *hdr;
uint32_t xid, seq, flags;
hdr = (struct isns_hdr *) buf_head(segment);
xid = ntohs(hdr->i_xid);
seq = ntohs(hdr->i_seq);
flags = ntohs(hdr->i_flags);
isns_debug_socket("Incoming PDU xid=%04x seq=%u len=%u func=%s%s%s%s%s%s\n",
xid, seq, ntohs(hdr->i_length),
isns_function_name(ntohs(hdr->i_function)),
(flags & ISNS_F_CLIENT)? " client" : "",
(flags & ISNS_F_SERVER)? " server" : "",
(flags & ISNS_F_AUTHBLK_PRESENT)? " authblk" : "",
(flags & ISNS_F_FIRST_PDU)? " first" : "",
(flags & ISNS_F_LAST_PDU)? " last" : "");
/* Find the message matching (addr, xid) */
msg = (struct isns_partial_msg *) isns_message_queue_find(q, xid, addr, alen);
if (msg != NULL) {
if (msg->imp_creds
&& (!creds || memcmp(msg->imp_creds, creds, sizeof(*creds)))) {
isns_warning("socket: credentials mismatch! Dropping PDU\n");
goto drop;
}
hdr = &msg->imp_header;
goto found;
}
msg = (struct isns_partial_msg *) __isns_alloc_message(xid, sizeof(*msg),
(void (*)(isns_message_t *)) __isns_msg_clear_partial);
memcpy(&msg->imp_addr, addr, alen);
msg->imp_addrlen = alen;
msg->imp_header = *hdr;
msg->imp_header.i_seq = 0;
isns_message_queue_append(q, &msg->imp_base);
isns_message_release(&msg->imp_base);
/* Message is owned by is_partial now */
/* Fix up the PDU header */
hdr = &msg->imp_header;
hdr->i_version = ntohs(hdr->i_version);
hdr->i_function = ntohs(hdr->i_function);
hdr->i_length = ntohs(hdr->i_length);
hdr->i_flags = ntohs(hdr->i_flags);
hdr->i_xid = ntohs(hdr->i_xid);
hdr->i_seq = ntohs(hdr->i_seq);
if (creds) {
msg->imp_credbuf = *creds;
msg->imp_creds = &msg->imp_credbuf;
}
found:
if (flags & ISNS_F_AUTHBLK_PRESENT) {
/* When authentication fails - should we drop the
* message or treat it as unauthenticated?
* For now we drop it, but a more user friendly
* approach might be to just treat it as
* unauthenticated.
*/
if (!isns_pdu_authenticate(sock->is_security, msg, segment))
goto drop;
} else if (msg->imp_header.i_flags & ISNS_F_AUTHBLK_PRESENT) {
/* Oops, unauthenticated fragment in an
* authenticated message. */
isns_debug_message(
"Oops, unauthenticated fragment in an "
"authenticated message!\n");
goto drop;
}
if ((flags & ISNS_F_FIRST_PDU)
&& !(msg->imp_flags & ISNS_F_FIRST_PDU)) {
/* FIXME: first seq must be zero */
msg->imp_first_seq = seq;
msg->imp_flags |= ISNS_F_FIRST_PDU;
}
if ((flags & ISNS_F_LAST_PDU)
&& !(msg->imp_flags & ISNS_F_LAST_PDU)) {
msg->imp_last_seq = seq;
msg->imp_flags |= ISNS_F_LAST_PDU;
}
chain = &msg->imp_chain;
while ((bp = *chain) != NULL) {
struct isns_hdr *ohdr = buf_head(bp);
/* Duplicate? Drop it! */
if (seq == ohdr->i_seq)
goto drop;
if (seq < ohdr->i_seq)
break;
chain = &bp->next;
}
segment->next = *chain;
*chain = segment;
msg->imp_msg_size += buf_avail(segment) - sizeof(*hdr);
msg->imp_pdu_count++;
/* We received first and last PDU - check if the
* chain is complete */
if (isns_msg_complete(msg)) {
/* Remove from partial queue.
* We clean the part of the message that is
* not in imp_base, so that we can pass this
* to the caller and have him call
* isns_message_release on it.
*/
__isns_msg_clear_partial(msg);
/* Move from partial queue to complete queue. */
isns_message_queue_move(&sock->is_complete,
&msg->imp_base);
msg->imp_base.im_socket = sock;
}
return;
drop:
buf_free(segment);
return;
}
/*
* Send side handling
*/
static void
isns_send_update(isns_socket_t *sock)
{
buf_t *bp = sock->is_xmit_buf;
if (bp && buf_avail(bp) == 0) {
sock->is_xmit_buf = bp->next;
buf_free(bp);
}
if (sock->is_xmit_buf)
sock->is_poll_mask |= POLLOUT;
else
sock->is_poll_mask &= ~POLLOUT;
}
/*
* Close the socket
*/
static void
isns_net_close(isns_socket_t *sock, int next_state)
{
if (sock->is_desc >= 0) {
close(sock->is_desc);
sock->is_desc = -1;
}
sock->is_poll_mask &= ~(POLLIN|POLLOUT);
sock->is_state = next_state;
buf_list_free(sock->is_xmit_buf);
sock->is_xmit_buf = NULL;
buf_free(sock->is_recv_buf);
sock->is_recv_buf = NULL;
isns_message_queue_destroy(&sock->is_partial);
isns_message_queue_destroy(&sock->is_complete);
}
static void
isns_net_set_timeout(isns_socket_t *sock,
void (*func)(isns_socket_t *),
unsigned int timeout)
{
gettimeofday(&sock->is_deadline, NULL);
sock->is_deadline.tv_sec += timeout;
sock->is_timeout = func;
}
static void
isns_net_cancel_timeout(isns_socket_t *sock)
{
timerclear(&sock->is_deadline);
}
void
isns_net_error(isns_socket_t *sock, int err_code)
{
if (sock->is_error)
sock->is_error(sock, err_code);
}
/*
* Create a socket from systemd fd
*/
isns_socket_t *
isns_create_systemd_socket(int idx)
{
const char *env;
unsigned int p, fds;
env = getenv("LISTEN_PID");
if (!env)
return NULL;
if (sscanf(env, "%u", &p) != 1)
return NULL;
if ((pid_t)p != getpid())
return NULL;
env = getenv("LISTEN_FDS");
if (!env)
return NULL;
if (sscanf(env, "%u", &fds) != 1)
return NULL;
if ((unsigned)idx >= fds)
return NULL;
return __isns_create_socket_from_fd(idx + 3, SOCK_STREAM);
}
/*
* Create a passive socket (server side)
*/
isns_socket_t *
isns_create_server_socket(const char *src_spec, const char *portspec, int af_hint, int sock_type)
{
struct addrinfo *src;
src = isns_get_address_list(src_spec, portspec,
af_hint, sock_type, AI_PASSIVE);
if (src == NULL)
return NULL;
return __isns_create_socket(src, NULL, sock_type);
}
/*
* Accept incoming connections.
*/
void
isns_net_stream_accept(isns_socket_t *sock)
{
isns_socket_t *child;
int fd;
#ifdef SO_PASSCRED
int passcred = 0;
socklen_t optlen;
#endif
fd = accept(sock->is_desc, NULL, NULL);
if (fd < 0) {
if (errno != EINTR)
isns_error("Error accepting connection: %m\n");
return;
}
#ifdef SO_PASSCRED
optlen = sizeof(passcred);
if (getsockopt(sock->is_desc, SOL_SOCKET, SO_PASSCRED,
&passcred, &optlen) >= 0) {
setsockopt(fd, SOL_SOCKET, SO_PASSCRED,
&passcred, sizeof(passcred));
}
#endif
child = isns_net_alloc(fd);
child->is_type = SOCK_STREAM;
child->is_autoclose = 1;
child->is_disconnect_fatal = 1;
child->is_poll_in = isns_net_stream_recv;
child->is_poll_out = isns_net_stream_xmit;
child->is_poll_hup = isns_net_stream_hup;
child->is_error = isns_net_stream_error;
child->is_poll_mask = POLLIN|POLLHUP;
child->is_security = sock->is_security;
/* We need to check the domain of the socket later. */
memcpy(&child->is_src.addr, &sock->is_src.addr, sock->is_src.addrlen);
child->is_src.addrlen = sock->is_src.addrlen;
if (isns_config.ic_network.idle_timeout)
isns_net_set_timeout(child,
isns_net_stream_disconnect,
isns_config.ic_network.idle_timeout);
isns_list_append(&all_sockets, &child->is_list);
}
/*
* This is called from the socket code when it detects
* an error condition.
*/
static void
isns_net_stream_error(isns_socket_t *sock, int err_code)
{
int timeo = 0, next_state = ISNS_SOCK_DEAD;
if (err_code == EAGAIN)
return;
isns_debug_socket("isns_net_stream_error: %s\n", strerror(err_code));
switch (err_code) {
case EINTR: /* ignored */
return;
case ECONNREFUSED:
case ECONNRESET:
case EHOSTUNREACH:
case ENETUNREACH:
case ENOTCONN:
case EPIPE:
if (sock->is_disconnect_fatal) {
isns_warning("socket disconnect, killing socket\n");
break;
}
/* fallthrough to disconnect */
timeo = isns_config.ic_network.reconnect_timeout;
/* fallthru */
case ETIMEDOUT:
/* Disconnect and try to reconnect */
if (sock->is_client) {
/* FIXME: We don't want this warning for ESI and
* SCN sockets on the server side. */
isns_warning("socket disconnect, retrying in %u sec\n",
timeo);
isns_net_set_timeout(sock,
isns_net_stream_reconnect,
timeo);
next_state = ISNS_SOCK_DISCONNECTED;
break;
}
/* fallthru */
default:
isns_error("socket error: %s\n", strerror(err_code));
}
/* Close the socket right away */
isns_net_close(sock, next_state);
}
/*
* recvmsg wrapper handling SCM_CREDENTIALS passing
*/
static int
isns_net_recvmsg(isns_socket_t *sock,
void *buffer, size_t count,
struct sockaddr *addr, socklen_t *alen,
struct_cmsgcred_t **cred)
{
static struct_cmsgcred_t cred_buf;
unsigned int control[128 + sizeof(cred_buf)];
struct cmsghdr *cmsg;
struct msghdr msg;
struct iovec iov;
int len;
*cred = NULL;
iov.iov_base = buffer;
iov.iov_len = count;
memset(&msg, 0, sizeof(msg));
/* Some kernels don't provide peer names for AF_LOCAL sockets,
* we'll synthesize a peer name based on the file descriptor
* later. */
if (sock->is_dst.addr.ss_family != AF_LOCAL && sock->is_src.addr.ss_family != AF_LOCAL) {
msg.msg_name = addr;
msg.msg_namelen = *alen;
}
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = control;
msg.msg_controllen = sizeof(control);
len = recvmsg(sock->is_desc, &msg, MSG_DONTWAIT);
if (len < 0)
return len;
cmsg = CMSG_FIRSTHDR(&msg);
while (cmsg) {
if (cmsg->cmsg_level == SOL_SOCKET
&& cmsg->cmsg_type == SCM_CREDENTIALS_portable) {
memcpy(&cred_buf, CMSG_DATA(cmsg), sizeof(cred_buf));
*cred = &cred_buf;
break;
}
cmsg = CMSG_NXTHDR(&msg, cmsg);
}
if (sock->is_dst.addr.ss_family != AF_LOCAL && sock->is_src.addr.ss_family != AF_LOCAL) {
*alen = msg.msg_namelen;
} else {
/* AF_LOCAL sockets don't have valid peer names on some
* kernels (e.g. Hurd), so synthesize one based on the
* file descriptor number. (It's only used for matching
* multiple PDUs based on their origin.) This is unique
* because this function is only ever called for stream
* sockets. */
struct sockaddr_un *sun = (struct sockaddr_un *)addr;
sun->sun_family = AF_LOCAL;
memcpy(&sun->sun_path, &sock->is_desc, sizeof(int));
*alen = offsetof(struct sockaddr_un, sun_path) + sizeof(int);
}
return len;
}
void
isns_net_stream_recv(isns_socket_t *sock)
{
unsigned char buffer[ISNS_MAX_BUFFER];
struct sockaddr_storage addr;
struct_cmsgcred_t *creds = NULL;
socklen_t alen = sizeof(addr);
buf_t *bp;
size_t count, total = 0;
int len;
again:
if ((bp = sock->is_recv_buf) == NULL) {
bp = buf_alloc(ISNS_MAX_MESSAGE);
sock->is_recv_buf = bp;
}
if ((count = buf_tailroom(bp)) > sizeof(buffer))
count = sizeof(buffer);
if (count == 0) {
/* Message too large */
isns_net_stream_error(sock, EMSGSIZE);
return;
}
#if 0
len = recvfrom(sock->is_desc, buffer, count, MSG_DONTWAIT,
(struct sockaddr *) &addr, &alen);
#else
len = isns_net_recvmsg(sock, buffer, count,
(struct sockaddr *) &addr, &alen,
&creds);
#endif
if (len < 0) {
isns_net_stream_error(sock, errno);
return;
}
if (len == 0) {
if (total == 0)
sock->is_poll_mask &= ~POLLIN;
return;
}
/* We received some data from client, re-arm the
* idle disconnect timer */
if (sock->is_autoclose
&& isns_config.ic_network.idle_timeout)
isns_net_set_timeout(sock,
isns_net_stream_disconnect,
isns_config.ic_network.idle_timeout);
buf_put(bp, buffer, len);
total += len;
/* Chop up the recv buffer into PDUs */
while ((bp = isns_socket_next_pdu(sock)) != NULL) {
/* We have a full PDU; enqueue it */
/* We shouldn't have more than one partial message
* on a TCP connection; we could check this here.
*/
isns_pdu_enqueue(sock, &addr, alen, bp, creds);
}
goto again;
}
#ifndef SO_PASSCRED
/* Without SO_PASSCRED, we need to make sure that credentials are
* added to all sent messages. (Otherwise recvmsg will not receive
* any credentials. */
ssize_t send_with_creds(int sockfd, const void *buf, size_t len, int flags)
{
unsigned char control[CMSG_SPACE(sizeof(struct_cmsgcred_t))];
struct cmsghdr *cmsg;
struct msghdr msg;
struct iovec iov;
iov.iov_base = (void *)buf;
iov.iov_len = len;
memset(&msg, 0, sizeof(msg));
msg.msg_name = NULL;
msg.msg_namelen = 0;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
memset(&control, 0, sizeof(control));
msg.msg_control = control;
msg.msg_controllen = sizeof(control);
cmsg = CMSG_FIRSTHDR(&msg);
cmsg->cmsg_len = CMSG_LEN(sizeof(struct_cmsgcred_t));
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_CREDENTIALS_portable;
/* The kernel will fill the actual data structure for us, so
* there's no need to bother with doing that ourselves. */
return sendmsg(sockfd, &msg, flags);
}
#endif
void
isns_net_stream_xmit(isns_socket_t *sock)
{
unsigned int count;
buf_t *bp = sock->is_xmit_buf;
int len;
/* If a connecting socket can send, it has
* the TCP three-way handshake. */
if (sock->is_state == ISNS_SOCK_CONNECTING) {
sock->is_state = ISNS_SOCK_IDLE;
sock->is_poll_mask |= POLLIN;
isns_net_cancel_timeout(sock);
}
if (bp == NULL)
return;
count = buf_avail(bp);
#ifndef SO_PASSCRED
/* If SO_PASSCRED is not available, we need to ensure we add
* credentials to every sent message. Only do this for AF_LOCAL
* sockets though, as this won't work on AF_INET{,6}. Check
* both is_src and is_dst for AF_LOCAL, because one of them
* might be AF_UNSPEC. */
if (sock->is_dst.addr.ss_family == AF_LOCAL || sock->is_src.addr.ss_family == AF_LOCAL)
len = send_with_creds(sock->is_desc, buf_head(bp), count, MSG_DONTWAIT);
else
len = send(sock->is_desc, buf_head(bp), count, MSG_DONTWAIT);
#else
len = send(sock->is_desc, buf_head(bp), count, MSG_DONTWAIT);
#endif
if (len < 0) {
isns_net_stream_error(sock, errno);
return;
}
debug_verbose("isns_net_stream_xmit(%p, count=%u): transmitted %d\n",
sock, count, len);
buf_pull(bp, len);
isns_send_update(sock);
}
void
isns_net_stream_hup(isns_socket_t *sock)
{
sock->is_poll_mask &= ~(POLLIN|POLLOUT);
/* POLLHUP while connecting means we failed */
if (sock->is_state == ISNS_SOCK_CONNECTING)
isns_net_stream_error(sock, ECONNREFUSED);
}
/*
* Clone an addrinfo list
*/
static struct addrinfo *
clone_addrinfo(const struct addrinfo *ai)
{
struct addrinfo *res = NULL, **p;
p = &res;
for (; ai; ai = ai->ai_next) {
struct addrinfo *new;
if (ai->ai_addrlen > sizeof(struct sockaddr_storage))
continue;
new = isns_calloc(1, sizeof(*new) + ai->ai_addrlen);
new->ai_family = ai->ai_family;
new->ai_socktype = ai->ai_socktype;
new->ai_protocol = ai->ai_protocol;
new->ai_addrlen = ai->ai_addrlen;
new->ai_addr = (struct sockaddr *) (new + 1);
memcpy(new->ai_addr, ai->ai_addr, new->ai_addrlen);
*p = new;
p = &new->ai_next;
}
return res;
}
static struct addrinfo *
__make_addrinfo(const struct sockaddr *ap, socklen_t alen, int socktype)
{
struct addrinfo *new;
new = isns_calloc(1, sizeof(*new) + alen);
new->ai_family = ap->sa_family;
new->ai_socktype = socktype;
new->ai_protocol = 0;
new->ai_addrlen = alen;
new->ai_addr = (struct sockaddr *) (new + 1);
memcpy(new->ai_addr, ap, alen);
return new;
}
static struct addrinfo *
make_addrinfo_unix(const char *pathname, int socktype)
{
unsigned int len = strlen(pathname);
struct sockaddr_un sun;
if (len + 1 > sizeof(sun.sun_path)) {
isns_error("Can't set AF_LOCAL address: path too long!\n");
return NULL;
}
sun.sun_family = AF_LOCAL;
strcpy(sun.sun_path, pathname);
return __make_addrinfo((struct sockaddr *) &sun, SUN_LEN(&sun) + 1, socktype);
}
static struct addrinfo *
make_addrinfo_any(int family, int socktype)
{
struct sockaddr_storage addr = { .ss_family = AF_UNSPEC };
struct addrinfo *res;
if (family != AF_UNSPEC) {
addr.ss_family = family;
res = __make_addrinfo((struct sockaddr *) &addr, sizeof(addr), socktype);
} else {
addr.ss_family = AF_INET6;
res = __make_addrinfo((struct sockaddr *) &addr, sizeof(addr), socktype);
addr.ss_family = AF_INET;
res->ai_next = __make_addrinfo((struct sockaddr *) &addr, sizeof(addr), socktype);
}
return res;
}