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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
|
/* See LICENSE file for copyright and license details. */
#include <sys/auxv.h>
#include <sys/epoll.h>
#include <sys/timerfd.h>
#include <libblake.h>
#include <libsimple.h>
#include <libsimple-arg.h>
USAGE("[-a unix-address] [-c config-file] [-p udp-port]");
#define UDP_PORT 42712
#define LOCAL_ADDRESS_PREFIX "@oikobus-"
#define LOCAL_ADDRESS_BUFSIZE (sizeof(LOCAL_ADDRESS_PREFIX) + 3u * sizeof(uintmax_t))
#define LOCAL_ADDRESS(UID) "%s%ju", LOCAL_ADDRESS_PREFIX, (uintmax_t)(UID)
#define SOCKADDR(ADDR) ((void *)&(ADDR)), ((socklen_t)sizeof(ADDR))
#define ALPHA64 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz{}"
#define MIN_REALM_LEN 1u
#define MAX_REALM_LEN 510u
#define CHALLENGE_SIZE 64u /* must be within [1 64] (BLAKE2b key bounds) */
#define PROOF_SIZE 64u /* must be within [1 64] (BLAKE2b digest bounds) */
#define CHALLENGE_PEPPER "\xa1\x7d\xcc\x75\x51\xd9\xc2\x2b\x63\xf9\x45\x83\x4b\x4d\xae\x4c"
union file;
enum file_type {
TIMER_FILE,
BROADCAST_FILE,
NETWORK_FILE,
LOCAL_FILE,
PEER_FILE,
CLIENT_FILE
};
#define FILE_COMMON\
enum file_type type;\
int fd;\
void (*on_event)(union file *this, uint32_t epoll_events)
struct timer_file {
FILE_COMMON;
union file *owner;
};
struct broadcast_file {
FILE_COMMON;
struct sockaddr_in addr;
struct timer_file timer;
int64_t timer_inc;
struct timespec alarm_time;
};
struct network_file {
FILE_COMMON;
};
struct local_file {
FILE_COMMON;
};
struct peer_file {
FILE_COMMON;
uint64_t id;
struct sockaddr_in addr;
uint8_t *realms;
struct handshake_state {
#define HANDSHAKE_A_INIT HANDSHAKE_A_SEND_ID
#define HANDSHAKE_B_INIT HANDSHAKE_B_SEND_ID
enum handshake_status {
HANDSHAKE_A_SEND_ID,
HANDSHAKE_A_RECV_ID,
HANDSHAKE_A_SEND_REALM,
HANDSHAKE_A_RECV_CHALLENGE,
HANDSHAKE_A_SEND_PROOF,
HANDSHAKE_A_RECV_ACCEPTANCE,
HANDSHAKE_B_SEND_ID,
HANDSHAKE_B_RECV_ID,
HANDSHAKE_B_RECV_REALM,
HANDSHAKE_B_SEND_CHALLENGE,
HANDSHAKE_B_RECV_PROOF,
HANDSHAKE_B_SEND_ACCEPTANCE
} status;
size_t realm;
uint16_t off;
uint16_t len;
uint16_t head;
uint16_t tail;
unsigned char buf[512];
unsigned char sbuf[512];
} *handshake_state;
};
struct client_file {
FILE_COMMON;
struct client_file *prev;
struct client_file *next;
};
union file {
struct { FILE_COMMON; };
struct timer_file timer;
struct broadcast_file broadcast;
struct network_file network;
struct local_file local;
struct peer_file peer;
struct client_file client;
};
struct broadcast_message {
#define BROADCAST_MESSAGE_SIZE 10
uint64_t id;
uint16_t port;
};
struct realm {
char *name;
char *key;
};
static struct realm *realms = NULL;
static size_t nrealms = 0u;
static struct broadcast_message server_identity;
static int epoll;
static struct epoll_event *events;
static int events_size;
static struct local_file *lsock;
static struct network_file *nsock;
static struct broadcast_file *bsock;
static struct peer_file **peers;
static size_t npeers;
static size_t peers_size;
static uid_t uid;
static struct client_file clients_head;
static struct client_file clients_tail;
static void
remove_peer(struct peer_file *peer)
{
size_t i;
for (i = 0u; i < npeers; i++) {
if (peers[i] == peer) {
peers[i] = peers[--npeers];
break;
}
}
close(peer->fd);
free(peer->handshake_state);
free(peer->realms);
free(peer);
}
static struct peer_file *
add_peer(int fd, uint64_t id, const struct sockaddr_in *addr,
enum handshake_status status, void (*on_event)(union file *, uint32_t))
{
struct peer_file *file;
struct epoll_event ev;
file = emalloc(sizeof(*file));
file->type = PEER_FILE;
file->fd = fd;
file->id = id;
file->addr = *addr;
file->on_event = on_event;
file->realms = nrealms ? ecalloc((nrealms + 7u) / 8u, sizeof(uint8_t)) : NULL;
file->handshake_state = ecalloc(1u, sizeof(*file->handshake_state));
file->handshake_state->status = status;
memset(&ev, 0, sizeof(ev));
ev.events = EPOLLIN | EPOLLOUT;
ev.data.ptr = file;
if (epoll_ctl(epoll, EPOLL_CTL_ADD, file->fd, &ev))
eprintf("epoll_ctl <epoll> EPOLL_CTL_ADD <peer tcp socket> {EPOLLIN|EPOLLOUT}:");
if (npeers == peers_size)
peers = ereallocarray(peers, ++peers_size, sizeof(*peers));
peers[npeers++] = file;
return file;
}
static void
on_client_event(union file *this, uint32_t epoll_events)
{
(void) this;
(void) epoll_events;
/* TODO */
}
static void
on_peer_event(union file *this, uint32_t epoll_events)
{
(void) this;
(void) epoll_events;
/* TODO */
}
static unsigned char *
handshake_prepare(struct peer_file *this, size_t len)
{
uint16_t n;
if (len > sizeof(this->handshake_state->sbuf) - 2u)
abort();
len += 2u;
n = (uint16_t)len;
this->handshake_state->off = 0u;
this->handshake_state->len = n;
n = htons(n);
memcpy(&this->handshake_state->sbuf[0u], &n, 2u);
return &this->handshake_state->sbuf[2u];
}
static int
handshake_continue(struct peer_file *this)
{
size_t rem;
ssize_t r;
while ((rem = this->handshake_state->len - this->handshake_state->off)) {
r = send(this->fd, &this->handshake_state->sbuf[this->handshake_state->off], rem, MSG_NOSIGNAL | MSG_DONTWAIT);
if (r < 0) {
if (errno == EINTR)
continue;
if (errno == ECONNRESET || errno == EPIPE)
return -1;
if (errno == EAGAIN)
return 0;
#if EAGAIN != EWOULDBLOCK
if (errno == EWOULDBLOCK)
return 0;
#endif
weprintf("send <peer tcp socket>:");
return -1;
}
this->handshake_state->off += (uint16_t)r;
}
this->handshake_state->off = 0u;
this->handshake_state->len = 0u;
return 1;
}
static int
handshake_send(struct peer_file *this, const void *message, size_t len)
{
if (!this->handshake_state->len)
memcpy(handshake_prepare(this, len), message, len);
return handshake_continue(this);
}
static int
handshake_receive(struct peer_file *this)
{
ssize_t r;
uint16_t len = 0u;
if (this->handshake_state->head != this->handshake_state->tail) {
memmove(&this->handshake_state->buf[0u],
&this->handshake_state->buf[this->handshake_state->head],
this->handshake_state->tail -= this->handshake_state->head);
this->handshake_state->off += this->handshake_state->tail;
this->handshake_state->tail = this->handshake_state->head = 0u;
}
for (;;) {
if (len) {
goto check_done;
} else if (this->handshake_state->off >= 2u) {
memcpy(&len, &this->handshake_state->buf[0u], 2u);
len = ntohs(len);
check_done:
if (this->handshake_state->off >= len)
break;
}
r = recv(this->fd, &this->handshake_state->buf[this->handshake_state->off],
sizeof(this->handshake_state->buf) - this->handshake_state->off,
MSG_DONTWAIT);
if (r <= 0) {
if (!r)
return -1;
if (errno == EINTR)
continue;
if (errno == ECONNRESET || errno == EPIPE)
return -1;
if (errno == EAGAIN)
return 0;
#if EAGAIN != EWOULDBLOCK
if (errno == EWOULDBLOCK)
return 0;
#endif
weprintf("recv <peer tcp socket>:");
return -1;
}
this->handshake_state->off += (uint16_t)r;
}
this->handshake_state->tail = this->handshake_state->off;
this->handshake_state->head = this->handshake_state->off = len;
return 1;
}
static void
generate_proof(const struct realm *realm, const void *challenge, unsigned char *buf)
{
unsigned char block[LIBBLAKE_BLAKE2B_BLOCK_SIZE];
struct libblake_blake2b_params params;
struct libblake_blake2b_state state;
size_t salt_len;
size_t key_len = strlen(realm->key);
size_t off = 0u;
salt_len = strlen(realm->name);
salt_len = salt_len < 16u ? salt_len : 16u;
memset(¶ms, 0, sizeof(params));
params.digest_len = PROOF_SIZE;
params.key_len = CHALLENGE_SIZE;
params.fanout = 1u;
params.depth = 1u;
memcpy(params.salt, realm->name, salt_len);
memcpy(params.pepper, CHALLENGE_PEPPER, 16u);
libblake_blake2b_init(&state, ¶ms);
memcpy(&block[0u], challenge, CHALLENGE_SIZE);
memset(&block[CHALLENGE_SIZE], 0, sizeof(block) - CHALLENGE_SIZE);
libblake_blake2b_force_update(&state, block, sizeof(block));
off = key_len & ~(sizeof(block) - 1u);
if (off == key_len)
off -= sizeof(block);
if (off)
off = libblake_blake2b_force_update(&state, realm->key, off);
memcpy(&block[0u], realm->key, key_len - off);
libblake_blake2b_digest(&state, block, key_len - off, 0, PROOF_SIZE, buf);
}
static void
peer_handshake(union file *this_, uint32_t epoll_events)
{
unsigned char proof_buf[PROOF_SIZE];
struct peer_file *this = &this_->peer;
struct epoll_event ev;
uint16_t len;
size_t i;
int r;
#define SEND(...) CHECKED(handshake_send(this, __VA_ARGS__)) goto wait_write
#define RECV() CHECKED(handshake_receive(this)) goto wait_read
#define CONT() CHECKED(handshake_continue(this)) goto wait_write
#define CHECKED(COMMAND)\
r = (COMMAND);\
if (r < 0) goto remove;\
if (r == 0)
(void) epoll_events;
switch (this->handshake_state->status) {
case HANDSHAKE_A_SEND_ID:
SEND(&server_identity.id, 8u);
this->handshake_state->status++;
/* fall-through */
case HANDSHAKE_A_RECV_ID:
RECV();
len = this->handshake_state->off;
this->handshake_state->off = 0u;
if (len != 10u || memcmp(&this->handshake_state->buf[2u], &this->id, 8u))
goto remove;
this->handshake_state->status++;
/* fall-through */
case HANDSHAKE_A_SEND_REALM:
send_realm:
if (this->handshake_state->realm == nrealms) {
SEND("", 0u);
break;
}
SEND(realms[this->handshake_state->realm].name,
strlen(realms[this->handshake_state->realm].name));
this->handshake_state->status++;
/* fall-through */
case HANDSHAKE_A_RECV_CHALLENGE:
RECV();
len = this->handshake_state->off;
this->handshake_state->off = 0u;
if (len == 2u) {
this->handshake_state->status = HANDSHAKE_A_SEND_REALM;
goto send_realm;
}
if (len != CHALLENGE_SIZE + 2u) {
goto remove;
}
generate_proof(&realms[this->handshake_state->realm],
&this->handshake_state->buf[2u],
handshake_prepare(this, PROOF_SIZE));
this->handshake_state->status++;
/* fall-through */
case HANDSHAKE_A_SEND_PROOF:
CONT();
this->handshake_state->status++;
/* fall-through */
case HANDSHAKE_A_RECV_ACCEPTANCE:
RECV();
len = this->handshake_state->off;
this->handshake_state->off = 0u;
if (len != 3u || this->handshake_state->buf[2u] > 1u)
goto remove;
if (this->handshake_state->buf[2u]) {
uint8_t bit = (uint8_t)(1u << (this->handshake_state->realm % 8u));
this->realms[this->handshake_state->realm / 8u] |= bit;
}
this->handshake_state->realm++;
this->handshake_state->status = HANDSHAKE_A_SEND_REALM;
goto send_realm;
case HANDSHAKE_B_SEND_ID:
if (!handshake_send(this, &server_identity.id, 8u))
goto wait_write;
this->handshake_state->status++;
/* fall-through */
case HANDSHAKE_B_RECV_ID:
RECV();
len = this->handshake_state->off;
this->handshake_state->off = 0u;
if (len != 10u)
goto remove;
memcpy(&this->id, &this->handshake_state->buf[2u], 8u);
if (this->id == server_identity.id)
goto remove;
for (i = 0u; i < npeers; i++)
if (peers[i]->id == this->id && peers[i] != this)
goto remove;
this->handshake_state->status++;
/* fall-through */
case HANDSHAKE_B_RECV_REALM:
recv_realm:
RECV();
len = this->handshake_state->off;
this->handshake_state->off = 0u;
if (len <= 2u) {
if (len == 2u)
break;
goto remove;
}
len = (uint16_t)(len - 2u);
for (i = 0u; i < nrealms; i++) {
if (memcmp(realms[i].name, &this->handshake_state->buf[2u], len))
continue;
if (realms[i].name[len])
continue;
break;
}
this->handshake_state->realm = i;
if (this->handshake_state->realm == nrealms) {
handshake_prepare(this, 0u);
} else {
unsigned char *m = handshake_prepare(this, CHALLENGE_SIZE);
for (i = 0u; i < CHALLENGE_SIZE; i++)
m[i] = (unsigned char)(rand() & 255);
}
this->handshake_state->status++;
/* fall-through */
case HANDSHAKE_B_SEND_CHALLENGE:
CONT();
if (this->handshake_state->realm == nrealms) {
this->handshake_state->status = HANDSHAKE_B_RECV_REALM;
goto recv_realm;
}
this->handshake_state->status++;
/* fall-through */
case HANDSHAKE_B_RECV_PROOF:
RECV();
len = this->handshake_state->off;
this->handshake_state->off = 0u;
if (len != PROOF_SIZE + 2u)
goto remove;
generate_proof(&realms[this->handshake_state->realm],
&this->handshake_state->sbuf[2u], proof_buf);
if (!memcmp(&this->handshake_state->buf[2u], proof_buf, PROOF_SIZE)) {
uint8_t bit = (uint8_t)(1u << (this->handshake_state->realm % 8u));
this->realms[this->handshake_state->realm / 8u] |= bit;
handshake_prepare(this, 1u)[0u] = 1u;
/* TODO we should send a realm index instead, so we can
* encode reals as indicies rather than names
* (index 0 should be reserved for the local-only
* realm: a default realm that can only be accessed
* on the same machine by the same user) */
} else {
handshake_prepare(this, 1u)[0u] = 0u;
}
this->handshake_state->status++;
/* fall-through */
case HANDSHAKE_B_SEND_ACCEPTANCE:
CONT();
this->handshake_state->status = HANDSHAKE_B_RECV_REALM;
goto recv_realm;
default:
abort();
}
for (i = 0u; i < (nrealms + 7u) / 8u; i++)
if (this->realms[i])
goto have_a_realm;
remove:
remove_peer(this);
return;
have_a_realm:
epoll_events = EPOLLIN;
this->on_event = &on_peer_event;
/* TODO copy over handshake recv buf */
free(this->handshake_state);
this->handshake_state = NULL;
config_epoll:
memset(&ev, 0, sizeof(ev));
ev.events = epoll_events;
ev.data.ptr = this;
if (epoll_ctl(epoll, EPOLL_CTL_MOD, this->fd, &ev))
eprintf("epoll_ctl <epoll> EPOLL_CTL_MOD <peer tcp socket> {%s}:",
epoll_events == EPOLLIN ? "EPOLLIN" : "EPOLLOUT");
return;
wait_write:
epoll_events = EPOLLOUT;
goto config_epoll;
wait_read:
epoll_events = EPOLLIN;
goto config_epoll;
#undef SEND
#undef RECV
#undef CONT
#undef CHECKED
}
static void
peer_connection_done(union file *this, uint32_t epoll_events)
{
int err = 0;
socklen_t len = (socklen_t)sizeof(err);
if (getsockopt(this->fd, SOL_SOCKET, SO_ERROR, &err, &len))
eprintf("getsockopt <peer tcp socket> SOL_SOCKET SO_ERROR");
if (len > (socklen_t)sizeof(err))
abort();
if (err && err != EINTR) {
weprintf("connect(async) <tcp socket> %s:%u\n",
inet_ntoa(this->peer.addr.sin_addr), ntohs(this->peer.addr.sin_port));
remove_peer(&this->peer);
return;
}
this->on_event = &peer_handshake;
peer_handshake(this, epoll_events);
}
static void
on_network_socket_event(union file *this, uint32_t epoll_events)
{
struct sockaddr_in addr;
socklen_t addrlen = (socklen_t)sizeof(addr);
struct peer_file *file;
int fd;
(void) epoll_events;
retry:
fd = accept4(this->fd, (void *)&addr, &addrlen, SOCK_NONBLOCK);
if (fd < 0) {
switch (errno) {
case EINTR:
goto retry;
case ECONNABORTED:
case ECONNRESET:
case EPERM:
return;
default:
eprintf("accept4 <tcp server socket> SOCK_NONBLOCK:");
}
}
if (addrlen > (socklen_t)sizeof(addr)) {
weprintf("TCP socket peer name overlong\n");
close(fd);
return;
}
file = add_peer(fd, 0u, &addr, HANDSHAKE_B_INIT, &peer_handshake);
peer_handshake((void *)file, EPOLLOUT);
}
static void
on_broadcast_socket_event(union file *this, uint32_t epoll_events)
{
struct broadcast_message msg;
struct sockaddr_in addr;
socklen_t addrlen = (socklen_t)sizeof(addr);
ssize_t r;
int fd, in_progress;
struct peer_file *file;
size_t i;
(void) epoll_events;
retry_recv:
r = recvfrom(this->fd, &msg, sizeof(msg), MSG_TRUNC, &addr, &addrlen);
if (r < 0) {
if (errno == EINTR)
goto retry_recv;
if (errno == ECONNREFUSED)
return;
eprintf("recvfrom <broadcast socket>:");
}
if (addrlen > (socklen_t)sizeof(addr)) {
weprintf("TCP socket peer name overlong\n");
return;
}
if (r != BROADCAST_MESSAGE_SIZE || msg.id == server_identity.id)
return;
for (i = 0u; i < npeers; i++)
if (msg.id == peers[i]->id)
return;
fd = socket(PF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
if (fd < 0) {
weprintf("socket PF_INET SOCK_STREAM|SOCK_NONBLOCK 0:");
return;
}
addr.sin_port = msg.port;
retry_connect:
if (!connect(fd, (void *)&addr, addrlen)) {
in_progress = 0;
} else if (errno == EINPROGRESS) {
in_progress = 1;
} else if (errno == EINTR) {
goto retry_connect;
} else {
weprintf("connect <tcp socket> %s:%u\n", inet_ntoa(addr.sin_addr), ntohs(msg.port));
if (errno != ENETUNREACH && errno != ETIMEDOUT && errno != ECONNREFUSED)
exit(1);
close(fd);
return;
}
file = add_peer(fd, msg.id, &addr, HANDSHAKE_A_INIT,
in_progress ? &peer_connection_done : &peer_handshake);
if (!in_progress)
peer_handshake((void *)file, EPOLLOUT);
}
static void
broadcast_identity(struct broadcast_file *file)
{
long int rnd;
struct itimerspec its;
if (sendto(file->fd, &server_identity, BROADCAST_MESSAGE_SIZE, 0, SOCKADDR(file->addr)) != BROADCAST_MESSAGE_SIZE)
weprintf("sendto <broadcast socket>:");
file->alarm_time.tv_sec += file->timer_inc;
file->timer_inc *= 2;
rnd = rand() & 255;
rnd *= 1000000l;
file->alarm_time.tv_nsec += rnd;
if (file->alarm_time.tv_nsec >= 1000000000l) {
file->alarm_time.tv_nsec -= 1000000000l;
file->alarm_time.tv_sec += 1;
}
memset(&its, 0, sizeof(its));
its.it_value = file->alarm_time;
if (timerfd_settime(file->timer.fd, 0, &its, NULL))
weprintf("timerfd_settime <timerfd for broadcast socket> 0 <single expiry> NULL:");
}
static void
on_broadcast_timer_event(union file *this, uint32_t epoll_events)
{
(void) epoll_events;
broadcast_identity(&this->timer.owner->broadcast);
}
static void
on_local_socket_event(union file *this, uint32_t epoll_events)
{
struct ucred cred;
socklen_t len = (socklen_t)sizeof(cred);
int fd;
struct client_file *file;
struct epoll_event ev;
(void) epoll_events;
retry:
fd = accept4(this->fd, NULL, NULL, SOCK_NONBLOCK | SOCK_CLOEXEC);
if (fd < 0) {
switch (errno) {
case EINTR:
goto retry;
case ECONNABORTED:
case ECONNRESET:
case EPERM:
return;
default:
eprintf("accept4 <local socket> NULL NULL SOCK_NONBLOCK|SOCK_CLOEXEC:");
}
}
if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cred, &len)) {
weprintf("getsockopt <local client socket> SOL_SOCKET SO_PEERCRED:");
close(fd);
return;
}
if (len != (socklen_t)sizeof(cred))
abort();
if (cred.uid != uid) {
/* TODO maybe it should be possible to open up realms to specific/all
* users so they don't need a separate instance running */
close(fd);
return;
}
file = emalloc(sizeof(*file));
file->type = CLIENT_FILE;
file->fd = fd;
file->on_event = &on_client_event;
file->next = &clients_tail;
file->prev = clients_tail.prev;
clients_tail.prev->next = file;
clients_tail.prev = file;
memset(&ev, 0, sizeof(ev));
ev.events = EPOLLIN;
ev.data.ptr = file;
if (epoll_ctl(epoll, EPOLL_CTL_ADD, file->fd, &ev))
eprintf("epoll_ctl <epoll> EPOLL_CTL_ADD <client local socket> {EPOLLIN}:");
}
static struct network_file *
create_network_socket(void)
{
struct sockaddr_in addr;
socklen_t addrlen = (socklen_t)sizeof(addr);
struct network_file *file;
struct epoll_event ev;
file = emalloc(sizeof(*file));
file->type = NETWORK_FILE;
file->on_event = &on_network_socket_event;
file->fd = socket(PF_INET, SOCK_STREAM, 0);
if (file->fd < 0)
eprintf("socket PF_INET SOCK_STREAM 0:");
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(file->fd, (const void *)&addr, addrlen))
eprintf("bind <tcp socket> &{AF_INET, 0.0.0.0:0}:");
if (getsockname(file->fd, &addr, &addrlen))
eprintf("getsockname <tcp socket>:");
if (addrlen < (socklen_t)(offsetof(struct sockaddr_in, sin_port) + sizeof(addr.sin_port)))
abort();
server_identity.port = addr.sin_port;
if (listen(file->fd, SOMAXCONN))
eprintf("listen <tcp socket> SOMAXCONN:");
memset(&ev, 0, sizeof(ev));
ev.events = EPOLLIN;
ev.data.ptr = file;
if (epoll_ctl(epoll, EPOLL_CTL_ADD, file->fd, &ev))
eprintf("epoll_ctl <epoll> EPOLL_CTL_ADD <tcp server socket> {EPOLLIN}:");
return file;
}
static struct broadcast_file *
create_broadcast_socket(uint16_t port)
{
struct broadcast_file *file;
struct epoll_event ev;
file = emalloc(sizeof(*file));
memset(file, 0, sizeof(*file));
file->type = BROADCAST_FILE;
file->on_event = &on_broadcast_socket_event;
file->timer_inc = 1;
file->timer.type = TIMER_FILE;
file->timer.owner = (void *)file;
file->timer.on_event = &on_broadcast_timer_event;
file->fd = socket(PF_INET, SOCK_DGRAM, 0);
if (file->fd < 0)
eprintf("socket PF_INET SOCK_DGRAM 0:");
/* TODO switch to multicast (for portability) */
if (setsockopt(file->fd, SOL_SOCKET, SO_REUSEADDR, &(int){1}, (socklen_t)sizeof(int)))
eprintf("setsockopt <udp socket> SOL_SOCKET SO_REUSEADDR &{1}:");
if (setsockopt(file->fd, SOL_SOCKET, SO_BROADCAST, &(int){1}, (socklen_t)sizeof(int)))
eprintf("setsockopt <udp socket> SOL_SOCKET SO_BROADCAST &{1}:");
memset(&file->addr, 0, sizeof(file->addr));
file->addr.sin_family = AF_INET;
file->addr.sin_port = htons(port);
file->addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(file->fd, SOCKADDR(file->addr)))
eprintf("bind <broadcast socket> &{AF_INET, 0.0.0.0:%i}:", port);
file->addr.sin_addr.s_addr = htonl(INADDR_BROADCAST);
file->timer.fd = timerfd_create(CLOCK_BOOTTIME, 0);
if (file->timer.fd < 0)
eprintf("timerfd_create CLOCK_BOOTTIME 0:");
memset(&ev, 0, sizeof(ev));
ev.events = EPOLLIN;
ev.data.ptr = file;
if (epoll_ctl(epoll, EPOLL_CTL_ADD, file->fd, &ev))
eprintf("epoll_ctl <epoll> EPOLL_CTL_ADD <broadcast socket> {EPOLLIN}:");
ev.data.ptr = &file->timer;
if (epoll_ctl(epoll, EPOLL_CTL_ADD, file->timer.fd, &ev))
eprintf("epoll_ctl <epoll> EPOLL_CTL_ADD <timerfd for broadcast socket> {EPOLLIN}:");
return file;
}
static struct local_file *
create_local_socket(const char *address)
{
struct sockaddr_un addr;
socklen_t addrlen = (socklen_t)sizeof(addr);
struct local_file *file;
struct epoll_event ev;
size_t len;
int print_sockname = 0;
len = strlen(address);
if (len > sizeof(addr.sun_path))
eprintf("local address overlong: %s", address);
file = emalloc(sizeof(*file));
file->type = LOCAL_FILE;
file->on_event = &on_local_socket_event;
file->fd = socket(PF_LOCAL, SOCK_SEQPACKET, 0);
if (file->fd < 0)
eprintf("socket PF_LOCAL SOCK_SEQPACKET 0:");
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_LOCAL;
memcpy(addr.sun_path, address, len);
if (!len || addr.sun_path[0u] == '@') {
addr.sun_path[0u] = '\0';
if (len <= 1u) {
for (len = 1u; len < sizeof(addr.sun_path); len++)
addr.sun_path[len] = ALPHA64[rand() & 63];
print_sockname = 1;
} else {
addrlen = (socklen_t)(offsetof(struct sockaddr_un, sun_path) + len);
}
}
if (bind(file->fd, (const void *)&addr, addrlen))
eprintf("bind <local socket> &{AF_LOCAL, %c%.*s}:",
addr.sun_path[0u] ? addr.sun_path[0u] : '@',
(int)len - 1, &addr.sun_path[1u]);
if (listen(file->fd, SOMAXCONN))
eprintf("listen <local socket> SOMAXCONN:");
memset(&ev, 0, sizeof(ev));
ev.events = EPOLLIN;
ev.data.ptr = file;
if (epoll_ctl(epoll, EPOLL_CTL_ADD, file->fd, &ev))
eprintf("epoll_ctl <epoll> EPOLL_CTL_ADD <tcp server socket> {EPOLLIN}:");
if (print_sockname) {
if (printf("@%.*s\n", (int)len - 1, &addr.sun_path[1u]) < 0 || fflush(stdout))
eprintf("printf:");
}
return file;
}
static void
init_process(void)
{
struct timespec ts;
unsigned long int auxval;
unsigned seed = 0;
size_t i;
int fd;
do {
fd = open("/dev/null", O_RDWR);
if (fd < 0)
eprintf("open /dev/null O_RDWR:");
if (fd > STDERR_FILENO)
close(fd);
} while (fd < STDERR_FILENO);
uid = getuid();
libblake_init();
clients_head.prev = NULL;
clients_head.next = &clients_tail;
clients_tail.prev = &clients_head;
clients_tail.next = NULL;
auxval = getauxval(AT_RANDOM);
if (auxval) {
unsigned char *r = (unsigned char *)(uintptr_t)auxval;
for (i = 0u; i < 16u; i++)
seed = seed * 131u + r[i];
}
if (!clock_gettime(CLOCK_REALTIME, &ts)) {
seed ^= (unsigned)ts.tv_sec;
seed ^= (unsigned)ts.tv_nsec;
}
if (!clock_gettime(CLOCK_MONOTONIC, &ts)) {
seed ^= (unsigned)ts.tv_sec * (unsigned)2654435761lu;
seed ^= (unsigned)ts.tv_nsec;
}
srand(seed);
}
static void
load_config(const char *config_file, char **local_address, uint16_t *udp_port)
{
FILE *f;
ssize_t r;
char *key, *value;
char *line = NULL;
size_t size = 0u;
size_t len, off, i;
int fd, old_fd;
int udp_set = 0;
long int li;
unsigned long int lu;
char *end, *start;
const char *env;
char *config_file_free = NULL;
size_t config_file_size = 0u;
if (!config_file) {
#define SET_PREFIX(PREFIX) SET_PREFIXN(PREFIX, strlen(PREFIX))
#define SET_PREFIXN(PREFIX, LEN)\
do {\
if (config_file_size < (LEN) + 32u) {\
config_file_size = (LEN) + 32u;\
config_file_free = erealloc(config_file_free, config_file_size);\
}\
start = stpcpy(config_file_free, (PREFIX));\
} while (0)
#define TEST_CONFIG(PATH)\
do {\
if (!access(PATH, F_OK)) {\
config_file = (PATH);\
goto open_file;\
}\
} while (0)
env = getenv("OIKOBUS_CONFIG");
if (env && *env) {
config_file = env;
goto open_file;
}
env = getenv("XDG_CONFIG_HOME");
if (env && *env) {
SET_PREFIX(env);
stpcpy(start, "/oikobus/config");
TEST_CONFIG(config_file_free);
stpcpy(start, "/oikobus.conf");
TEST_CONFIG(config_file_free);
}
env = getenv("HOME");
if (env && *env) {
SET_PREFIX(env);
} else {
struct passwd *pw;
retry_getpwuid:
pw = getpwuid(uid);
if (!pw) {
if (errno == EINTR)
goto retry_getpwuid;
eprintf("getpwuid <real uid>:");
}
if (!pw->pw_dir || !*pw->pw_dir)
goto no_home;
SET_PREFIX(pw->pw_dir);
}
stpcpy(start, "/.config/oikobus/config");
TEST_CONFIG(config_file_free);
stpcpy(start, "/.config/oikobus.conf");
TEST_CONFIG(config_file_free);
stpcpy(start, "/.oikobus/config");
TEST_CONFIG(config_file_free);
stpcpy(start, "/.oikobus.conf");
TEST_CONFIG(config_file_free);
no_home:
env = getenv("XDG_CONFIG_DIRS");
if (env && *env) {
for (off = 0u; env[off]; off = i) {
for (i = off; env[i] && env[i] != ':'; i++);
len = i - off;
if (env[i])
i++;
if (!len)
continue;
SET_PREFIXN(&env[off], len);
stpcpy(start, "/oikobus/config");
TEST_CONFIG(config_file_free);
stpcpy(start, "/oikobus.conf");
TEST_CONFIG(config_file_free);
}
}
TEST_CONFIG("/etc/oikobus/config");
TEST_CONFIG("/etc/oikobus.conf");
eprintf("no configuration file found, use -c/dev/null if you don't want to load one");
#undef SET_PREFIXN
#undef SET_PREFIX
#undef TEST_CONFIG
} else {
if (!strcmp(config_file, "-")) {
config_file = "/dev/stdin";
fd = STDIN_FILENO;
goto open_fd;
} else if (!strcmp(config_file, "/dev/stdin")) {
fd = STDIN_FILENO;
goto open_fd;
} else if (!strcmp(config_file, "/dev/stdout")) {
fd = STDOUT_FILENO;
goto open_fd;
} else if (!strcmp(config_file, "/dev/stderr")) {
fd = STDERR_FILENO;
goto open_fd;
}
if (strstarts(config_file, "/dev/fd/")) {
off = sizeof("/dev/fd/") - 1u;
} else if (strstarts(config_file, "/proc/self/fd/")) {
off = sizeof("/proc/self/fd/") - 1u;
} else {
goto open_file;
}
if ('0' > config_file[off] || config_file[off] > '9')
goto open_file;
errno = 0;
li = strtol(&config_file[off], &end, 10);
if (errno || li < 0 || li > INT_MAX || *end)
goto open_file;
fd = (int)li;
if (fd <= STDERR_FILENO) {
open_fd:
fd = dup(old_fd = fd);
if (fd < 0)
eprintf("dup %i:", old_fd);
}
f = fdopen(fd, "r");
goto file_opened;
}
open_file:
f = fopen(config_file, "r");
file_opened:
if (!f)
eprintf("%s:", config_file);
while ((r = getdelim(&line, &size, '\n', f)) != -1) {
len = (size_t)r;
if (len && line[len - 1u] == '\n')
line[--len] = '\0';
if (len && line[len - 1u] == '\r')
line[--len] = '\0';
off = 0u;
while (isspace(line[off]))
off++;
key = &line[off];
value = NULL;
for (i = off; line[i]; i++) {
if (line[i] == '#' || line[i] == ';') {
if (i == off || isspace(line[i - 1u])) {
line[i] = '\0';
len = i;
break;
}
} else if ((line[i] == ':' || line[i] == '=') && !value) {
value = &line[i];
}
}
while (len && isspace(line[len - 1u]))
line[--len] = '\0';
if (value) {
i = (size_t)(value - key);
*value++ = '\0';
while (isspace(*value))
value++;
while (i-- && isspace(line[i]))
line[i] = '\0';
}
if (nrealms) {
if (!strcmp(key, "password")) {
if (!value)
goto value_missing;
if (realms[nrealms - 1u].key)
goto duplicate_realm_option;
realms[nrealms - 1u].key = estrdup(value);
} else {
eprintf("%s: realm option '%s' not recognised", config_file, key);
}
} else if (!value && key[0] == '[' && (end = strchr(key, '\0'))[-1] == ']') {
key++;
*--end = '\0';
len = (size_t)(end - key);
if (len < MIN_REALM_LEN || len > MAX_REALM_LEN)
eprintf("%s: invalid realm name length: '%s', must "
"be between %u and %u bytes (inclusively)",
config_file, key, MIN_REALM_LEN, MAX_REALM_LEN);
for (i = 0u; i < nrealms; i++)
if (!strcmp(key, realms[i].name))
eprintf("%s: duplicate section for realm '%s'", config_file, key);
realms = ereallocarray(realms, ++nrealms, sizeof(*realms));
realms[nrealms - 1u].name = estrdup(key);
realms[nrealms - 1u].key = NULL;
} else {
if (!strcmp(key, "udp-port")) {
if (!value)
goto value_missing;
if (udp_set++)
goto duplicate_global_option;
errno = 0;
lu = strtoul(value, &end, 10);
if (errno || lu == 0u || lu > UINT16_MAX || *end)
eprintf("%s: global option '%s' not recognised requires a "
"non-zero, unsigned 16-bit integer", config_file, key);
*udp_port = (uint16_t)lu;
} else if (!strcmp(key, "unix-address")) {
if (!value)
goto value_missing;
if (*local_address)
goto duplicate_global_option;
*local_address = estrdup(value);
} else {
eprintf("%s: global option '%s' not recognised", config_file, key);
}
}
}
if (ferror(f) || fclose(f))
eprintf("getline %s:", config_file);
free(line);
free(config_file_free);
return;
duplicate_realm_option:
eprintf("%s: realm option '%s' configured twice for realm '%s'", config_file, key, realms[nrealms - 1u].name);
duplicate_global_option:
eprintf("%s: global option '%s' configured twice", config_file, key);
value_missing:
eprintf("%s: option '%s' requires a value", config_file, key);
}
static void
init_server(const char *config_file, const char *local_address_cmdline, uint16_t udp_port_cmdline)
{
uint16_t udp_port = UDP_PORT;
const char *local_address = NULL;
char *local_address_free = NULL;
char local_address_buf[LOCAL_ADDRESS_BUFSIZE];
size_t i;
load_config(config_file, &local_address_free, &udp_port);
local_address = local_address_free;
if (udp_port_cmdline)
udp_port = udp_port_cmdline;
if (local_address_cmdline)
local_address = local_address_cmdline;
if (!local_address) {
sprintf(local_address_buf, LOCAL_ADDRESS(getuid()));
local_address = local_address_buf;
}
for (i = 0u; i < sizeof(server_identity.id); i++)
((unsigned char *)&server_identity.id)[i] = (unsigned char)(rand() & 255);
events_size = 32;
events = ecalloc((size_t)events_size, sizeof(*events));
epoll = epoll_create1(0);
if (epoll < 0)
eprintf("create_epoll1 0:");
lsock = create_local_socket(local_address);
nsock = create_network_socket();
bsock = create_broadcast_socket(udp_port);
free(local_address_free);
}
static void
signal_inited(void)
{
if (dup2(STDERR_FILENO, STDIN_FILENO) != STDIN_FILENO)
eprintf("dup2 STDERR_FILENO STDIN_FILENO:");
if (dup2(STDERR_FILENO, STDOUT_FILENO) != STDOUT_FILENO)
eprintf("dup2 STDERR_FILENO STDOUT_FILENO:");
}
int
main(int argc, char *argv[])
{
uint16_t udp_port_cmdline = 0u;
const char *config_file = NULL;
const char *local_address_cmdline = NULL;
char *arg;
unsigned long int lu;
union file *file;
int n;
ARGBEGIN {
/* TODO add daemonisation options */
/* TODO add realm options */
case 'a':
if (local_address_cmdline)
usage();
local_address_cmdline = ARG();
if (!*local_address_cmdline)
usage();
break;
case 'c':
if (config_file)
usage();
config_file = ARG();
if (!*config_file)
usage();
break;
case 'p':
arg = ARG();
if ('0' > arg[0u] || arg[0u] > '9' || udp_port_cmdline)
usage();
errno = 0;
lu = strtoul(arg, &arg, 10);
if (errno || *arg || lu > UINT16_MAX || !lu)
usage();
udp_port_cmdline = (uint16_t)lu;
break;
default:
usage();
} ARGEND;
/* -W is reserved for vendor options */
if (argc)
usage();
init_process();
init_server(config_file, local_address_cmdline, udp_port_cmdline);
broadcast_identity(bsock);
signal_inited();
for (;;) {
n = epoll_wait(epoll, events, events_size, -1);
if (n < 0) {
if (errno == EINTR)
continue;
eprintf("epoll_wait <epoll> <buffer> %i -1:", events_size);
}
while (n--) {
file = events[n].data.ptr;
(*file->on_event)(file, events[n].events);
}
}
}
|