-
Notifications
You must be signed in to change notification settings - Fork 5
/
ncp.c
4266 lines (3951 loc) · 151 KB
/
ncp.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
/* Copyright © 2020-2023 Björn Victor (bjorn@victor.se) */
/* NCP (Network Control Program) implementing Chaosnet transport layer
for cbridge, the bridge program for various Chaosnet implementations. */
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// TODO:
// - Document it better
// - Rewrite in higher-level language
//
// add statistics struct, for (new) PEEK protocol to report
// write client library (but see named.py for how simple it is, not needed really?)
#include <stdlib.h>
#include <ctype.h>
#include <sys/un.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/param.h>
#include <stdarg.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <assert.h>
#include "cbridge.h"
#include "pkqueue.h"
#ifndef USE_CHAOS_SIMPLE
// NYI
#define USE_CHAOS_SIMPLE 0
#endif
#include "ncp.h"
#if CHAOS_DNS
#include <resolv.h>
#include <arpa/nameser.h>
#endif
// ms to wait for ack of final EOF
#define EOF_WAIT_TIMEOUT (3*DEFAULT_RETRANSMISSION_INTERVAL)
// ms to wait for conn to become Open from RFC_Received before closing it down
#define FINISH_WAIT_TIMEOUT 5000
#define MAX_CONTACT_NAME_LENGTH CH_PK_MAX_DATALEN
// configurable stuff
int ncp_enabled = 0;
// chaos socket directory
#define DEFAULT_CHAOS_SOCKET_DIRECTORY "/tmp/"
static char chaos_socket_directory[PATH_MAX];
// default domain for host lookups
#if CHAOS_DNS
#define DEFAULT_CHAOS_DOMAIN "chaosnet.net"
static char **chaos_domains = NULL;
static int number_of_chaos_domains = 0;
#endif
// default retransmission interval
static int default_retransmission_interval = DEFAULT_RETRANSMISSION_INTERVAL;
// default window size
static int default_window_size = DEFAULT_WINSIZE;
// default EOF wait timeout
static int eof_wait_timeout = EOF_WAIT_TIMEOUT;
// finish wait timeout
static int finish_wait_timeout = FINISH_WAIT_TIMEOUT;
// transparently follow FWD
static int forward_transparently = 0;
// debug/trace
static int ncp_debug = 0;
static int ncp_trace = 0;
// list of registered listeners
struct listener *registered_listeners;
// list of active conns
struct conn_list *conn_list;
// list of hostnames from the hosts file
struct private_host_addr {
char *name;
u_short addr;
};
struct private_host_addr *private_hosts = NULL;
int number_of_private_hosts = 0;
static void update_window_available(struct conn_state *cs, u_short winz);
static void print_conn(char *leader, struct conn *conn, int alsostate);
static void start_conn(struct conn *conn);
static void add_output_pkt(struct conn *c, struct chaos_header *pkt);
static void socket_closed_for_conn(struct conn *conn);
static void socket_closed_for_simple_conn(struct conn *conn);
static void retransmit_controlled_packets(struct conn *conn);
static void user_socket_los(struct conn *conn, char *fmt, ...);
static int receive_or_die(struct conn *conn, u_char *buf, int buflen);
static void send_to_user_socket(struct conn *conn, struct chaos_header *pkt, u_char *buf, int len);
static int send_controlled_ncp_packet(struct conn_state *cs, struct chaos_header *pkt, int pklen);
// parse a configuration file line:
// ncp socketdir /var/run debug on domain ams.chaosnet.net trace on
int
parse_ncp_config_line()
{
char *tok = NULL;
int val = 0;
strcpy(chaos_socket_directory,DEFAULT_CHAOS_SOCKET_DIRECTORY); // default
while ((tok = strtok(NULL, " \t\r\n")) != NULL) {
val = 0;
if (strcmp(tok,"socketdir") == 0) {
tok = strtok(NULL, " \t\r\n");
if (tok == NULL) { fprintf(stderr,"ncp: no socket directory specified\n"); return -1; }
strncpy(chaos_socket_directory, tok, sizeof(chaos_socket_directory));
if ((strlen(chaos_socket_directory) < sizeof(chaos_socket_directory)) &&
(chaos_socket_directory[strlen(chaos_socket_directory)-1] != '/')) {
fprintf(stderr,"ncp: fixing socketdir to add slash to \"%s\"\n", chaos_socket_directory);
strcat(chaos_socket_directory, "/");
}
#if CHAOS_DNS
} else if ((strcmp(tok,"domain") == 0) || (strcmp(tok,"domains") == 0)) {
char *sp, *ep;
tok = strtok(NULL, " \t\r\n");
if (tok == NULL) { fprintf(stderr,"ncp: no domain specified\n"); return -1; }
for (sp = tok, ep = index(tok, ','); ep != NULL; sp = ep+1, ep = index(ep+1, ',')) {
// look for comma-separated domain list
chaos_domains = realloc(chaos_domains, (number_of_chaos_domains+1) * sizeof(char *));
if (chaos_domains == NULL) { perror("realloc(chaos_domains)"); exit(1); }
*ep = '\0';
if (strlen(sp) == 0) {
fprintf(stderr,"Syntax error in \"domain\" setting - empty domain\n");
return -1;
}
chaos_domains[number_of_chaos_domains++] = strdup(sp);
}
// add the single one, or the last one
if (strlen(sp) == 0) {
fprintf(stderr,"Syntax error in \"domain\" setting - empty domain\n");
return -1;
}
chaos_domains = realloc(chaos_domains, (number_of_chaos_domains+1) * sizeof(char *));
if (chaos_domains == NULL) { perror("realloc(chaos_domains)"); exit(1); }
chaos_domains[number_of_chaos_domains++] = strdup(sp);
#endif
} else if (strcmp(tok,"retrans") == 0) {
tok = strtok(NULL, " \t\r\n");
if (tok == NULL) { fprintf(stderr,"ncp: no retrans value specified\n"); return -1; }
if (sscanf(tok, "%d", &val) != 1) { fprintf(stderr,"ncp: bad retrans value specified: %s\n", tok); return -1; }
if (val < 1) { fprintf(stderr,"ncp: bad retrans value specified: %d\n", val); return -1; }
// @@@@ at least #define limits?
if ((val < 100) || (val > 15*1000)) { fprintf(stderr,"ncp: very short or long retrans value specified: %d\n", val); return -1; }
else default_retransmission_interval = val;
} else if (strcmp(tok,"eofwait") == 0) {
tok = strtok(NULL, " \t\r\n");
if (tok == NULL) { fprintf(stderr,"ncp: no eofwait value specified\n"); return -1; }
if (sscanf(tok, "%d", &val) != 1) { fprintf(stderr,"ncp: bad eofwait value specified: %s\n", tok); return -1; }
if (val < 1) { fprintf(stderr,"ncp: bad eofwait value specified: %d\n", val); return -1; }
// @@@@ at least #define limits?
if ((val < 100) || (val > 3*60*1000)) { fprintf(stderr,"ncp: very short or long eofwait value specified: %d\n", val); return -1; }
else eof_wait_timeout = val;
} else if (strcmp(tok,"finishwait") == 0) {
tok = strtok(NULL, " \t\r\n");
if (tok == NULL) { fprintf(stderr,"ncp: no finishwait value specified\n"); return -1; }
if (sscanf(tok, "%d", &val) != 1) { fprintf(stderr,"ncp: bad finishwait value specified: %s\n", tok); return -1; }
if (val < 1) { fprintf(stderr,"ncp: bad finishwait value specified: %d\n", val); return -1; }
// @@@@ at least #define limits?
if ((val < 100) || (val > 15*60*1000)) { fprintf(stderr,"ncp: very short or long finishwait value specified: %d\n", val); return -1; }
else finish_wait_timeout = val;
} else if (strcmp(tok,"window") == 0) {
tok = strtok(NULL, " \t\r\n");
if (tok == NULL) { fprintf(stderr,"ncp: no window value specified\n"); return -1; }
// allow any base: 0x for hex, 012 for octal, otherwise decimal
if (sscanf(tok, "%i", &val) != 1) { fprintf(stderr,"ncp: bad window value specified: %s\n", tok); return -1; }
if ((val < 1) || (val > MAX_WINSIZE)) { fprintf(stderr,"ncp: bad window value specified: %d\n", val); return -1; }
else default_window_size = val;
} else if (strcmp(tok, "follow_forward") == 0) {
tok = strtok(NULL, " \t\r\n");
if ((tok == NULL) || (strcasecmp(tok,"on") == 0) || (strcasecmp(tok,"yes") == 0)) {
forward_transparently = 1;
} else if ((strcasecmp(tok,"off") == 0) || (strcasecmp(tok,"no") == 0)) {
forward_transparently = 0;
} else {
fprintf(stderr,"ncp: bad 'follow_forward' arg %s specified\n", tok);
return -1;
}
} else if (strcmp(tok, "debug") == 0) {
tok = strtok(NULL, " \t\r\n");
if ((tok == NULL) || (strcasecmp(tok,"on") == 0) || (strcasecmp(tok,"yes") == 0)) {
ncp_debug = 1;
} else if ((strcasecmp(tok,"off") == 0) || (strcasecmp(tok,"no") == 0)) {
ncp_debug = 0;
} else if ((sscanf(tok, "%d", &val) == 1) && (val >= 0)) {
// allow decimal values too
ncp_debug = val;
} else {
fprintf(stderr,"ncp: bad 'debug' arg %s specified\n", tok);
return -1;
}
} else if (strcmp(tok, "trace") == 0) {
tok = strtok(NULL, " \t\r\n");
if ((tok == NULL) || (strcasecmp(tok,"on") == 0) || (strcasecmp(tok,"yes") == 0)) {
ncp_trace = 1;
} else if ((strcasecmp(tok,"off") == 0) || (strcasecmp(tok,"no") == 0)) {
ncp_trace = 0;
} else if ((sscanf(tok, "%d", &val) == 1) && (val >= 0)) {
// allow decimal values too
ncp_trace = val;
} else {
fprintf(stderr,"ncp: bad 'trace' arg %s specified\n", tok);
return -1;
}
} else if (strcmp(tok, "enabled") == 0) {
tok = strtok(NULL, " \t\r\n");
if ((tok == NULL) || (strcasecmp(tok,"on") == 0) || (strcasecmp(tok,"yes") == 0)) {
ncp_enabled = 1;
} else if ((strcasecmp(tok,"off") == 0) || (strcasecmp(tok,"no") == 0)) {
ncp_enabled = 0;
} else {
fprintf(stderr,"ncp: bad 'enabled' arg %s specified\n", tok);
return -1;
}
} else {
fprintf(stderr,"bad ncp keyword %s\n", tok);
return -1;
}
}
#if CHAOS_DNS
if (number_of_chaos_domains == 0) {
// add default domain
chaos_domains = malloc(sizeof(char *));
if (chaos_domains != NULL)
chaos_domains[number_of_chaos_domains++] = DEFAULT_CHAOS_DOMAIN;
}
#endif
if (verbose || ncp_debug) {
printf("NCP is %s. Socket directory \"%s\", retrans %d, window %d, eofwait %d, finishwait %d, follow_forward %s, debug %d %s, trace %d %s\n",
ncp_enabled ? "enabled" : "disabled",
chaos_socket_directory,
default_retransmission_interval, default_window_size,
eof_wait_timeout, finish_wait_timeout,
forward_transparently > 0 ? "on" : "off",
ncp_debug, (ncp_debug > 0) ? "on" : "off",
ncp_trace, (ncp_trace > 0) ? "on" : "off");
#if CHAOS_DNS
if (number_of_chaos_domains > 0) {
int i;
printf(" %d configured domain%s: ", number_of_chaos_domains, number_of_chaos_domains == 1 ? "" : "s");
for (i = 0; i < number_of_chaos_domains; i++)
printf("%s%s", chaos_domains[i], i < number_of_chaos_domains-1 ? ", " : "");
printf("\n");
}
#endif
}
return 0;
}
static void
trace_conn(char *leader, struct conn *conn)
{
char tbuf[128], buf[256];
if (ncp_trace) {
time_t now = time(NULL);
strftime(tbuf, sizeof(tbuf), "%T", localtime(&now));
sprintf(buf, "%s %s", tbuf, leader);
print_conn(buf, conn, 0);
}
}
char *
conn_thread_name(struct conn *conn)
{
if (pthread_equal(conn->conn_to_net_thread, pthread_self()))
return "conn_to_net";
else if (pthread_equal(conn->conn_to_sock_thread, pthread_self()))
return "conn_to_sock";
else if (pthread_equal(conn->conn_from_sock_thread, pthread_self()))
return "conn_from_sock";
else
return "(not conn thread)";
}
//////////////// utility
static int
opcode_uncontrolled(int opc)
{
if ((opc == CHOP_RFC) || (opc == CHOP_OPN) || (opc == CHOP_EOF) || (opc == CHOP_BRD)
|| (opc >= CHOP_DAT))
// controlled
return 0;
else
// uncontrolled
return 1;
}
static int
packet_uncontrolled(struct chaos_header *pkt)
{
return opcode_uncontrolled(ch_opcode(pkt));
}
// make an unsigned short random value
static u_short
make_u_short_random(void)
{
// call srandom() in ncp_user_server
return random() % (1<<16);
}
static pthread_mutex_t indexindexlock = PTHREAD_MUTEX_INITIALIZER;
#define INDEXINDEXMAX 0x10000
static u_short indexindex[INDEXINDEXMAX];
static int indexindexindex = 0;
static u_short
make_fresh_index(void)
{
int i, found = 1;
u_short new;
PTLOCKN(indexindexlock,"indexindexlock");
if (indexindexindex > (INDEXINDEXMAX>>4)) {
if (ncp_debug) printf("GC of indexes, have %#x\n", indexindexindex);
// gc old indexes @@@@ could check if they are in use, of course...
memmove(&indexindex[0], &indexindex[INDEXINDEXMAX>>8], sizeof(u_short)*(INDEXINDEXMAX>>8));
indexindexindex = INDEXINDEXMAX>>8;
}
if (ncp_debug > 1) printf("Making new index, now have %d in use\n", indexindexindex);
while (found) {
new = make_u_short_random();
found = 0;
// if (ncp_debug) printf(" trying %#x\n", new);
for (i = 0; i < indexindexindex; i++)
if (indexindex[i] == new) {
found = 1;
break;
}
}
if (ncp_debug > 1) printf(" Using %#x\n", new);
indexindex[++indexindexindex] = new;
PTUNLOCKN(indexindexlock,"indexindexlock");
return new;
}
//////// packet numbers, modulo 2^16 - see section 3.4 in MIT AIM 628
int pktnum_less(u_short a, u_short b)
{
return (((int)a-(int)b) & 0100000) != 0;
}
int pktnum_equal(u_short a, u_short b)
{
// assumes using pktnum_1plus so no overflow
return a==b;
}
static int pktnum_diff(u_short a, u_short b)
{
signed int x = (int)a-(int)b;
if (x < 0)
return x+0200000;
else
return x;
}
static int pktnum_1plus(u_short a)
{
return ((int)a+1) & 0177777;
}
static int pktnum_1minus(u_short a)
{
return pktnum_diff(a, 1);
}
//////// named sockets
static void
set_socket_buf(int sock, int which, u_int size)
{
u_int oldbuf, oldlen = sizeof(oldbuf), setbuf = size, newbuf, newlen = sizeof(newbuf);
// get old value
if (getsockopt(sock, SOL_SOCKET, which, (void *)&oldbuf, &oldlen) < 0)
perror("getsockopt");
// set new
if (setsockopt(sock, SOL_SOCKET, which, (void *)&setbuf, sizeof(setbuf)) < 0)
perror("setsockopt");
// doublecheck?
if (getsockopt(sock, SOL_SOCKET, which, (void *)&newbuf, &newlen) < 0)
perror("getsockopt");
else if (ncp_debug && (newbuf != setbuf))
fprintf(stderr,"NCP socket %sBUF: set %d, result is %d\n", (which == SO_SNDBUF ? "SND" : "RCV"),
setbuf, newbuf);
if (ncp_debug) printf("NCP changed %sBUF from %d to %d\n", (which == SO_SNDBUF ? "SND" : "RCV"),
oldbuf, newbuf);
}
static int
make_named_socket(int socktype, char *path, conntype_t conntype)
{
int sock, slen;
struct sockaddr_un local;
struct stat stb;
local.sun_family = AF_UNIX;
strcpy(local.sun_path, chaos_socket_directory);
strcat(local.sun_path, path);
slen = strlen(local.sun_path)+ 1 + sizeof(local.sun_family);
// if the socket file exists, try connecting to it, and if it succeeds, complain and terminate
if (stat(local.sun_path, &stb) == 0) {
if ((stb.st_mode & S_IFMT) == S_IFSOCK) {
if (ncp_debug) fprintf(stderr,"stat(%s) successful, trying to connect\n", local.sun_path);
if ((sock = socket(AF_UNIX, socktype, 0)) < 0) {
perror("socktype(AF_UNIX)");
exit(1);
}
if (connect(sock, (struct sockaddr *)&local, slen) == 0) {
fprintf(stderr,"?? Warning: server socket \"%s\" already exists and is active - avoid running two cbridge processes!\n",
local.sun_path);
exit(1);
} else if (ncp_debug) {
fprintf(stderr,"Info: connect to \"%s\": %s\n", local.sun_path, strerror(errno));
}
// don't need this anymore
close(sock);
} else
fprintf(stderr,"%% socket file %s exists but is not a socket (mode %#o), removing it\n",
local.sun_path, (stb.st_mode & S_IFMT));
// it didn't respond, try removing it
if (unlink(local.sun_path) < 0) {
fprintf(stderr,"?? failed to unlink \"%s\": %s\n", local.sun_path, strerror(errno));
exit(1);
} else if (ncp_debug)
fprintf(stderr,"NCP unlinked old socket file %s\n", local.sun_path);
} else if (ncp_debug)
fprintf(stderr,"Info: failed to stat \"%s\": %s\n", local.sun_path, strerror(errno));
// it doesn't exist at this point
if ((sock = socket(AF_UNIX, socktype, 0)) < 0) {
perror("?? socket(AF_UNIX)");
exit(1);
}
slen = strlen(local.sun_path)+ 1 + sizeof(local.sun_family);
if (bind(sock, (struct sockaddr *)&local, slen) < 0) {
perror("?? bind(local)");
exit(1);
}
if (chmod(local.sun_path, 0777) < 0)
perror("?? chmod(local, 0777)"); // @@@@ configurable?
if (socktype == SOCK_STREAM) {
if (listen(sock, 25) < 0) { // @@@@ random limit
perror("?? listen(local)");
exit(1);
}
}
// Set low socket buffer sizes to make windows matter more.
// Apparently linux only cares about SO_SNDBUF (not SO_RCVBUF),
// so also need do this for client code.
// On macOS, default sizes seem to be 8k, and on linux 208k, so this might really matter.
// Soemwhere it says that for linux, the minimum (doubled) value is
// 256 (SO_RCVBUF) and 2048 (SO_SNDBUF) minus 32 for overhead,
// but it seems SNDBUF min is 4608 and RCVBUF is 2304.
if (conntype == CT_Packet) {
set_socket_buf(sock, SO_SNDBUF, PACKET_SOCKET_BUFFER_SIZE);
set_socket_buf(sock, SO_RCVBUF, PACKET_SOCKET_BUFFER_SIZE);
}
// no signal, just error, please!
#ifdef F_SETNOSIGPIPE
if (fcntl(sock, F_SETNOSIGPIPE, 1) == -1) { perror("fcntl(pipe)"); exit(1); }
#else
#ifdef SO_NOSIGPIPE
int set = 1;
if (setsockopt(sock, SOL_SOCKET, SO_NOSIGPIPE, (void *)&set, sizeof(int)) < 0) { perror("setsockopt(pipe)"); exit(1); }
#else
#ifndef MSG_NOSIGNAL
#warn No way to disable SIGPIPE
#endif
#endif
#endif
return sock;
}
//////////////// datatypes
//////// conns
static char *
state_name(connstate_t s)
{
switch (s) {
case CS_Inactive: return "Inactive";
case CS_Answered: return "Answered";
case CS_CLS_Received: return "CLS_Received";
case CS_Listening: return "Listening";
case CS_RFC_Received: return "RFC_Received";
case CS_RFC_Sent: return "RFC_Sent";
case CS_Open_Sent: return "Open_Sent";
case CS_Open: return "Open";
case CS_LOS_Received: return "LOS_Received";
case CS_Host_Down: return "Host_Down";
case CS_Foreign: return "Foreign";
case CS_BRD_Sent: return "BRD_Sent";
case CS_Finishing: return "Finishing";
default: return "(undefined connection state)";
}
}
static char *
conn_state_name(struct conn *conn)
{
return state_name(conn->conn_state->state);
}
static char *
conn_type_type_name(conntype_t ct)
{
switch (ct) {
case CT_Stream: return "Stream";
case CT_Simple: return "Simple";
case CT_Packet: return "Packet";
default: return "(undefined connection type)";
}
}
static char *
conn_type_name(struct conn *conn)
{
return conn_type_type_name(conn->conn_type);
}
#if 0 // unused
static char *
conn_sockaddr_path(struct conn *c)
{
return c->conn_sockaddr.sun_path;
}
#endif
static void
print_conn(char *leader, struct conn *conn, int alsostate)
{
time_t now = time(NULL);
printf("%s conn %p %s contact \"%s\" remote <%#o,%#x> local <%#o,%#x> state %s age %ld t/o %d ff %d sock %d %s\r\n",
leader,
conn, conn_type_name(conn),
conn->conn_contact,
conn->conn_rhost, conn->conn_ridx,
conn->conn_lhost, conn->conn_lidx,
conn_state_name(conn), now - conn->conn_created, conn->rfc_timeout,
conn->follow_forward,
conn->conn_sock, conn->conn_sockaddr.sun_path);
if (alsostate) {
struct conn_state *cs = conn->conn_state;
printf("%s init %#x made %#x fwin %d avail %d, read %d contr %d ooo %d, ack %#x rec %#x, send %d high %#x inair %d ack %#x last rec %ld probe %ld\r\n",
leader, conn->initial_pktnum, cs->pktnum_made_highest,
cs->foreign_winsize, cs->window_available, pkqueue_length(cs->read_pkts), cs->read_pkts_controlled,
pkqueue_length(cs->received_pkts_ooo),
cs->pktnum_read_highest, cs->pktnum_received_highest,
pkqueue_length(cs->send_pkts), cs->send_pkts_pktnum_highest,
pktnum_diff(cs->send_pkts_pktnum_highest, cs->pktnum_sent_receipt),
cs->pktnum_sent_acked,
cs->time_last_received > 0 ? now - cs->time_last_received : -1,
cs->time_last_probed > 0 ? now - cs->time_last_probed : -1);
}
}
void
set_conn_state(struct conn *c, connstate_t old, connstate_t new, int havelock)
{
struct conn_state *cs = c->conn_state;
// Warn if asked to change from a state we're no longer in
if (cs->state != old) {
if (cs->state != new)
// don't complain if we're already in the new state
if (ncp_debug) printf("%%%% Conn %p told to change from %s to %s but now in %s - NOT CHANGING STATE\n",
c, state_name(old), state_name(new), state_name(cs->state));
return;
}
if (!havelock) PTLOCKN(cs->conn_state_lock,"conn_state_lock");
if (ncp_debug) printf("Conn %p changing from %s to %s (%s)\n", c, conn_state_name(c), state_name(new), havelock ? "had lock" : "locked");
cs->state = new;
if (pthread_cond_broadcast(&cs->conn_state_cond) != 0) perror("?? pthread_cond_broadcast(conn_state_cond)");
if (!havelock) PTUNLOCKN(cs->conn_state_lock,"conn_state_lock");
}
connstate_t
await_conn_state(struct conn *c, connstate_t new, int timeout_ms)
{
int timedout;
struct timespec to;
struct timeval tv;
struct conn_state *cs = c->conn_state;
PTLOCKN(cs->conn_state_lock,"conn_state_lock");
gettimeofday(&tv, NULL);
tv.tv_usec += timeout_ms*1000;
while (tv.tv_usec >= 1000000) {
tv.tv_sec++; tv.tv_usec -= 1000000;
}
to.tv_sec = tv.tv_sec + 0;
to.tv_nsec = tv.tv_usec * 1000;
timedout = 0;
while ((timedout == 0) && (cs->state != new)) {
if (timeout_ms > 0) {
if (ncp_debug) printf("NCP in %s await %s for %d ms\n",
conn_state_name(c), state_name(new), timeout_ms);
timedout = pthread_cond_timedwait(&cs->conn_state_cond, &cs->conn_state_lock, &to);
}
else
pthread_cond_wait(&cs->conn_state_cond, &cs->conn_state_lock);
}
PTUNLOCKN(cs->conn_state_lock,"conn_state_lock");
if (timedout == ETIMEDOUT)
return -1;
else if (timedout < 0)
perror("?? pthread_cond_timedwait");
return cs->state;
}
static struct conn *
make_conn(conntype_t ctype, int sock, struct sockaddr_un *sa, int sa_len)
{
// mutable conn state
struct conn_state *cs = (struct conn_state *)calloc(1, sizeof(struct conn_state));
struct pkqueue *read_pkts = make_pkqueue();
struct pkqueue *received_pkts_ooo = make_pkqueue();
struct pkqueue *send_pkts = make_pkqueue();
if (ncp_debug) printf("Creating %s conn\n", conn_type_type_name(ctype));
if ((cs == NULL)||(read_pkts == NULL)||(received_pkts_ooo==NULL)||(send_pkts==NULL)) {
perror("?? malloc(make_conn)");
exit(1);
}
cs->pktnum_made_highest = make_fresh_index(); // initialize
cs->read_pkts = read_pkts;
cs->read_pkts_controlled = 0;
cs->received_pkts_ooo = received_pkts_ooo;
cs->received_pkts_ooo_width = 0;
cs->send_pkts = send_pkts;
cs->send_pkts_pktnum_highest = cs->pktnum_made_highest;
cs->state = CS_Inactive;
cs->local_winsize = DEFAULT_WINSIZE;
cs->foreign_winsize = DEFAULT_WINSIZE;
cs->window_available = DEFAULT_WINSIZE;
cs->time_last_received = 0;
cs->time_last_probed = 0;
// condition vars, locks
if (pthread_mutex_init(&cs->conn_state_lock, NULL) != 0)
perror("?? pthread_mutex_init(conn_state_lock)");
if (pthread_cond_init(&cs->conn_state_cond, NULL) != 0)
perror("?? pthread_cond_init(conn_state_cond)");
if (pthread_mutex_init(&cs->read_mutex, NULL) != 0)
perror("?? pthread_mutex_init(read_mutex)");
if (pthread_cond_init(&cs->read_cond, NULL) != 0)
perror("?? pthread_cond_init(read_cond)");
if (pthread_mutex_init(&cs->received_ooo_mutex, NULL) != 0)
perror("?? pthread_mutex_init(received_ooo_mutex)");
if (pthread_mutex_init(&cs->send_mutex, NULL) != 0)
perror("?? pthread_mutex_init(send_mutex)");
if (pthread_cond_init(&cs->send_cond, NULL) != 0)
perror("?? pthread_cond_init(send_cond)");
if (pthread_mutex_init(&cs->window_mutex, NULL) != 0)
perror("?? pthread_mutex_init(window_mutex)");
if (pthread_cond_init(&cs->window_cond, NULL) != 0)
perror("?? pthread_cond_init(window_cond)");
// the conn itself
struct conn *conn = (struct conn *)calloc(1, sizeof(struct conn));
conn->conn_type = ctype;
if (pthread_mutex_init(&conn->conn_lock, NULL) != 0)
perror("?? pthread_mutex_init(conn_lock)");
conn->conn_sock = sock;
if (sa != NULL)
memcpy(&conn->conn_sockaddr, sa, (sa_len > sizeof(conn->conn_sockaddr) ? sizeof(conn->conn_sockaddr) : sa_len));
conn->conn_state = cs;
conn->retransmission_interval = default_retransmission_interval;
conn->initial_winsize = default_window_size;
conn->follow_forward = forward_transparently;
conn->rfc_timeout = CONNECTION_TIMEOUT;
conn->conn_created = time(NULL);
conn->initial_pktnum = cs->pktnum_made_highest; // @@@@ debug
if (ncp_debug) print_conn("Made new", conn, 1);
return conn;
}
static struct conn *
make_temp_conn_from_pkt(struct chaos_header *ch)
{
struct conn *conn = make_conn(CT_Simple, 0, NULL, 0);
// no locking needed, not accessible from outside yet
conn->conn_rhost = ch_srcaddr(ch);
conn->conn_ridx = ch_srcindex(ch);
conn->conn_lhost = ch_destaddr(ch);
conn->conn_lidx = ch_destindex(ch);
return conn;
}
static void
free_conn(struct conn *conn)
{
int x;
struct conn_state *cs = conn->conn_state;
PTLOCKN(cs->read_mutex,"read_mutex");
if (ncp_debug) printf("free_pkqeue(read_pkts)\n");
free_pkqueue(cs->read_pkts);
PTUNLOCKN(cs->read_mutex,"read_mutex");
PTLOCKN(cs->received_ooo_mutex,"received_ooo_mutex");
if (ncp_debug) printf("free_pkqeue(received_pkts_ooo)\n");
free_pkqueue(cs->received_pkts_ooo);
PTUNLOCKN(cs->received_ooo_mutex,"received_ooo_mutex");
PTLOCKN(cs->send_mutex,"send_mutex");
if (ncp_debug) printf("free_pkqeue(send_pkts)\n");
free_pkqueue(cs->send_pkts);
PTUNLOCKN(cs->send_mutex,"send_mutex");
if (conn->conn_contact != NULL)
free(conn->conn_contact);
if (conn->conn_contact_args != NULL)
free(conn->conn_contact_args);
if ((x = pthread_mutex_destroy(&conn->conn_lock)) != 0)
fprintf(stderr,"pthread_mutex_destroy(conn_lock): %s\n", strerror(x));
if ((x = pthread_mutex_destroy(&cs->conn_state_lock)) != 0)
fprintf(stderr,"pthread_mutex_destroy(conn_state_lock): %s\n", strerror(x));
if ((x = pthread_cond_destroy(&cs->conn_state_cond)) != 0)
fprintf(stderr,"pthread_cond_destroy(conn_state_cond): %s\n", strerror(x));
if ((x = pthread_mutex_destroy(&cs->read_mutex)) != 0)
fprintf(stderr,"pthread_mutex_destroy(read_mutex): %s\n", strerror(x));
if ((x = pthread_cond_destroy(&cs->read_cond)) != 0)
fprintf(stderr,"pthread_cond_destroy(read_cond): %s\n", strerror(x));
if ((x = pthread_mutex_destroy(&cs->received_ooo_mutex)) != 0)
fprintf(stderr,"pthread_mutex_destroy(received_ooo_mutex): %s\n", strerror(x));
if ((x = pthread_mutex_destroy(&cs->send_mutex)) != 0)
fprintf(stderr,"pthread_mutex_destroy(send_mutex): %s\n", strerror(x));
if ((x = pthread_cond_destroy(&cs->send_cond)) != 0)
fprintf(stderr,"pthread_cond_destroy(send_cond): %s\n", strerror(x));
if ((x = pthread_mutex_destroy(&cs->window_mutex)) != 0)
fprintf(stderr,"pthread_mutex_destroy(window_mutex): %s\n", strerror(x));
if ((x = pthread_cond_destroy(&cs->window_cond)) != 0)
fprintf(stderr,"pthread_cond_destroy(window_cond): %s\n", strerror(x));
if (ncp_debug) printf("NCP freeing conn_state for %p\n", conn);
free(cs);
if (ncp_debug) printf("NCP freeing conn %p\n", conn);
free(conn);
}
static pthread_mutex_t connlist_lock = PTHREAD_MUTEX_INITIALIZER;
static int
conn_list_length(void)
{
int len = 0;
PTLOCKN(connlist_lock,"connlist_lock");
struct conn_list *l;
for (l = conn_list; l != NULL; l = l->conn_next)
len++;
PTUNLOCKN(connlist_lock,"connlist_lock");
return len;
}
static struct conn_list *
add_active_conn(struct conn *c)
{
struct conn_list *new = (struct conn_list *)malloc(sizeof(struct conn_list));
new->conn_conn = c;
if (ncp_debug) print_conn("Adding active",c,0);
PTLOCKN(connlist_lock,"connlist_lock");
new->conn_next = conn_list;
new->conn_prev = NULL;
if (conn_list != NULL)
conn_list->conn_prev = new;
conn_list = new;
PTUNLOCKN(connlist_lock,"connlist_lock");
if (ncp_debug > 1) print_conn("Added active",c,0);
return conn_list;
}
// find c on conn_list, remove from conn_list, and free the element from conn_list
// c is also freed!
static void
remove_active_conn(struct conn *c, int dolock, int dofree)
{
struct conn_list *cl;
if (ncp_debug) printf("NCP removing conn %p\n", c);
if (dolock) {
PTLOCKN(connlist_lock,"connlist_lock");
}
for (cl = conn_list; cl != NULL; cl = cl->conn_next) {
struct conn *cn = cl->conn_conn;
if ((cn == c) ||
((c->conn_rhost == cn->conn_rhost) &&
(c->conn_ridx == cn->conn_ridx) &&
(c->conn_lhost == cn->conn_lhost) &&
(c->conn_lidx == cn->conn_lidx))) {
int lastone = 0;
if (ncp_debug) printf("Removing conn %p from conn_list %p prev %p next %p\n",
c, cl, cl->conn_prev, cl->conn_next);
if (cl->conn_prev != NULL)
cl->conn_prev->conn_next = cl->conn_next;
else
// if prev was null, this is the first element, so conn_list needs updating
conn_list = cl->conn_next;
if (cl->conn_next != NULL)
cl->conn_next->conn_prev = cl->conn_prev;
if ((cl->conn_prev == NULL) && (cl->conn_next == NULL))
lastone = 1;
if (ncp_debug) printf("NCP freeing conn_list entry %p for %p\n", cl, c);
free(cl);
if (lastone)
conn_list = NULL;
if (dofree) {
if (ncp_debug) printf("NCP freeing conn %p\n", c);
free_conn(c);
}
break;
}
}
if (dolock) {
PTUNLOCKN(connlist_lock,"connlist_lock");
}
}
// find a conn on conn_list which matches the (incoming) packet
static struct conn *
find_existing_conn(struct chaos_header *ch)
{
struct conn_list *cl;
struct conn *val = NULL;
int opc = ch_opcode(ch);
u_short src = ch_srcaddr(ch), sidx = ch_srcindex(ch);
u_short dest = ch_destaddr(ch), didx = ch_destindex(ch);
PTLOCKN(connlist_lock,"connlist_lock");
for (cl = conn_list; (cl != NULL) && (val == NULL); cl = cl->conn_next) {
// @@@@ when sending an RFC to self, this seems to find the wrong end (i.e. the RFC-sending end)
// @@@@ break this up into more easily understandable cases!
struct conn *c = cl->conn_conn;
PTLOCKN(c->conn_lock,"conn_lock");
PTLOCKN(c->conn_state->conn_state_lock,"conn_state_lock");
if ( // already existing conn
((c->conn_rhost == src) &&
(c->conn_ridx == sidx) &&
(c->conn_lhost == dest) &&
(c->conn_lidx == didx))
||
// Retransmitted RFC before our OPN was received, or before we even sent it
(((c->conn_state->state == CS_Open_Sent) || (c->conn_state->state == CS_RFC_Received)) &&
(opc == CHOP_RFC) &&
(c->conn_rhost == src) &&
(c->conn_ridx == sidx) &&
(c->conn_lhost == dest) &&
(didx == 0))
||
// answer to RFC: remote index of conn is 0, but remote host matches
// answer to BRD: both remote index and host are 0
(((((c->conn_state->state == CS_RFC_Sent) && (c->conn_rhost == src)) ||
((c->conn_state->state == CS_BRD_Sent) && (c->conn_rhost == 0))) &&
(c->conn_ridx == 0) &&
// local parts match
(c->conn_lhost == dest) && (c->conn_lidx == didx) &&
// and it is an answer of some kind
((opc == CHOP_ANS) || (opc == CHOP_OPN) || (opc == CHOP_FWD) || (opc == CHOP_CLS)))
)) {
val = c;
PTUNLOCKN(c->conn_state->conn_state_lock,"conn_state_lock");
PTUNLOCKN(c->conn_lock,"conn_lock");
break;
} else if (
// another ANS or FWD for a broadcast receiver
// (only the first OPN is accepted, and matched above in BRD_Sent)
(c->conn_state->state == CS_Answered) &&
((opc == CHOP_ANS) || (opc == CHOP_FWD)) &&
// this indicates a broadcast receiver
(c->conn_rhost == 0) && (c->conn_ridx == 0) &&
// local part must match
(c->conn_lhost == dest) && (c->conn_lidx == didx)) {
// the BRD_Sent conn has zero rhost, but allow different hosts to ANS the same BRD conn
val = c;
PTUNLOCKN(c->conn_state->conn_state_lock,"conn_state_lock");
PTUNLOCKN(c->conn_lock,"conn_lock");
break;
} else {
PTUNLOCKN(c->conn_state->conn_state_lock,"conn_state_lock");
PTUNLOCKN(c->conn_lock,"conn_lock");
}
}
if (ncp_debug && (val == NULL) &&
((ch_opcode(ch) == CHOP_RFC) || (ch_opcode(ch) == CHOP_BRD) || (ch_opcode(ch) == CHOP_LOS))) {
u_char contact[CH_PK_MAX_DATALEN];
get_packet_string(ch, contact, sizeof(contact));
printf("NCP: no conn found for %s %#x from src <%#o,%#x> for dest <%#o,%#x>, data (len %d) \"%s\"\n",
ch_opcode_name(ch_opcode(ch)), ch_packetno(ch),
ch_srcaddr(ch),ch_srcindex(ch),ch_destaddr(ch),ch_destindex(ch), ch_nbytes(ch), contact);
if ((ch_opcode(ch) == CHOP_RFC) || (ch_opcode(ch) == CHOP_BRD)) {
printf("NCP: conn list length%s\n", conn_list == NULL ? " empty" : ":");
struct conn_list *c = conn_list;
while (c) {
print_conn(">", c->conn_conn, 1);
c = c->conn_next;
}
}
}
PTUNLOCKN(connlist_lock,"connlist_lock");
return val;
}
//////// listeners
static void
print_listener(char *leader, struct listener *l, int tstamp)
{
char buf[128];
if (tstamp) {
// Include timestamp
time_t now = time(NULL);
strftime(buf, sizeof(buf), "%T ", localtime(&now));
} else
buf[0] = '\0';
printf("%s%s listener %p for \"%s\" conn %p next %p prev %p\n", buf,
leader, l, l->lsn_contact, l->lsn_conn, l->lsn_next, l->lsn_prev);
}
static struct listener *
make_listener(struct conn *c, u_char *contact)
{
struct listener *l = (struct listener *)malloc(sizeof(struct listener));
if (l == NULL) {
perror("?? malloc(make_listener)");
exit(1);
}
int len = strlen((char *)contact);
if (len > MAX_CONTACT_NAME_LENGTH) len = MAX_CONTACT_NAME_LENGTH;
l->lsn_contact = calloc(1,len+1);
strncpy((char *)l->lsn_contact, (char *)contact, len);
l->lsn_conn = c;
l->lsn_next = NULL;
l->lsn_prev = NULL;
return l;
}
static void
free_listener(struct listener *lsn)
{
// assert(not on the registered_listeners list)
if (lsn->lsn_contact != NULL)
free(lsn->lsn_contact);
if (ncp_debug) printf("NCP freeing listener %p\n", lsn);
free(lsn);
}
static pthread_mutex_t listener_lock = PTHREAD_MUTEX_INITIALIZER;
static void
unlink_listener(struct listener *ll, int dolock)
{
if (dolock) {
PTLOCKN(listener_lock,"listener_lock");
}
if (ll->lsn_prev == NULL) {
if (registered_listeners != NULL)
registered_listeners->lsn_prev = ll;
registered_listeners = ll->lsn_next;
} else {
ll->lsn_prev->lsn_next = ll->lsn_next;
if (ll->lsn_next != NULL)
ll->lsn_next->lsn_prev = ll->lsn_prev;
}
if (dolock) {
PTUNLOCKN(listener_lock,"listener_lock");
}
}