/
net.c
1660 lines (1447 loc) · 48.2 KB
/
net.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
#include <arcan_shmif.h>
#include <arcan_shmif_server.h>
#include <errno.h>
#include <pwd.h>
#include <unistd.h>
#include <signal.h>
#include <poll.h>
#include <fcntl.h>
#include <inttypes.h>
#include <sys/wait.h>
#include <stdarg.h>
#include <ctype.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <netdb.h>
#include "a12.h"
#include "a12_int.h"
#include "a12_helper.h"
#include "anet_helper.h"
#include "directory.h"
enum anet_mode {
ANET_SHMIF_CL = 1,
ANET_SHMIF_CL_REVERSE = 2,
ANET_SHMIF_SRV,
ANET_SHMIF_SRV_INHERIT,
ANET_SHMIF_EXEC,
ANET_SHMIF_DIRSRV_INHERIT
};
enum mt_mode {
MT_SINGLE = 0,
MT_FORK = 1
};
struct arcan_net_meta {
struct anet_options* opts;
int argc;
char** argv;
char* bin;
};
static struct {
bool soft_auth;
bool no_default;
bool probe_only;
bool keep_alive;
size_t accept_n_pk_unknown;
size_t backpressure;
size_t backpressure_soft;
int directory;
struct anet_dirsrv_opts dirsrv;
struct anet_dircl_opts dircl;
char* trust_domain;
char* path_self;
char* outbound_tag;
volatile bool flag_rescan;
} global = {
.backpressure_soft = 2,
.backpressure = 6,
.directory = -1,
.outbound_tag = "default",
.dircl = {
.source_port = 6681
},
.dirsrv = {
.allow_tunnel = true
}
};
static const char* trace_groups[] = {
"video",
"audio",
"system",
"event",
"transfer",
"debug",
"missing",
"alloc",
"crypto",
"vdetail",
"binary",
"security",
"directory"
};
static struct a12_vframe_opts vcodec_tuning(
struct a12_state* S, int segid, struct shmifsrv_vbuffer* vb, void* tag);
/* keystore is singleton global */
static struct keystore_provider prov = {
.type = A12HELPER_PROVIDER_BASEDIR,
.directory.dirfd = -1
};
static bool open_keystore(const char** err)
{
if (-1 == prov.directory.dirfd){
prov.directory.dirfd = a12helper_keystore_dirfd(err);
if (-1 == prov.directory.dirfd)
return false;
}
if (!a12helper_keystore_open(&prov)){
*err = "Couldn't open keystore from basedir (ARCAN_STATEPATH)";
return false;
}
return true;
}
static int tracestr_to_bitmap(char* work)
{
int res = 0;
char* pt = strtok(work, ",");
while(pt != NULL){
for (size_t i = 1; i <= COUNT_OF(trace_groups); i++){
if (strcasecmp(trace_groups[i-1], pt) == 0){
res |= 1 << (i - 1);
break;
}
}
pt = strtok(NULL, ",");
}
return res;
}
/*
* Since we pull in some functions from the main arcan codebase, we need to
* define this symbol, used if the random function has problems with entropy
* etc.
*/
void arcan_fatal(const char* msg, ...)
{
va_list args;
va_start(args, msg);
vfprintf(stderr, msg, args);
va_end(args);
exit(EXIT_FAILURE);
}
static bool handover_setup(struct a12_state* S,
int fd, struct arcan_net_meta* meta, struct shmifsrv_client** C)
{
if (meta->opts->mode != ANET_SHMIF_EXEC && global.directory <= 0)
return true;
/* wait for authentication before going for the shmifsrv processing mode */
char* msg;
if (!anet_authenticate(S, fd, fd, &msg)){
a12int_trace(A12_TRACE_SYSTEM, "authentication failed: %s", msg);
free(msg);
shutdown(fd, SHUT_RDWR);
close(fd);
return false;
}
if (S->remote_mode == ROLE_PROBE){
a12int_trace(A12_TRACE_SYSTEM, "probed:terminating");
shutdown(fd, SHUT_RDWR);
close(fd);
return false;
}
a12int_trace(A12_TRACE_SYSTEM, "client connected, spawning: %s", meta->bin);
/* connection is ok, tie it to a new shmifsrv_client via the exec arg. The GUID
* is left 0 here as the local bound applications tend to not have much of a
* perspective on that. Should it become relevant, just stepping Kp with a local
* salt through the hash should do the trick. */
int socket, errc;
extern char** environ;
struct shmifsrv_envp env = {
.init_w = 32, .init_h = 32,
.path = meta->bin,
.argv = meta->argv, .envv = environ
};
*C = shmifsrv_spawn_client(env, &socket, &errc, 0);
if (!*C){
shutdown(fd, SHUT_RDWR);
close(fd);
return false;
}
return true;
}
static int get_bcache_dir()
{
const char* base = getenv("A12_CACHE_DIR");
if (!base)
return -1;
return open(base, O_DIRECTORY | O_CLOEXEC);
}
#ifdef DEBUG
extern void shmifint_set_log_device(struct arcan_shmif_cont*, FILE*);
#endif
static void set_log_trace()
{
#ifdef DEBUG
if (!a12_trace_targets)
return;
char buf[sizeof("cl_log_xxxxxx.log")];
snprintf(buf, sizeof(buf), "cl_log_%.6d.log", (int) getpid());
FILE* fpek = fopen(buf, "w+");
shmifint_set_log_device(NULL, fpek);
if (fpek){
a12_set_trace_level(a12_trace_targets, fpek);
}
#endif
}
static void fork_a12srv(struct a12_state* S, int fd, void* tag)
{
/*
* With the directory server mode we also maintain a shmif server connection
* and inherit shmif into the forked child that is a re-execution of ourselves. */
int clsock = -1;
struct shmifsrv_client* cl = NULL;
struct arcan_net_meta* ameta = tag;
if (global.directory > 0){
if (global.flag_rescan){
anet_directory_srv_rescan(&global.dirsrv);
anet_directory_shmifsrv_set(&global.dirsrv);
global.flag_rescan = false;
}
char tmpfd[32], tmptrace[32];
snprintf(tmpfd, sizeof(tmpfd), "%d", fd);
snprintf(tmptrace, sizeof(tmptrace), "%d", a12_trace_targets);
char* argv[] = {global.path_self, "-d", tmptrace, "-S", tmpfd, NULL, NULL};
/* shmif-server lib will get to waitpid / kill so we don't need to care here */
struct shmifsrv_envp env = {
.path = global.path_self,
.envv = NULL,
.argv = argv,
.detach = 2 | 4 | 8
};
cl = shmifsrv_spawn_client(env, &clsock, NULL, 0);
if (cl){
anet_directory_shmifsrv_thread(cl, S);
}
a12_channel_close(S);
close(fd);
return;
}
pid_t fpid = fork();
/* just ignore and return to caller */
if (fpid > 0){
a12int_trace(A12_TRACE_SYSTEM, "client handed off to %d", (int)fpid);
a12_channel_close(S);
close(fd);
close(clsock);
return;
}
if (fpid == -1){
a12int_trace(A12_TRACE_SYSTEM, "couldn't fork/dispatch, ulimits reached?\n");
a12_channel_close(S);
close(fd);
return;
}
/* Split the log output on debug so we see what is going on */
set_log_trace();
/* make sure that we don't leak / expose whatever the listening process has,
* not much to do to guarantee or communicate the failure on these three -
* possibly creating a slush-pipe and dup:ing that .. */
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
open("/dev/null", O_RDONLY);
open("/dev/null", O_WRONLY);
open("/dev/null", O_WRONLY);
if (cl){
shmifsrv_free(cl, SHMIFSRV_FREE_NO_DMS);
}
struct shmifsrv_client* C = NULL;
struct arcan_net_meta* meta = tag;
int rc = 0;
if (!handover_setup(S, fd, meta, &C)){
goto out;
}
/* this is for a full 'remote desktop' like scenario, directory is handled
* in handover_setup */
arcan_shmif_privsep(NULL, "shmif", NULL, 0);
if (C){
a12helper_a12cl_shmifsrv(S, C, fd, fd, (struct a12helper_opts){
.redirect_exit = meta->opts->redirect_exit,
.devicehint_cp = meta->opts->devicehint_cp,
.vframe_block = global.backpressure,
.vframe_soft_block = global.backpressure_soft,
.eval_vcodec = vcodec_tuning,
.bcache_dir = get_bcache_dir()
});
shmifsrv_free(C, SHMIFSRV_FREE_NO_DMS);
}
else {
/* we should really re-exec ourselves with the 'socket-passing' setup so that
* we won't act as a possible ASLR break */
rc = a12helper_a12srv_shmifcl(NULL, S, NULL, fd, fd);
}
out:
shutdown(fd, SHUT_RDWR);
close(fd);
exit(rc < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
}
extern char** environ;
static struct a12_vframe_opts vcodec_tuning(
struct a12_state* S, int segid, struct shmifsrv_vbuffer* vb, void* tag)
{
struct a12_vframe_opts opts = {
.method = VFRAME_METHOD_DZSTD,
.bias = VFRAME_BIAS_BALANCED
};
/* missing: here a12_state_iostat could be used to get congestion information
* and encoder feedback, then use that to forward new parameters + bias */
switch (segid){
case SEGID_LWA:
opts.method = VFRAME_METHOD_H264;
break;
case SEGID_GAME:
opts.method = VFRAME_METHOD_H264;
opts.bias = VFRAME_BIAS_LATENCY;
break;
case SEGID_AUDIO:
opts.method = VFRAME_METHOD_RAW_NOALPHA;
opts.bias = VFRAME_BIAS_LATENCY;
break;
/* this one is also a possible subject for codec passthrough, that will have
* to be implemented in the server util part as we need shmif to propagate if
* we can deal with passthrough and then device_fail that if the other end
* starts to reject the bitstream */
case SEGID_MEDIA:
case SEGID_BRIDGE_WAYLAND:
case SEGID_BRIDGE_X11:
opts.method = VFRAME_METHOD_H264;
opts.bias = VFRAME_BIAS_QUALITY;
break;
}
/* this is temporary until we establish a config format where the parameters
* can be set in a non-commandline friendly way (recall ARCAN_CONNPATH can
* result in handover-exec arcan-net */
if (opts.method == VFRAME_METHOD_H264){
static bool got_opts;
static unsigned long cbr = 22;
static unsigned long br = 1024;
/* convert and clamp to the values supported by x264 in ffmpeg */
if (!got_opts){
char* tmp;
if ((tmp = getenv("A12_VENC_CRF"))){
cbr = strtoul(tmp, NULL, 10);
if (cbr > 55)
cbr = 55;
}
if ((tmp = getenv("A12_VENC_RATE"))){
br = strtoul(tmp, NULL, 10);
if (br * 1000 > INT_MAX)
br = INT_MAX;
}
got_opts = true;
}
opts.ratefactor = cbr;
opts.bitrate = br;
}
return opts;
}
static void single_a12srv(struct a12_state* S, int fd, void* tag)
{
struct shmifsrv_client* C = NULL;
struct arcan_net_meta* meta = tag;
if (!handover_setup(S, fd, meta, &C))
return;
if (C){
a12helper_a12cl_shmifsrv(S, C, fd, fd, (struct a12helper_opts){
.redirect_exit = meta->opts->redirect_exit,
.devicehint_cp = meta->opts->devicehint_cp,
.vframe_block = global.backpressure,
.vframe_soft_block = global.backpressure_soft,
.eval_vcodec = vcodec_tuning,
.bcache_dir = get_bcache_dir()
});
shmifsrv_free(C, SHMIFSRV_FREE_NO_DMS);
}
else{
a12helper_a12srv_shmifcl(NULL, S, NULL, fd, fd);
shutdown(fd, SHUT_RDWR);
close(fd);
}
}
static void dir_to_shmifsrv(struct a12_state* S, struct a12_dynreq a, void* tag);
struct dirstate {
int fd;
struct anet_options* aopts;
struct shmifsrv_client* shmif;
struct a12_dynreq req;
};
static void a12cl_dispatch(
struct anet_options* args,
struct a12_state* S, struct shmifsrv_client* cl, int fd)
{
/* Directory mode has a simpler processing loop so treat it special here, also
* reducing attack surface since very little actual forwarding or processing is
* needed. */
if (global.directory > 0){
global.dircl.basedir = global.directory;
anet_directory_cl(S, global.dircl, fd, fd);
close(fd);
return;
}
/* we are registering ourselves as a sink into a remote directory, that is
* special in the sense that we hold on to the shmifsrv_client for a bit and
* if we get a dir-open we latch the two together. */
if (a12_remote_mode(S) == ROLE_DIR){
struct dirstate* ds = malloc(sizeof(struct dirstate));
*ds = (struct dirstate){
.fd = fd,
.aopts = args,
.shmif = cl
};
global.dircl.dir_source = dir_to_shmifsrv;
global.dircl.dir_source_tag = ds;
anet_directory_cl(S, global.dircl, fd, fd);
free(ds);
}
else
/* note that the a12helper will do the cleanup / free */
a12helper_a12cl_shmifsrv(S, cl, fd, fd, (struct a12helper_opts){
.vframe_block = global.backpressure,
.redirect_exit = args->redirect_exit,
.devicehint_cp = args->devicehint_cp,
.bcache_dir = get_bcache_dir()
});
close(fd);
}
static struct pk_response key_auth_dir(uint8_t pk[static 32], void* tag)
{
struct dirstate* ds = tag;
struct pk_response auth = {.authentic = true};
/* We need the key we registered with the dirsrv with as the sink will be
* expecting it, while we trust whatever as the outer packet authk combine with
* the ephemeral key.
*
* The ephemeral key match what the source (us) registered as, the same goes
* for the inner. The reason for this is to be able to determine via a sideband
* if the directory is trying to MITM. Since the Kpub is announced via the
* directory the source can fire up another client and check that the announced
* key is the same as the one it actually announced.
*/
char* tmp;
uint16_t tmpport;
uint8_t my_private_key[32];
a12helper_keystore_hostkey(
global.outbound_tag, 0, my_private_key, &tmp, &tmpport);
a12_set_session(&auth, pk, my_private_key);
return auth;
}
static void dir_a12srv(struct a12_state* S, int fd, void* tag)
{
struct dirstate* ds = tag;
a12int_trace(A12_TRACE_DIRECTORY, "source_inbound_connected");
/* should not be able to happen at this stage, hello won't go through without
* the right authk and if you have that you're either source, sink or dirsrv
* and both sink and dirsrv would be able to math the pubk. */
char* msg;
if (!anet_authenticate(S, fd, fd, &msg)){
a12int_trace(A12_TRACE_SECURITY, "authentication_failed");
return;
}
a12int_trace(A12_TRACE_DIRECTORY, "source_inbound_ready");
a12helper_a12cl_shmifsrv(S, ds->shmif, fd, fd, (struct a12helper_opts){
.redirect_exit = ds->aopts->redirect_exit,
.devicehint_cp = ds->aopts->devicehint_cp,
.vframe_block = global.backpressure,
.vframe_soft_block = global.backpressure_soft,
.eval_vcodec = vcodec_tuning,
.bcache_dir = get_bcache_dir()
});
shmifsrv_free(ds->shmif, SHMIFSRV_FREE_NO_DMS);
shutdown(fd, SHUT_RDWR);
exit(EXIT_SUCCESS);
}
static void dir_to_shmifsrv(struct a12_state* S, struct a12_dynreq a, void* tag)
{
a12int_trace(A12_TRACE_DIRECTORY, "open_request_negotiated");
struct dirstate* ds = tag;
ds->req = a;
pid_t fpid = fork();
/* Here, we fork() into listening on our registered port, this is the same as
* the cldispatch that forks. We shouldn't be in a path where any substantial
* POSIX 'technically UB territory buuuut' approach to the fork pattern has any
* real effect.
*
* When things are a bit more robust, switch to the fork-fexec self approach
* anyhow for IPC cleanliness, it's just inheriting the shmifsrc-client setup
* that is a bit of a hassle. */
if (fpid == 0){
/* Trust the directory server provided secret.
*
* A nuanced option here is if to set the accept_n_pk_unknown to 1 or not.
* The consequence is that the directory or the sink gets to install one key
* we trust for inbound use.
*
* One probably would want to set that to a specific group for this context
* of use, or mark the transitive origin / history. If that doesn't happen
* and the keystore gets re-used for sourcing something else, that installed
* key is part of the general trusted base.
*
* At the same time tracking the key, and depending on connection mode, add
* that as a possible outbound target with the IP it connected from if an
* interesting option for future discovery both LAN and WAN as well as
* attribution.
*
* Block the behaviour outright for now, and don't forget that the parent might
* actually be running / bleeding some state into us from the command line that
* applied to the outbound connection when registering to the directory that
* should not apply now in the role of a source.
*/
global.soft_auth = true;
global.accept_n_pk_unknown = 0;
/* the shared secret to protect the initial hello is no longer optional, and we
* have an added touch of forcing the 'ephemeral' key to be the one supplied by
* the sink in order to let them differentiate the identity it uses with the
* directory versus the one it uses with us. */
snprintf(ds->aopts->opts->secret, 32, "%s", a.authk);
char* outhost;
uint16_t outport;
ds->aopts->opts->pk_lookup = key_auth_dir;
ds->aopts->opts->pk_lookup_tag = ds;
/* A subtle difference here is that the the private key we should use in the
* setup (here same for ephem and real) is the one used to outbound connect to
* the directory and not a listening default. We also want a timeout for the
* case where we listen but nobody connects to us (reachability?). Remove the
* host so that we don't try to bind the old outbound ip. */
char* errmsg = NULL;
ds->aopts->host = NULL;
anet_listen(ds->aopts, &errmsg, dir_a12srv, ds);
fprintf(stderr, "%s", errmsg ? errmsg : "");
exit(EXIT_SUCCESS);
}
else if (fpid == -1){
fprintf(stderr, "fork_a12cl() couldn't fork new process, check ulimits\n");
shmifsrv_free(ds->shmif, SHMIFSRV_FREE_NO_DMS);
shutdown(ds->fd, SHUT_RDWR);
close(ds->fd);
return;
}
else {
/* just ignore and return to caller, we might need a monitoring channel for
* multiplexing in tunnel- traffic - and in those cases we need to keep the
* ds->fd (directory connection) alive. the same goes for --exec mode, as we
* can supply more clients through the same directory setup we can keep it
* alive, but that has more considerations -- how many do we want? the other
* connections might require tunneling, so at first it is better to just go 1:1
* for dirsrv connection and --exec pass. */
a12int_trace(A12_TRACE_SYSTEM, "client handed off to %d", (int)fpid);
shmifsrv_free(ds->shmif, SHMIFSRV_FREE_LOCAL);
shutdown(ds->fd, SHUT_RDWR);
wait(NULL);
close(ds->fd);
}
}
static void fork_a12cl_dispatch(
struct anet_options* args,
struct a12_state* S, struct shmifsrv_client* cl, int fd)
{
pid_t fpid = fork();
if (fpid == 0){
a12cl_dispatch(args, S, cl, fd);
exit(EXIT_SUCCESS);
}
else if (fpid == -1){
fprintf(stderr, "fork_a12cl() couldn't fork new process, check ulimits\n");
shmifsrv_free(cl, SHMIFSRV_FREE_NO_DMS);
a12_channel_close(S);
shutdown(fd, SHUT_RDWR);
close(fd);
return;
}
else {
/* just ignore and return to caller */
a12int_trace(A12_TRACE_SYSTEM, "client handed off to %d", (int)fpid);
a12_channel_close(S);
shmifsrv_free(cl, SHMIFSRV_FREE_LOCAL);
shutdown(fd, SHUT_RDWR);
close(fd);
}
}
static struct anet_cl_connection find_connection(
struct anet_options* opts, struct shmifsrv_client* cl)
{
struct anet_cl_connection anet;
int rc = opts->retry_count;
int timesleep = 1;
const char* err;
if (!open_keystore(&err)){
fprintf(stderr, "couldn't open keystore: %s\n", err);
}
if (!global.trust_domain)
global.trust_domain = strdup("outbound");
/* connect loop until retry count exceeded */
while (rc != 0 && (!cl || (shmifsrv_poll(cl) != CLIENT_DEAD))){
anet = anet_cl_setup(opts);
if (anet.state)
break;
if (!anet.state){
if (anet.errmsg){
fputs(anet.errmsg, stderr);
free(anet.errmsg);
anet.errmsg = NULL;
}
if (timesleep < 10)
timesleep++;
if (rc > 0)
rc--;
sleep(timesleep);
continue;
}
}
return anet;
}
/* connect / authloop shmifsrv */
static struct anet_cl_connection forward_shmifsrv_cl(
struct shmifsrv_client* cl, struct anet_options* opts)
{
struct anet_cl_connection anet = find_connection(opts, cl);
/* failed, or retry-count exceeded? */
if (!anet.state || shmifsrv_poll(cl) == CLIENT_DEAD){
shmifsrv_free(cl, SHMIFSRV_FREE_NO_DMS);
if (anet.state){
a12_free(anet.state);
close(anet.fd);
if (anet.errmsg)
free(anet.errmsg);
}
}
/* wait / block the processing until we know the connection is authentic,
* this will callback into keystore and so on */
char* msg;
if (!anet_authenticate(anet.state,
anet.fd, anet.fd, &msg) || shmifsrv_poll(cl) == CLIENT_DEAD){
if (msg){
a12int_trace(A12_TRACE_SYSTEM, "authentication_failed=%s", msg);
}
shmifsrv_free(cl, SHMIFSRV_FREE_NO_DMS);
if (anet.state){
a12_free(anet.state);
close(anet.fd);
}
if (anet.errmsg)
free(anet.errmsg);
}
return anet;
}
static int a12_connect(struct anet_options* args,
void (*dispatch)(
struct anet_options* args,
struct a12_state* S, struct shmifsrv_client* cl, int fd))
{
signal(SIGPIPE, SIG_IGN);
signal(SIGCHLD, SIG_IGN);
int shmif_fd = -1;
for(;;){
struct shmifsrv_client* cl =
shmifsrv_allocate_connpoint(args->cp, NULL, S_IRWXU, shmif_fd);
if (!cl){
fprintf(stderr, "couldn't open connection point\n");
return EXIT_FAILURE;
}
/* first time, extract the connection point descriptor from the connection */
if (-1 == shmif_fd)
shmif_fd = shmifsrv_client_handle(cl);
struct pollfd pfd = {.fd = shmif_fd, .events = POLLIN | POLLERR | POLLHUP};
/* wait for a connection */
for(;;){
int pv = poll(&pfd, 1, -1);
if (-1 == pv){
if (errno != EINTR && errno != EAGAIN){
shmifsrv_free(cl, true);
fprintf(stderr, "error while waiting for a connection\n");
return EXIT_FAILURE;
}
continue;
}
else if (pv)
break;
}
/* accept it (this will mutate the client_handle internally) */
shmifsrv_poll(cl);
/* setup the connection, we do this after the fact rather than before as remote
* is more likely to have a timeout than locally */
struct anet_cl_connection anet = forward_shmifsrv_cl(cl, args);
/* wake the client */
a12int_trace(A12_TRACE_SYSTEM, "local connection found, forwarding to dispatch");
dispatch(args, anet.state, cl, anet.fd);
}
return EXIT_SUCCESS;
}
/* Special version of a12_connect where we inherit the connection primitive
* to the local shmif client, so we can forego most of the domainsocket bits.
* The normal use-case for this is where ARCAN_CONNPATH is set to a12://
* prefix and shmif execs into arcan-net */
static int a12_preauth(struct anet_options* args,
void (*dispatch)(
struct anet_options* args,
struct a12_state* S, struct shmifsrv_client* cl, int fd))
{
int sc;
struct shmifsrv_client* cl = shmifsrv_inherit_connection(args->sockfd, &sc);
if (!cl){
fprintf(stderr, "(shmif::arcan-net) "
"couldn't build connection from socket (%d)\n", sc);
shutdown(args->sockfd, SHUT_RDWR);
close(args->sockfd);
return EXIT_FAILURE;
}
args->opts->local_role = ROLE_SOURCE;
struct anet_cl_connection anet = forward_shmifsrv_cl(cl, args);
/* and ack the connection */
dispatch(args, anet.state, cl, anet.fd);
return EXIT_SUCCESS;
}
static bool tag_host(struct anet_options* anet, char* hoststr, const char** err)
{
char* toksep = strrchr(hoststr, '@');
if (!toksep)
return false;
*toksep = '\0';
anet->key = hoststr;
global.outbound_tag = hoststr;
anet->keystore.type = A12HELPER_PROVIDER_BASEDIR;
anet->keystore.directory.dirfd = a12helper_keystore_dirfd(err);
return true;
}
static bool show_usage(const char* msg)
{
fprintf(stderr, "Usage:\n"
"Forward local arcan applications (push): \n"
" arcan-net [-Xtd] -s connpoint [tag@]host port\n"
" (keystore-mode) -s connpoint tag@\n"
" (inherit socket) -S fd_no [tag@]host port\n\n"
"Server local arcan application (pull): \n"
" -l port [ip] -- /usr/bin/app arg1 arg2 argn\n\n"
"Bridge remote inbound arcan applications (to ARCAN_CONNPATH): \n"
" arcan-net [-Xtd] -l port [ip]\n\n"
"Bridge remote outbound arcan application: \n"
" arcan-net [tag@]host port\n\n"
"Directory/discovery server (uses ARCAN_APPLBASEPATH): \n"
" arcan-net --directory -l port [ip]\n\n"
"Directory/discovery client: \n"
" arcan-net [tag@]host port [appl]\n\n"
"Directory/discovery source-client: \n"
" arcan-net [tag@]host port -- name /usr/bin/app arg1 arg2 argn\n\n"
"Forward-local options:\n"
"\t-X \t Disable EXIT-redirect to ARCAN_CONNPATH env (if set)\n"
"\t-r, --retry n \t Limit retry-reconnect attempts to 'n' tries\n\n"
"Authentication:\n"
"\t --no-ephem-rt \t Disable ephemeral keypair roundtrip (outbound only)\n"
"\t-a, --auth n \t Read authentication secret from stdin (maxlen:32)\n"
"\t \t if [n] is provided, n keys added to trusted\n"
"\t --soft-auth \t Permit unknown via authentication secret (password)\n"
"\t --allow-pk n \t Explicitly permit (b64-encoded) Kpub\n"
"\t-T, --trust s \t Specify trust domain for splitting keystore\n"
"\t \t outbound connections default to 'outbound' while\n"
"\t \t serving/listening defaults to a wildcard ('*')\n\n"
""
"Options:\n"
"\t-t \t Single- client (no fork/mt - easier troubleshooting)\n"
"\t --probe-only \t (outbound) Authenticate and print server primary state\n"
"\t-d bitmap \t Set trace bitmap (bitmask or key1,key2,...)\n"
"\t-v, --version \t Print build/version information to stdout\n\n"
"Directory client options: \n"
"\t --keep-appl \t Don't wipe appl after execution\n"
"\t --reload \t Re-request the same appl after completion\n"
"\t --ident name \t When attaching as a source or directory, identify as [name]\n"
"\t --keep-alive \t Keep connection alive and print changes to the directory\n"
"\t --push-appl s \t Push [s] from APPLBASE to the server\n"
"\t --tunnel \t Default request tunnelling as source/sink connection\n"
"\t --block-log \t Don't attempt to forward script errors or crash logs\n"
"\t --source-port \t When sourcing use this port for listening\n"
"\t --block-state \t Don't attempt to synch state before/after running appl\n\n"
"Directory server options: \n"
"\t --allow-src s \t Let clients in trust group [s, all=*] register as sources\n"
"\t --allow-appl s \t Let clients in trust group [s, all=*] update appls and resources\n"
"\t --allow-dir s \t Let clients in trust group [s, all=*] register as directories\n\n"
"\t --block-tunnel \t Disallow tunneling traffic between isolated sources/sinks\n\n"
"Environment variables:\n"
"\tARCAN_STATEPATH\t Used for keystore and state blobs (sensitive)\n"
#ifdef WANT_H264_ENC
"\tA12_VENC_CRF \t video rate factor (sane=17..28) (0=lossless,51=worst)\n"
"\tA12_VENC_RATE \t bitrate in kilobits/s (hintcap to crf)\n"
#endif
"\tA12_VBP \t backpressure maximium cap (0..8)\n"
"\tA12_VBP_SOFT \t backpressure soft (full-frames) cap (< VBP)\n"
"\tA12_CACHE_DIR \t Used for caching binary stores (fonts, ...)\n\n"
"Keystore mode (ignores connection arguments):\n"
"\tAdd/Append key: arcan-net keystore tag host [port=6680]\n"
"\t tag=default is reserved\n"
"\nTrace groups (stderr):\n"
"\tvideo:1 audio:2 system:4 event:8 transfer:16\n"
"\tdebug:32 missing:64 alloc:128 crypto:256 vdetail:512\n"
"\tbinary:1024 security:2048 directory:4096\n\n%s%s",
msg ? msg : "",
msg ? "\n\n" : ""
);
return false;
}
static int apply_commandline(int argc, char** argv, struct arcan_net_meta* meta)
{
const char* modeerr = "Mixed or multiple -s or -l arguments";
struct anet_options* opts = meta->opts;
/* the default role is sink, -s -exec changes this to source */
opts->opts->local_role = ROLE_SINK;
/* default-trace security warnings */
a12_set_trace_level(2048, stderr);
size_t i = 1;
/* mode defining switches and shared switches */
for (; i < argc; i++){
if (argv[i][0] != '-')
break;
if (strcmp(argv[i], "-V") == 0 || strcmp(argv[i], "--version") == 0){
fprintf(stdout,
"%s\nshmif-%" PRIu64"\n", ARCAN_BUILDVERSION, arcan_shmif_cookie());
exit(EXIT_SUCCESS);
}
if (strcmp(argv[i], "-d") == 0){
if (i == argc - 1)
return show_usage("-d without trace value argument");
char* workstr = NULL;
unsigned long val = strtoul(argv[++i], &workstr, 10);
if (workstr == argv[i]){
val = tracestr_to_bitmap(workstr);
}
a12_set_trace_level(val, stderr);
}
/* a12 client, shmif server */
else if (strcmp(argv[i], "-s") == 0){
if (opts->mode)
return show_usage(modeerr);
opts->opts->local_role = ROLE_SOURCE;
opts->mode = ANET_SHMIF_SRV;
if (i >= argc - 1)
return show_usage("-s: Missing connpoint argument");
opts->cp = argv[++i];
/* shmif connection points are restricted set */
for (size_t ind = 0; opts->cp[ind]; ind++)
if (!isalnum(opts->cp[ind]))
return show_usage("-s: Invalid character in connpoint [a-Z,0-9]");
i++;
if (i >= argc)
return show_usage("-s: Missing tag@ or host port argument");
const char* err = NULL;
if (tag_host(opts, argv[i], &err)){
if (err)
return show_usage(err);
continue;
}
opts->host = argv[i++];
if (i >= argc)
return show_usage("-s: Missing port argument");
opts->port = argv[i];
if (i != argc - 1)
return show_usage("-s: Trailing arguments after port");
continue;
}
/* a12 client, shmif server, inherit primitives */
else if (strcmp(argv[i], "-S") == 0){
if (opts->mode)
return show_usage(modeerr);
opts->mode = ANET_SHMIF_SRV_INHERIT;
if (i >= argc - 1)
return show_usage("Invalid arguments, -S without room for socket");
opts->sockfd = strtoul(argv[++i], NULL, 10);
struct stat fdstat;
if (-1 == fstat(opts->sockfd, &fdstat))
return show_usage("Couldn't stat -S descriptor");
/* Both socket passed and preauth arcan shmif connection? treat that as the
* directory server forking off into itself to handle a client connection */
if (getenv("ARCAN_SOCKIN_FD")){
opts->mode = ANET_SHMIF_DIRSRV_INHERIT;
opts->opts->local_role = ROLE_DIR;
continue;
}
if ((fdstat.st_mode & S_IFMT) != S_IFSOCK)
return show_usage("-S descriptor does not point to a socket");
if (i == argc)
return show_usage("-S without room for tag or host/port");