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
|
/* SPDX-License-Identifier: GPL-2.0 */
/** \file command.c Client authentication and server commands. */
#include <netinet/in.h>
#include <sys/socket.h>
#include <signal.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <lopsub.h>
#include "para.h"
#include "error.h"
#include "lsu.h"
#include "crypt.h"
#include "sideband.h"
#include "command.h"
#include "string.h"
#include "afh.h"
#include "net.h"
#include "list.h"
#include "server.h"
#include "sched.h"
#include "send.h"
#include "vss.h"
#include "daemon.h"
#include "fd.h"
#include "ipc.h"
#include "server_cmd.lsg.h"
#include "signal.h"
/** \cond doxygen_ignore */
#define SERVER_CMD_AUX_INFO(_arg) _arg,
static const unsigned server_command_perms[] = {LSG_SERVER_CMD_AUX_INFOS};
#undef SERVER_CMD_AUX_INFO
#define SERVER_CMD_AUX_INFO(_arg) #_arg,
static const char * const server_command_perms_txt[] = {LSG_SERVER_CMD_AUX_INFOS};
#undef SERVER_CMD_AUX_INFO
/* Commands including options must be shorter than this. */
#define MAX_COMMAND_LEN 32768
/* Must be large enough for the auth request and the challange response. */
#define HANDSHAKE_BUFSIZE 4096
/** \endcond */
extern int mmd_mutex;
extern struct misc_meta_data *mmd;
int send_afs_status(struct command_context *cc, bool parser_friendly);
static bool subcmd_should_die;
/*
* Don't call PARA_XXX_LOG() here as we might already hold the log mutex. See
* generic_signal_handler() for details.
*/
static void command_handler_sighandler(int s)
{
if (s == SIGTERM)
subcmd_should_die = true;
}
/*
* Compute human readable vss status text.
*
* We can't call vss_playing() and friends here because those functions read
* the flags from the primary mmd structure, so calling them from command
* handler context would require to take the mmd lock. At the time the function
* is called we already took a copy of the mmd structure and want to use the
* flags value of the copy for computing the vss status text.
*/
static char *vss_status_tohuman(unsigned int flags)
{
if (flags & VSS_PLAYING)
return para_strdup("playing");
if (flags & VSS_NEXT)
return para_strdup("stopped");
return para_strdup("paused");
}
/*
* Never returns NULL.
*/
static char *vss_get_status_flags(unsigned int flags)
{
char *msg = alloc(5 * sizeof(char));
msg[0] = (flags & VSS_PLAYING)? 'P' : '_';
msg[1] = (flags & VSS_NOMORE)? 'O' : '_';
msg[2] = (flags & VSS_NEXT)? 'N' : '_';
msg[3] = (flags & VSS_REPOS)? 'R' : '_';
msg[4] = '\0';
return msg;
}
static unsigned get_status(struct misc_meta_data *nmmd, bool parser_friendly,
char **result)
{
char *status, *flags; /* vss status info */
long offset = (nmmd->offset + 500) / 1000;
/* nobody updates the command handler's instance of "now" */
struct timeval current_time;
struct para_buffer b = {.flags = parser_friendly? PBF_SIZE_PREFIX : 0};
/* report real status */
status = vss_status_tohuman(nmmd->vss_status_flags);
flags = vss_get_status_flags(nmmd->vss_status_flags);
clock_get_realtime(¤t_time);
WRITE_STATUS_ITEM(&b, SI_status, "%s\n", status);
WRITE_STATUS_ITEM(&b, SI_status_flags, "%s\n", flags);
WRITE_STATUS_ITEM(&b, SI_offset, "%li\n", offset);
WRITE_STATUS_ITEM(&b, SI_afs_mode, "%s\n", mmd->afs_mode_string);
WRITE_STATUS_ITEM(&b, SI_stream_start, "%lu.%lu\n",
(long unsigned)nmmd->stream_start.tv_sec,
(long unsigned)nmmd->stream_start.tv_usec);
WRITE_STATUS_ITEM(&b, SI_current_time, "%lu.%lu\n",
(long unsigned)current_time.tv_sec,
(long unsigned)current_time.tv_usec);
free(flags);
free(status);
*result = b.buf;
return b.offset;
}
/**
* Send a sideband packet through a blocking file descriptor.
*
* \param scc fd and crypto keys.
* \param buf The buffer to send.
* \param numbytes The size of \a buf.
* \param band The sideband designator of this packet.
* \param dont_free If true, never deallocate \a buf.
*
* The nonblock flag must be disabled for the file descriptor given by \a scc.
*
* Stream cipher encryption is automatically activated if necessary via the
* sideband transformation, depending on the value of \a band.
*
* \return Standard.
*
* \sa \ref send_sb_va().
*/
int send_sb(struct stream_cipher_context *scc, void *buf, size_t numbytes,
int band, bool dont_free)
{
int ret;
struct sb_context *sbc;
struct iovec iov[2];
sb_transformation trafo = band < SBD_PROCEED? NULL : sc_trafo;
struct sb_buffer sbb = SBB_INIT(band, buf, numbytes);
sbc = sb_new_send(&sbb, dont_free, trafo, scc->send);
do {
ret = sb_get_send_buffers(sbc, iov);
ret = xwritev(scc->fd, iov, ret);
if (ret < 0)
goto fail;
} while (sb_sent(sbc, ret) == false);
return 1;
fail:
sb_free(sbc);
return ret;
}
/**
* Create a variable sized buffer and send it as a sideband packet.
*
* \param scc Passed to \ref send_sb.
* \param band See \ref send_sb.
* \param fmt The format string.
*
* \return The return value of the underlying call to \ref send_sb.
*/
__printf_3_4 int send_sb_va(struct stream_cipher_context *scc, int band,
const char *fmt, ...)
{
va_list ap;
char *msg;
int ret;
va_start(ap, fmt);
ret = xvasprintf(&msg, fmt, ap);
va_end(ap);
return send_sb(scc, msg, ret, band, false);
}
/**
* Send an error message to a client.
*
* \param cc Client info.
* \param err The (positive) error code.
*
* \return The return value of the underlying call to send_sb_va().
*/
int send_strerror(struct command_context *cc, int err)
{
return send_sb_va(&cc->scc, SBD_ERROR_LOG, "%s\n", para_strerror(err));
}
/**
* Send an error context to a client,
*
* \param cc Client info.
* \param errctx The error context string.
*
* \return The return value of the underlying call to send_sb_va().
*
* This function frees the error context string after it was sent.
*/
int send_errctx(struct command_context *cc, char *errctx)
{
int ret;
if (!errctx)
return 0;
ret = send_sb_va(&cc->scc, SBD_ERROR_LOG, "%s\n", errctx);
free(errctx);
return ret;
}
static int check_sender_args(struct command_context *cc,
struct lls_parse_result *lpr, struct sender_command_data *scd)
{
int i, ret;
const char * const subcmds[] = {SENDER_SUBCOMMANDS};
const char *arg;
char *errctx;
unsigned num_inputs = lls_num_inputs(lpr);
scd->sender_num = -1;
ret = lls(lls_check_arg_count(lpr, 2, INT_MAX, &errctx));
if (ret < 0) {
send_errctx(cc, errctx);
return ret;
}
arg = lls_input(0, lpr);
FOR_EACH_SENDER(i)
if (strcmp(senders[i]->name, arg) == 0)
break;
if (!senders[i])
return -E_COMMAND_SYNTAX;
scd->sender_num = i;
arg = lls_input(1, lpr);
for (i = 0; i < NUM_SENDER_CMDS; i++)
if (!strcmp(subcmds[i], arg))
break;
if (i == NUM_SENDER_CMDS)
return -E_COMMAND_SYNTAX;
scd->cmd_num = i;
if (!senders[scd->sender_num]->client_cmds[scd->cmd_num])
return -E_SENDER_CMD;
switch (scd->cmd_num) {
case SENDER_on:
case SENDER_off:
if (num_inputs != 2)
return -E_COMMAND_SYNTAX;
break;
case SENDER_deny:
case SENDER_allow:
if (num_inputs != 3 || parse_cidr(lls_input(2, lpr), scd->host,
sizeof(scd->host), &scd->netmask) == NULL)
return -E_COMMAND_SYNTAX;
break;
case SENDER_add:
case SENDER_delete:
if (num_inputs != 3)
return -E_COMMAND_SYNTAX;
return parse_fec_url(lls_input(2, lpr), scd);
default:
return -E_COMMAND_SYNTAX;
}
return 1;
}
/**
* Receive a sideband packet from a blocking file descriptor.
*
* \param scc fd and crypto keys.
* \param expected_band The expected band designator.
* \param max_size Passed to \ref sb_new_recv().
* \param result Body of the sideband packet is returned here.
*
* If \a expected_band is not \p SBD_ANY, the band designator of the received
* sideband packet is compared to \a expected_band and a mismatch is considered
* an error.
*
* \return Standard.
*/
int recv_sb(struct stream_cipher_context *scc,
enum sb_designator expected_band,
size_t max_size, struct iovec *result)
{
int ret;
struct sb_context *sbc;
struct iovec iov;
struct sb_buffer sbb;
sb_transformation trafo;
trafo = expected_band != SBD_ANY && expected_band < SBD_PROCEED?
NULL : sc_trafo;
sbc = sb_new_recv(max_size, trafo, scc->recv);
for (;;) {
sb_get_recv_buffer(sbc, &iov);
ret = recv_bin_buffer(scc->fd, iov.iov_base, iov.iov_len);
if (ret == 0)
ret = -E_EOF;
if (ret < 0)
goto fail;
ret = sb_received(sbc, ret, &sbb);
if (ret < 0)
goto fail;
if (ret > 0)
break;
}
ret = -E_BAD_BAND;
if (expected_band != SBD_ANY && sbb.band != expected_band)
goto fail;
*result = sbb.iov;
return 1;
fail:
sb_free(sbc);
return ret;
}
/** \cond doxygen_ignore */
static int com_sender(struct command_context *cc, struct lls_parse_result *lpr)
{
int i, ret = 0;
char *msg = NULL;
struct sender_command_data scd;
if (lls_num_inputs(lpr) == 0) {
FOR_EACH_SENDER(i) {
char *tmp;
ret = xasprintf(&tmp, "%s%s\n", msg? msg : "",
senders[i]->name);
free(msg);
msg = tmp;
}
return send_sb(&cc->scc, msg, ret, SBD_OUTPUT, false);
}
ret = check_sender_args(cc, lpr, &scd);
if (ret < 0) {
if (scd.sender_num < 0)
return ret;
if (strcmp(lls_input(1, lpr), "status") == 0)
msg = senders[scd.sender_num]->status();
else
msg = senders[scd.sender_num]->help();
return send_sb(&cc->scc, msg, strlen(msg), SBD_OUTPUT, false);
}
switch (scd.cmd_num) {
case SENDER_add:
case SENDER_delete:
assert(senders[scd.sender_num]->resolve_target);
ret = senders[scd.sender_num]->resolve_target(lls_input(2, lpr),
&scd);
if (ret < 0)
return ret;
}
for (i = 0; i < 10; i++) {
mutex_lock(mmd_mutex);
if (mmd->sender_cmd_data.cmd_num >= 0) {
/* another sender command is active, retry in 100ms */
struct timespec ts = {.tv_nsec = 100 * 1000 * 1000};
mutex_unlock(mmd_mutex);
nanosleep(&ts, NULL);
continue;
}
mmd->sender_cmd_data = scd;
mutex_unlock(mmd_mutex);
break;
}
return (i < 10)? 1 : -E_LOCK;
}
EXPORT_SERVER_CMD_HANDLER(sender);
static int com_si(struct command_context *cc,
__a_unused struct lls_parse_result *lpr)
{
char *msg, *ut;
int ret;
ut = daemon_get_uptime_str(now);
mutex_lock(mmd_mutex);
ret = xasprintf(&msg,
"up: %s\nplayed: %u\n"
"server_pid: %d\n"
"afs_pid: %d\n"
"connections (active/accepted/total): %u/%u/%u\n"
"supported audio formats: %s\n",
ut, mmd->num_played,
(int)getppid(),
(int)afs_pid,
mmd->active_connections,
mmd->num_commands,
mmd->num_connects,
AUDIO_FORMAT_HANDLERS
);
mutex_unlock(mmd_mutex);
free(ut);
return send_sb(&cc->scc, msg, ret, SBD_OUTPUT, false);
}
EXPORT_SERVER_CMD_HANDLER(si);
static int com_version(struct command_context *cc, struct lls_parse_result *lpr)
{
char *msg;
size_t len;
if (SERVER_CMD_OPT_GIVEN(VERSION, VERBOSE, lpr))
len = xasprintf(&msg, "%s", version_text("server"));
else
len = xasprintf(&msg, "%s\n", version_single_line("server"));
return send_sb(&cc->scc, msg, len, SBD_OUTPUT, false);
}
EXPORT_SERVER_CMD_HANDLER(version);
/* These status items are cleared if no audio file is currently open. */
#define EMPTY_STATUS_ITEMS \
ITEM(path) \
ITEM(directory) \
ITEM(basename) \
ITEM(score) \
ITEM(attributes_bitmap) \
ITEM(attributes_txt) \
ITEM(hash) \
ITEM(image_id) \
ITEM(image_name) \
ITEM(lyrics_id) \
ITEM(lyrics_name) \
ITEM(bitrate) \
ITEM(format) \
ITEM(frequency) \
ITEM(channels) \
ITEM(duration) \
ITEM(seconds_total) \
ITEM(num_played) \
ITEM(last_played) \
ITEM(techinfo) \
ITEM(artist) \
ITEM(title) \
ITEM(year) \
ITEM(album) \
ITEM(comment) \
ITEM(mtime) \
ITEM(file_size) \
ITEM(chunk_time) \
ITEM(num_chunks) \
ITEM(amplification) \
ITEM(play_time) \
/*
* Create a set of audio-file related status items with empty values. These are
* written to stat clients when no audio file is open.
*/
static unsigned empty_status_items(bool parser_friendly, char **result)
{
char *esi;
unsigned len;
if (parser_friendly)
len = xasprintf(&esi,
#define ITEM(x) "0004 %02x:\n"
EMPTY_STATUS_ITEMS
#undef ITEM
#define ITEM(x) , (unsigned) SI_ ## x
EMPTY_STATUS_ITEMS
#undef ITEM
);
else
len = xasprintf(&esi,
#define ITEM(x) "%s:\n"
EMPTY_STATUS_ITEMS
#undef ITEM
#define ITEM(x) ,status_item_list[SI_ ## x]
EMPTY_STATUS_ITEMS
#undef ITEM
);
*result = esi;
return len;
}
#undef EMPTY_STATUS_ITEMS
static int com_stat(struct command_context *cc, struct lls_parse_result *lpr)
{
int ret;
struct misc_meta_data tmp, *nmmd = &tmp;
char *s;
bool parser_friendly = SERVER_CMD_OPT_GIVEN(STAT, PARSER_FRIENDLY,
lpr) > 0;
uint32_t num = SERVER_CMD_UINT32_VAL(STAT, NUM, lpr);
const struct timespec ts = {.tv_sec = 50, .tv_nsec = 0};
para_sigaction(SIGINT, SIG_IGN);
para_sigaction(SIGUSR1, command_handler_sighandler);
para_sigaction(SIGTERM, command_handler_sighandler);
/*
* Simply checking subcmd_should_die is racy because a signal may
* arrive after the check but before the subsequent call to sleep(3).
* If this happens, sleep(3) would not be interrupted by the signal.
* To avoid this we block SIGTERM here and allow it to arrive only
* while we sleep.
*/
para_block_signal(SIGTERM);
para_block_signal(SIGUSR1);
for (;;) {
sigset_t set;
/*
* Copy the mmd structure to minimize the time we hold the mmd
* lock.
*/
mutex_lock(mmd_mutex);
*nmmd = *mmd;
mutex_unlock(mmd_mutex);
ret = get_status(nmmd, parser_friendly, &s);
ret = send_sb(&cc->scc, s, ret, SBD_OUTPUT, false);
if (ret < 0)
goto out;
if (nmmd->vss_status_flags & VSS_NEXT) {
char *esi;
ret = empty_status_items(parser_friendly, &esi);
ret = send_sb(&cc->scc, esi, ret, SBD_OUTPUT, false);
if (ret < 0)
goto out;
} else
send_afs_status(cc, parser_friendly);
ret = 1;
if (num > 0 && !--num)
goto out;
sigemptyset(&set); /* empty set means: unblock all signals */
/*
* pselect(2) allows to atomically unblock signals, then go to
* sleep. Calling sigprocmask(2) followed by sleep(3) would
* open a race window similar to the one described above.
*/
pselect(1, NULL, NULL, NULL, &ts, &set);
if (subcmd_should_die) {
PARA_EMERG_LOG("terminating on SIGTERM\n");
goto out;
}
ret = -E_SERVER_CRASH;
if (getppid() == 1)
goto out;
}
out:
return ret;
}
EXPORT_SERVER_CMD_HANDLER(stat);
static const char *aux_info_cb(unsigned cmd_num, bool verbose)
{
static char result[80];
unsigned perms = server_command_perms[cmd_num];
if (verbose) {
/* permissions: VSS_READ | VSS_WRITE */
sprintf(result, "permissions: %s",
server_command_perms_txt[cmd_num]);
} else {
result[0] = perms & AFS_READ? 'a' : '-';
result[1] = perms & AFS_WRITE? 'A' : '-';
result[2] = perms & VSS_READ? 'v' : '-';
result[3] = perms & VSS_WRITE? 'V' : '-';
result[4] = '\0';
}
return result;
}
static int com_help(struct command_context *cc, struct lls_parse_result *lpr)
{
char *buf;
unsigned n;
bool long_help = SERVER_CMD_OPT_GIVEN(HELP, LONG, lpr);
int ret, ret2;
uint8_t band;
ret = lsu_com_help(long_help, lpr, server_cmd_suite, aux_info_cb,
&buf, &n);
band = ret < 0? SBD_ERROR_LOG : SBD_OUTPUT;
ret2 = send_sb(&cc->scc, buf, n, band, false);
return ret >= 0? ret2 : ret;
}
EXPORT_SERVER_CMD_HANDLER(help);
static int com_hup(__a_unused struct command_context *cc,
__a_unused struct lls_parse_result *lpr)
{
kill(getppid(), SIGHUP);
return 1;
}
EXPORT_SERVER_CMD_HANDLER(hup);
static int com_ll(struct command_context *cc, struct lls_parse_result *lpr)
{
unsigned ll, perms;
char *errctx;
const char *sev[] = {SEVERITIES}, *arg;
int ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
if (ret < 0) {
send_errctx(cc, errctx);
return ret;
}
if (lls_num_inputs(lpr) == 0) { /* reporting is an unprivileged op. */
const char *severity;
mutex_lock(mmd_mutex);
severity = sev[mmd->loglevel];
mutex_unlock(mmd_mutex);
return send_sb_va(&cc->scc, SBD_OUTPUT, "%s\n", severity);
}
/*
* Changing the loglevel changes the state of both the afs and the vss,
* so we require both AFS_WRITE and VSS_WRITE.
*/
perms = AFS_WRITE | VSS_WRITE;
if ((cc->u->perms & perms) != perms)
return -ERRNO_TO_PARA_ERROR(EPERM);
arg = lls_input(0, lpr);
for (ll = 0; ll < NUM_LOGLEVELS; ll++)
if (!strcmp(arg, sev[ll]))
break;
if (ll >= NUM_LOGLEVELS)
return -ERRNO_TO_PARA_ERROR(EINVAL);
PARA_INFO_LOG("new log level: %s\n", sev[ll]);
/* Ask the server and afs processes to adjust their log level. */
mutex_lock(mmd_mutex);
mmd->loglevel = ll;
mutex_unlock(mmd_mutex);
return 1;
}
EXPORT_SERVER_CMD_HANDLER(ll);
static int com_term(__a_unused struct command_context *cc,
__a_unused struct lls_parse_result *lpr)
{
/*
* The server catches SIGTERM and propagates this signal to all its
* children. We are about to exit anyway, but we'd leak tons of memory
* if being terminated by the signal. So we ignore the signal here and
* terminate via the normal exit path, deallocating all memory.
*/
para_sigaction(SIGTERM, SIG_IGN);
kill(getppid(), SIGTERM);
return 1;
}
EXPORT_SERVER_CMD_HANDLER(term);
static int com_play(__a_unused struct command_context *cc,
struct lls_parse_result *lpr)
{
mutex_lock(mmd_mutex);
if (SERVER_CMD_OPT_GIVEN(PLAY, NEXT, lpr))
mmd->new_vss_status_flags |= VSS_NEXT;
mmd->new_vss_status_flags |= VSS_PLAYING;
mmd->new_vss_status_flags &= ~VSS_NOMORE;
mutex_unlock(mmd_mutex);
return 1;
}
EXPORT_SERVER_CMD_HANDLER(play);
static int com_stop(__a_unused struct command_context *cc,
__a_unused struct lls_parse_result *lpr)
{
mutex_lock(mmd_mutex);
mmd->new_vss_status_flags &= ~VSS_PLAYING;
mmd->new_vss_status_flags &= ~VSS_REPOS;
mmd->new_vss_status_flags |= VSS_NEXT;
mutex_unlock(mmd_mutex);
return 1;
}
EXPORT_SERVER_CMD_HANDLER(stop);
static int com_pause(__a_unused struct command_context *cc,
__a_unused struct lls_parse_result *lpr)
{
mutex_lock(mmd_mutex);
if (!vss_paused() && !vss_stopped()) {
mmd->events++;
mmd->new_vss_status_flags &= ~VSS_PLAYING;
mmd->new_vss_status_flags &= ~VSS_NEXT;
}
mutex_unlock(mmd_mutex);
return 1;
}
EXPORT_SERVER_CMD_HANDLER(pause);
static int com_next(__a_unused struct command_context *cc,
__a_unused struct lls_parse_result *lpr)
{
mutex_lock(mmd_mutex);
mmd->events++;
mmd->new_vss_status_flags |= VSS_NEXT;
mutex_unlock(mmd_mutex);
return 1;
}
EXPORT_SERVER_CMD_HANDLER(next);
static int com_nomore(__a_unused struct command_context *cc,
__a_unused struct lls_parse_result *lpr)
{
mutex_lock(mmd_mutex);
if (vss_playing() || vss_paused())
mmd->new_vss_status_flags |= VSS_NOMORE;
mutex_unlock(mmd_mutex);
return 1;
}
EXPORT_SERVER_CMD_HANDLER(nomore);
static int com_ff(struct command_context *cc, struct lls_parse_result *lpr)
{
long promille;
int i, ret;
char *errctx;
ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
if (ret < 0) {
send_errctx(cc, errctx);
return ret;
}
ret = para_atoi32(lls_input(0, lpr), &i);
if (ret < 0)
return ret;
mutex_lock(mmd_mutex);
ret = -E_NO_AUDIO_FILE;
if (!mmd->afd.afhi.chunks_total || !mmd->afd.afhi.seconds_total)
goto out;
ret = 1;
promille = (1000 * mmd->current_chunk) / mmd->afd.afhi.chunks_total;
/*
* We need this cast because without it the expression on the right
* hand side is of unsigned type.
*/
promille += 1000 * i / (int)mmd->afd.afhi.seconds_total;
if (promille < 0)
promille = 0;
if (promille > 1000) {
mmd->new_vss_status_flags |= VSS_NEXT;
goto out;
}
mmd->repos_request = (mmd->afd.afhi.chunks_total * promille) / 1000;
mmd->new_vss_status_flags |= VSS_REPOS;
mmd->new_vss_status_flags &= ~VSS_NEXT;
mmd->events++;
out:
mutex_unlock(mmd_mutex);
return ret;
}
EXPORT_SERVER_CMD_HANDLER(ff);
static int com_jmp(struct command_context *cc, struct lls_parse_result *lpr)
{
int i, ret;
char *errctx;
ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
if (ret < 0) {
send_errctx(cc, errctx);
return ret;
}
if (sscanf(lls_input(0, lpr), "%d", &i) <= 0)
return -ERRNO_TO_PARA_ERROR(EINVAL);
if (i < 0 || i > 100)
return -ERRNO_TO_PARA_ERROR(EINVAL);
mutex_lock(mmd_mutex);
ret = -E_NO_AUDIO_FILE;
if (!mmd->afd.afhi.chunks_total)
goto out;
PARA_INFO_LOG("jumping to %d%%\n", i);
mmd->repos_request = (mmd->afd.afhi.chunks_total * i + 50) / 100;
mmd->new_vss_status_flags |= VSS_REPOS;
mmd->new_vss_status_flags &= ~VSS_NEXT;
ret = 1;
mmd->events++;
out:
mutex_unlock(mmd_mutex);
return ret;
}
EXPORT_SERVER_CMD_HANDLER(jmp);
/** \endcond */
static void reset_signals(void)
{
para_sigaction(SIGCHLD, SIG_IGN);
para_sigaction(SIGINT, SIG_DFL);
para_sigaction(SIGTERM, SIG_DFL);
para_sigaction(SIGHUP, SIG_DFL);
}
static int parse_auth_request(char *buf, int len, const struct user **u)
{
int ret;
char *p, *username, **features = NULL;
size_t auth_rq_len = strlen(AUTH_REQUEST_MSG);
*u = NULL;
if (len < auth_rq_len + 2)
return -E_AUTH_REQUEST;
if (strncmp(buf, AUTH_REQUEST_MSG, auth_rq_len) != 0)
return -E_AUTH_REQUEST;
username = buf + auth_rq_len;
p = strchr(username, ' ');
if (p) {
int i;
if (p == username)
return -E_AUTH_REQUEST;
*p = '\0';
p++;
create_argv(p, ",", &features);
for (i = 0; features[i]; i++) {
/*
* sha256 is used unconditionally, but we need to
* accept the feature request until 0.9.0.
*/
if (strcmp(features[i], "sha256")) {
ret = -E_BAD_FEATURE;
goto out;
}
}
}
PARA_DEBUG_LOG("received auth request for user %s\n", username);
*u = user_list_lookup(username);
ret = 1;
out:
free_argv(features);
return ret;
}
static int run_command(struct command_context *cc, struct iovec *iov)
{
int ret, i, argc;
char *p, *end, **argv;
const struct lls_command *lcmd = NULL;
unsigned perms;
struct lls_parse_result *lpr;
char *errctx;
if (iov->iov_base == NULL || iov->iov_len == 0)
return -ERRNO_TO_PARA_ERROR(EINVAL);
p = iov->iov_base;
p[iov->iov_len - 1] = '\0'; /* just to be sure */
ret = lls(lls_lookup_subcmd(p, server_cmd_suite, &errctx));
if (ret < 0) {
send_errctx(cc, errctx);
return ret;
}
perms = server_command_perms[ret];
if ((perms & cc->u->perms) != perms)
return -ERRNO_TO_PARA_ERROR(EPERM);
lcmd = lls_cmd(ret, server_cmd_suite);
end = iov->iov_base + iov->iov_len;
for (i = 0; p < end; i++)
p += strlen(p) + 1;
argc = i;
argv = arr_alloc(argc + 1, sizeof(char *));
for (i = 0, p = iov->iov_base; p < end; i++) {
argv[i] = para_strdup(p);
p += strlen(p) + 1;
}
argv[argc] = NULL;
PARA_NOTICE_LOG("calling com_%s() for user %s\n",
lls_command_name(lcmd), cc->u->name);
ret = lls(lls_parse(argc, argv, lcmd, &lpr, &errctx));
if (ret >= 0) {
const struct server_cmd_user_data *ud = lls_user_data(lcmd);
ret = ud->handler(cc, lpr);
lls_free_parse_result(lpr, lcmd);
} else
send_errctx(cc, errctx);
free_argv(argv);
mutex_lock(mmd_mutex);
mmd->num_commands++;
if (ret >= 0 && (perms & AFS_WRITE))
mmd->events++;
mutex_unlock(mmd_mutex);
return ret;
}
/**
* Perform user authentication and execute a command.
*
* \param fd The file descriptor to send output to.
* \param afs_fd Permanent server-afs command socket, needed for afs callbacks.
*
* When the server process accepts an incoming tcp connection on the TCP command
* port port, it forks and the resulting child calls this function.
*
* An RSA-based challenge/response is used to authenticate the peer. If the
* authentication succeeds, a random session key is generated and sent back to
* the peer, encrypted with its RSA public key. From this point on, all
* transfers are encrypted with this session key using a stream cipher.
*
* Next it is checked if the peer supplied a valid server command or a command
* for the audio file selector. If yes, and if the user has sufficient
* permissions to execute this command, the function calls the corresponding
* command handler which performs argument checking and further processing.
*
* To cope with DOS attacks, a timer is set up right after the fork. If the
* connection was still not authenticated when the timeout expires, the child
* process is terminated.
*
* \return Standard.
*
* \sa alarm(2), \ref openssl.c, \ref crypt.h.
*/
int handle_connect(int fd, int afs_fd)
{
int ret;
unsigned char rand_buf[APC_CHALLENGE_SIZE + 2 * SESSION_KEY_LEN];
unsigned char challenge_hash[HASH_SIZE];
char *command = NULL, *buf = NULL, hsbuf[HANDSHAKE_BUFSIZE];
unsigned char *crypt_buf;
size_t numbytes;
struct command_context cc_struct = {.afs_fd = afs_fd}, *cc = &cc_struct;
struct iovec iov;
alarm(10);
cc->scc.fd = fd;
reset_signals();
/* we need a blocking fd here as recv() might return EAGAIN otherwise. */
ret = mark_fd_blocking(fd);
if (ret < 0)
goto net_err;
/* send Welcome message */
ret = write_va_buffer(fd, "This is para_server, version %s.\n"
"Features: \n", /* currently none */
paraslash_version()
);
if (ret < 0)
goto net_err;
/* recv auth request line */
ret = recv_buffer(fd, hsbuf, HANDSHAKE_BUFSIZE);
if (ret < 0)
goto net_err;
ret = parse_auth_request(hsbuf, ret, &cc->u);
if (ret < 0)
goto net_err;
if (cc->u) {
get_random_bytes_or_die(rand_buf, sizeof(rand_buf));
ret = apc_pub_encrypt(cc->u->pubkey, rand_buf, sizeof(rand_buf),
&crypt_buf);
if (ret < 0)
goto net_err;
numbytes = ret;
} else {
/*
* We don't want to reveal our user names, so we send a
* challenge to the client even if the user does not exist, and
* fail the authentication later.
*/
numbytes = 256;
crypt_buf = alloc(numbytes);
get_random_bytes_or_die(crypt_buf, numbytes);
}
PARA_DEBUG_LOG("sending %d byte challenge + session key (%zu bytes)\n",
APC_CHALLENGE_SIZE, numbytes);
ret = send_sb(&cc->scc, crypt_buf, numbytes, SBD_CHALLENGE, false);
if (ret < 0)
goto net_err;
ret = recv_sb(&cc->scc, SBD_CHALLENGE_RESPONSE,
HANDSHAKE_BUFSIZE, &iov);
if (ret < 0)
goto net_err;
buf = iov.iov_base;
numbytes = iov.iov_len;
PARA_DEBUG_LOG("received %zu bytes challenge response\n", numbytes);
ret = -E_BAD_USER;
if (!cc->u)
goto net_err;
/*
* The correct response is the hash of the first APC_CHALLENGE_SIZE bytes
* of the random data.
*/
ret = -E_BAD_AUTH;
if (numbytes != HASH_SIZE)
goto net_err;
hash_function((char *)rand_buf, APC_CHALLENGE_SIZE, challenge_hash);
if (memcmp(challenge_hash, buf, HASH_SIZE))
goto net_err;
/* auth successful */
alarm(0);
PARA_INFO_LOG("good auth for %s\n", cc->u->name);
/* init stream cipher keys with the second part of the random buffer */
cc->scc.recv = sc_new(rand_buf + APC_CHALLENGE_SIZE, SESSION_KEY_LEN);
cc->scc.send = sc_new(rand_buf + APC_CHALLENGE_SIZE + SESSION_KEY_LEN,
SESSION_KEY_LEN);
ret = send_sb(&cc->scc, NULL, 0, SBD_PROCEED, false);
if (ret < 0)
goto net_err;
ret = recv_sb(&cc->scc, SBD_COMMAND, MAX_COMMAND_LEN, &iov);
if (ret < 0)
goto net_err;
ret = run_command(cc, &iov);
free(iov.iov_base);
if (ret < 0)
goto err_out;
if (ret >= 0)
goto out;
err_out:
if (send_strerror(cc, -ret) >= 0)
send_sb(&cc->scc, NULL, 0, SBD_EXIT__FAILURE, true);
net_err:
PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
out:
free(buf);
free(command);
mutex_lock(mmd_mutex);
mmd->active_connections--;
mutex_unlock(mmd_mutex);
if (ret >= 0) {
ret = send_sb(&cc->scc, NULL, 0, SBD_EXIT__SUCCESS, true);
if (ret < 0)
PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
}
sc_free(cc->scc.recv);
sc_free(cc->scc.send);
return ret;
}
|