-
Notifications
You must be signed in to change notification settings - Fork 38
/
main.c
1267 lines (1072 loc) · 31.2 KB
/
main.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
/*
* MOC - music on console
* Copyright (C) 2004-2005 Damian Pietras <daper@daper.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/utsname.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <time.h>
#include <locale.h>
#include <assert.h>
#include <popt.h>
#include "common.h"
#include "server.h"
#include "interface.h"
#include "options.h"
#include "protocol.h"
#include "log.h"
#include "decoder.h"
#include "lists.h"
#include "files.h"
#include "rcc.h"
static int mocp_argc;
static const char **mocp_argv;
static int popt_next_val = 1;
static char *render_popt_command_line ();
/* List of MOC-specific environment variables. */
static struct {
const char *name;
const char *desc;
} environment_variables[] = {
{"MOCP_OPTS", "Additional command line options"},
{"MOCP_POPTRC", "List of POPT configuration files"}
};
struct parameters
{
char *config_file;
int no_config_file;
int debug;
int only_server;
int foreground;
int append;
int enqueue;
int clear;
int play;
int allow_iface;
int stop;
int exit;
int pause;
int unpause;
int next;
int previous;
int get_file_info;
int toggle_pause;
int playit;
int seek_by;
char jump_type;
int jump_to;
char *formatted_info_param;
int get_formatted_info;
char *adj_volume;
char *toggle;
char *on;
char *off;
};
/* Connect to the server, return fd of the socket or -1 on error. */
static int server_connect ()
{
struct sockaddr_un sock_name;
int sock;
/* Create a socket.
* For reasons why AF_UNIX is the correct constant to use in both
* cases, see the commentary the SVN log for commit r2833. */
if ((sock = socket (AF_UNIX, SOCK_STREAM, 0)) == -1)
return -1;
sock_name.sun_family = AF_UNIX;
strcpy (sock_name.sun_path, socket_name());
if (connect(sock, (struct sockaddr *)&sock_name,
SUN_LEN(&sock_name)) == -1) {
close (sock);
return -1;
}
return sock;
}
/* Ping the server.
* Return 1 if the server responds with EV_PONG, otherwise 0. */
static int ping_server (int sock)
{
int event;
send_int(sock, CMD_PING); /* ignore errors - the server could have
already closed the connection and sent
EV_BUSY */
if (!get_int(sock, &event))
fatal ("Error when receiving pong response!");
return event == EV_PONG ? 1 : 0;
}
/* Check if a directory ./.moc exists and create if needed. */
static void check_moc_dir ()
{
char *dir_name = create_file_name ("");
struct stat file_stat;
/* strip trailing slash */
dir_name[strlen(dir_name)-1] = 0;
if (stat (dir_name, &file_stat) == -1) {
if (errno != ENOENT)
fatal ("Error trying to check for "CONFIG_DIR" directory: %s",
xstrerror (errno));
if (mkdir (dir_name, 0700) == -1)
fatal ("Can't create directory %s: %s",
dir_name, xstrerror (errno));
}
else {
if (!S_ISDIR(file_stat.st_mode) || access (dir_name, W_OK))
fatal ("%s is not a writable directory!", dir_name);
}
}
/* Run client and the server if needed. */
static void start_moc (const struct parameters *params, lists_t_strs *args)
{
int server_sock;
if (params->foreground) {
set_me_server ();
server_init (params->debug, params->foreground);
server_loop ();
return;
}
server_sock = server_connect ();
if (server_sock != -1 && params->only_server)
fatal ("Server is already running!");
if (server_sock == -1) {
int i = 0;
int notify_pipe[2];
ssize_t rc;
printf ("Running the server...\n");
/* To notify the client that the server socket is ready */
if (pipe(notify_pipe))
fatal ("pipe() failed: %s", xstrerror (errno));
switch (fork()) {
case 0: /* child - start server */
set_me_server ();
server_init (params->debug, params->foreground);
rc = write (notify_pipe[1], &i, sizeof(i));
if (rc < 0)
fatal ("write() to notify pipe failed: %s", xstrerror (errno));
close (notify_pipe[0]);
close (notify_pipe[1]);
server_loop ();
options_free ();
decoder_cleanup ();
io_cleanup ();
files_cleanup ();
rcc_cleanup ();
common_cleanup ();
exit (EXIT_SUCCESS);
case -1:
fatal ("fork() failed: %s", xstrerror (errno));
default:
close (notify_pipe[1]);
if (read(notify_pipe[0], &i, sizeof(i)) != sizeof(i))
fatal ("Server exited!");
close (notify_pipe[0]);
server_sock = server_connect ();
if (server_sock == -1) {
perror ("server_connect()");
fatal ("Can't connect to the server!");
}
}
}
if (params->only_server)
send_int (server_sock, CMD_DISCONNECT);
else {
xsignal (SIGPIPE, SIG_IGN);
if (!ping_server (server_sock))
fatal ("Can't connect to the server!");
init_interface (server_sock, params->debug, args);
interface_loop ();
interface_end ();
}
close (server_sock);
}
/* Send commands requested in params to the server. */
static void server_command (struct parameters *params, lists_t_strs *args)
{
int sock;
if ((sock = server_connect()) == -1)
fatal ("The server is not running!");
xsignal (SIGPIPE, SIG_IGN);
if (!ping_server (sock))
fatal ("Can't connect to the server!");
if (params->playit)
interface_cmdline_playit (sock, args);
if (params->clear)
interface_cmdline_clear_plist (sock);
if (params->append)
interface_cmdline_append (sock, args);
if (params->enqueue)
interface_cmdline_enqueue (sock, args);
if (params->play)
interface_cmdline_play_first (sock);
if (params->get_file_info)
interface_cmdline_file_info (sock);
if (params->seek_by)
interface_cmdline_seek_by (sock, params->seek_by);
if (params->jump_type=='%')
interface_cmdline_jump_to_percent (sock,params->jump_to);
if (params->jump_type=='s')
interface_cmdline_jump_to (sock,params->jump_to);
if (params->get_formatted_info)
interface_cmdline_formatted_info (sock, params->formatted_info_param);
if (params->adj_volume)
interface_cmdline_adj_volume (sock, params->adj_volume);
if (params->toggle)
interface_cmdline_set (sock, params->toggle, 2);
if (params->on)
interface_cmdline_set (sock, params->on, 1);
if (params->off)
interface_cmdline_set (sock, params->off, 0);
if (params->exit) {
if (!send_int(sock, CMD_QUIT))
fatal ("Can't send command!");
}
else if (params->stop) {
if (!send_int(sock, CMD_STOP) || !send_int(sock, CMD_DISCONNECT))
fatal ("Can't send commands!");
}
else if (params->pause) {
if (!send_int(sock, CMD_PAUSE) || !send_int(sock, CMD_DISCONNECT))
fatal ("Can't send commands!");
}
else if (params->next) {
if (!send_int(sock, CMD_NEXT) || !send_int(sock, CMD_DISCONNECT))
fatal ("Can't send commands!");
}
else if (params->previous) {
if (!send_int(sock, CMD_PREV) || !send_int(sock, CMD_DISCONNECT))
fatal ("Can't send commands!");
}
else if (params->unpause) {
if (!send_int(sock, CMD_UNPAUSE) || !send_int(sock, CMD_DISCONNECT))
fatal ("Can't send commands!");
}
else if (params->toggle_pause) {
int state, ev, cmd = -1;
if (!send_int(sock, CMD_GET_STATE))
fatal ("Can't send commands!");
if (!get_int(sock, &ev) || ev != EV_DATA || !get_int(sock, &state))
fatal ("Can't get data from the server!");
if (state == STATE_PAUSE)
cmd = CMD_UNPAUSE;
else if (state == STATE_PLAY)
cmd = CMD_PAUSE;
if (cmd != -1 && !send_int(sock, cmd))
fatal ("Can't send commands!");
if (!send_int(sock, CMD_DISCONNECT))
fatal ("Can't send commands!");
}
close (sock);
}
static void show_version ()
{
int rc;
struct utsname uts;
putchar ('\n');
printf (" This is : %s\n", PACKAGE_NAME);
printf (" Version : %s\n", PACKAGE_VERSION);
#ifdef PACKAGE_REVISION
printf (" Revision : %s\n", PACKAGE_REVISION);
#endif
/* Show build time */
#ifdef __DATE__
printf (" Built : %s", __DATE__);
# ifdef __TIME__
printf (" %s", __TIME__);
# endif
putchar ('\n');
#endif
/* Show compiled-in components */
printf (" Compiled with :");
#ifdef HAVE_OSS
printf (" OSS");
#endif
#ifdef HAVE_SNDIO
printf (" SNDIO");
#endif
#ifdef HAVE_ALSA
printf (" ALSA");
#endif
#ifdef HAVE_JACK
printf (" JACK");
#endif
#ifndef NDEBUG
printf (" DEBUG");
#endif
#ifdef HAVE_CURL
printf (" Network streams");
#endif
#ifdef HAVE_SAMPLERATE
printf (" resample");
#endif
putchar ('\n');
rc = uname (&uts);
if (rc == 0)
printf (" Running on : %s %s %s\n", uts.sysname, uts.release,
uts.machine);
printf (" Author : Damian Pietras\n");
printf (" Homepage : %s\n", PACKAGE_URL);
printf (" E-Mail : %s\n", PACKAGE_BUGREPORT);
printf (" Copyright : (C) 2003-2016 Damian Pietras and others\n");
printf (" License : GNU General Public License, version 2 or later\n");
putchar ('\n');
}
/* Show program banner. */
static void show_banner ()
{
printf ("%s (version %s", PACKAGE_NAME, PACKAGE_VERSION);
#ifdef PACKAGE_REVISION
printf (", revision %s", PACKAGE_REVISION);
#endif
printf (")\n");
}
static const char mocp_summary[] = "[OPTIONS] [FILE|DIR ...]";
/* Show program usage. */
static void show_usage (poptContext ctx)
{
show_banner ();
poptSetOtherOptionHelp (ctx, mocp_summary);
poptPrintUsage (ctx, stdout, 0);
}
/* Show program help. */
static void show_help (poptContext ctx)
{
size_t ix;
show_banner ();
poptSetOtherOptionHelp (ctx, mocp_summary);
poptPrintHelp (ctx, stdout, 0);
printf ("\nEnvironment variables:\n\n");
for (ix = 0; ix < ARRAY_SIZE(environment_variables); ix += 1)
printf (" %-34s%s\n", environment_variables[ix].name,
environment_variables[ix].desc);
printf ("\n");
}
/* Show POPT-interpreted command line arguments. */
static void show_args ()
{
if (mocp_argc > 0) {
char *str;
str = getenv ("MOCP_POPTRC");
if (str)
printf ("MOCP_POPTRC='%s' ", str);
str = getenv ("MOCP_OPTS");
if (str)
printf ("MOCP_OPTS='%s' ", str);
str = render_popt_command_line ();
printf ("%s\n", str);
free (str);
}
}
/* Disambiguate the user's request. */
static void show_misc_cb (poptContext ctx,
enum poptCallbackReason unused1 ATTR_UNUSED,
const struct poptOption *opt,
const char *unused2 ATTR_UNUSED,
void *unused3 ATTR_UNUSED)
{
switch (opt->shortName) {
case 'V':
show_version ();
break;
case 'h':
show_help (ctx);
break;
case 0:
if (!strcmp (opt->longName, "echo-args"))
show_args ();
else
if (!strcmp (opt->longName, "usage"))
show_usage (ctx);
break;
}
exit (EXIT_SUCCESS);
}
enum {
CL_HANDLED = 0,
CL_NOIFACE,
CL_SDRIVER,
CL_MUSICDIR,
CL_THEME,
CL_SETOPTION,
CL_MOCDIR,
CL_SYNCPL,
CL_NOSYNC,
CL_ASCII,
CL_JUMP,
CL_GETINFO
};
static struct parameters params;
static struct poptOption general_opts[] = {
#ifndef NDEBUG
{"debug", 'D', POPT_ARG_NONE, ¶ms.debug, CL_HANDLED,
"Turn on logging to a file", NULL},
#endif
{"moc-dir", 'M', POPT_ARG_STRING, NULL, CL_MOCDIR,
"Use the specified MOC directory instead of the default", "DIR"},
{"music-dir", 'm', POPT_ARG_NONE, NULL, CL_MUSICDIR,
"Start in MusicDir", NULL},
{"config", 'C', POPT_ARG_STRING, ¶ms.config_file, CL_HANDLED,
"Use the specified config file instead of the default"
" (conflicts with '--no-config')", "FILE"},
{"no-config", 0, POPT_ARG_NONE, ¶ms.no_config_file, CL_HANDLED,
"Use program defaults rather than any config file"
" (conflicts with '--config')", NULL},
{"set-option", 'O', POPT_ARG_STRING, NULL, CL_SETOPTION,
"Override the configuration option NAME with VALUE", "'NAME=VALUE'"},
{"foreground", 'F', POPT_ARG_NONE, ¶ms.foreground, CL_HANDLED,
"Run the server in foreground (logging to stdout)", NULL},
{"server", 'S', POPT_ARG_NONE, ¶ms.only_server, CL_HANDLED,
"Only run the server", NULL},
{"sound-driver", 'R', POPT_ARG_STRING, NULL, CL_SDRIVER,
"Use the first valid sound driver", "DRIVERS"},
{"ascii", 'A', POPT_ARG_NONE, NULL, CL_ASCII,
"Use ASCII characters to draw lines", NULL},
{"theme", 'T', POPT_ARG_STRING, NULL, CL_THEME,
"Use the selected theme file (read from ~/.moc/themes if the path is not absolute)", "FILE"},
{"sync", 'y', POPT_ARG_NONE, NULL, CL_SYNCPL,
"Synchronize the playlist with other clients", NULL},
{"nosync", 'n', POPT_ARG_NONE, NULL, CL_NOSYNC,
"Don't synchronize the playlist with other clients", NULL},
POPT_TABLEEND
};
static struct poptOption server_opts[] = {
{"pause", 'P', POPT_ARG_NONE, ¶ms.pause, CL_NOIFACE,
"Pause", NULL},
{"unpause", 'U', POPT_ARG_NONE, ¶ms.unpause, CL_NOIFACE,
"Unpause", NULL},
{"toggle-pause", 'G', POPT_ARG_NONE, ¶ms.toggle_pause, CL_NOIFACE,
"Toggle between playing and paused", NULL},
{"stop", 's', POPT_ARG_NONE, ¶ms.stop, CL_NOIFACE,
"Stop playing", NULL},
{"next", 'f', POPT_ARG_NONE, ¶ms.next, CL_NOIFACE,
"Play the next song", NULL},
{"previous", 'r', POPT_ARG_NONE, ¶ms.previous, CL_NOIFACE,
"Play the previous song", NULL},
{"seek", 'k', POPT_ARG_INT, ¶ms.seek_by, CL_NOIFACE,
"Seek by N seconds (can be negative)", "N"},
{"jump", 'j', POPT_ARG_STRING, NULL, CL_JUMP,
"Jump to some position in the current track", "N{%,s}"},
{"volume", 'v', POPT_ARG_STRING, ¶ms.adj_volume, CL_NOIFACE,
"Adjust the PCM volume", "[+,-]LEVEL"},
{"exit", 'x', POPT_ARG_NONE, ¶ms.exit, CL_NOIFACE,
"Shutdown the server", NULL},
{"append", 'a', POPT_ARG_NONE, ¶ms.append, CL_NOIFACE,
"Append the files/directories/playlists passed in "
"the command line to playlist", NULL},
{"recursively", 'e', POPT_ARG_NONE, ¶ms.append, CL_NOIFACE,
"Alias for --append", NULL},
{"enqueue", 'q', POPT_ARG_NONE, ¶ms.enqueue, CL_NOIFACE,
"Add the files given on command line to the queue", NULL},
{"clear", 'c', POPT_ARG_NONE, ¶ms.clear, CL_NOIFACE,
"Clear the playlist", NULL},
{"play", 'p', POPT_ARG_NONE, ¶ms.play, CL_NOIFACE,
"Start playing from the first item on the playlist", NULL},
{"playit", 'l', POPT_ARG_NONE, ¶ms.playit, CL_NOIFACE,
"Play files given on command line without modifying the playlist", NULL},
{"toggle", 't', POPT_ARG_STRING, ¶ms.toggle, CL_NOIFACE,
"Toggle a control (shuffle, autonext, repeat)", "CONTROL"},
{"on", 'o', POPT_ARG_STRING, ¶ms.on, CL_NOIFACE,
"Turn on a control (shuffle, autonext, repeat)", "CONTROL"},
{"off", 'u', POPT_ARG_STRING, ¶ms.off, CL_NOIFACE,
"Turn off a control (shuffle, autonext, repeat)", "CONTROL"},
{"info", 'i', POPT_ARG_NONE, ¶ms.get_file_info, CL_NOIFACE,
"Print information about the file currently playing", NULL},
{"format", 'Q', POPT_ARG_STRING, ¶ms.formatted_info_param, CL_GETINFO,
"Print formatted information about the file currently playing", "FORMAT"},
POPT_TABLEEND
};
static struct poptOption misc_opts[] = {
{NULL, 0, POPT_ARG_CALLBACK,
(void *) (uintptr_t) show_misc_cb, 0, NULL, NULL},
{"version", 'V', POPT_ARG_NONE, NULL, 0,
"Print version information", NULL},
{"echo-args", 0, POPT_ARG_NONE, NULL, 0,
"Print POPT-interpreted arguments", NULL},
{"usage", 0, POPT_ARG_NONE, NULL, 0,
"Print brief usage", NULL},
{"help", 'h', POPT_ARG_NONE, NULL, 0,
"Print extended usage", NULL},
POPT_TABLEEND
};
static struct poptOption mocp_opts[] = {
{NULL, 0, POPT_ARG_INCLUDE_TABLE, general_opts, 0, "General options:", NULL},
{NULL, 0, POPT_ARG_INCLUDE_TABLE, server_opts, 0, "Server commands:", NULL},
{NULL, 0, POPT_ARG_INCLUDE_TABLE, misc_opts, 0, "Miscellaneous options:", NULL},
POPT_AUTOALIAS
POPT_TABLEEND
};
/* Read the POPT configuration files as given in MOCP_POPTRC. */
static void read_mocp_poptrc (poptContext ctx, const char *env_poptrc)
{
int ix, rc, count;
lists_t_strs *files;
files = lists_strs_new (4);
count = lists_strs_split (files, env_poptrc, ":");
for (ix = 0; ix < count; ix += 1) {
const char *fn;
fn = lists_strs_at (files, ix);
if (!strlen (fn))
continue;
if (!is_secure (fn))
fatal ("POPT config file is not secure: %s", fn);
rc = poptReadConfigFile (ctx, fn);
if (rc < 0)
fatal ("Error reading POPT config file '%s': %s",
fn, poptStrerror (rc));
}
lists_strs_free (files);
}
/* Check that the ~/.popt file is secure. */
static void check_popt_secure ()
{
int len;
const char *home, dot_popt[] = ".popt";
char *home_popt;
home = get_home ();
len = strlen (home) + strlen (dot_popt) + 2;
home_popt = xcalloc (len, sizeof (char));
snprintf (home_popt, len, "%s/%s", home, dot_popt);
if (!is_secure (home_popt))
fatal ("POPT config file is not secure: %s", home_popt);
free (home_popt);
}
/* Read the default POPT configuration file. */
static void read_default_poptrc (poptContext ctx)
{
int rc;
check_popt_secure ();
rc = poptReadDefaultConfig (ctx, 0);
if (rc == POPT_ERROR_ERRNO) {
int saved_errno = errno;
fprintf (stderr, "\n"
"WARNING: The following fatal error message may be bogus!\n"
" If you have an empty /etc/popt.d directory, try\n"
" adding an empty file to it. If that does not fix\n"
" the problem then you have a genuine error.\n");
errno = saved_errno;
}
if (rc != 0)
fatal ("Error reading default POPT config file: %s",
poptStrerror (rc));
}
/* Read the POPT configuration files(s). */
static void read_popt_config (poptContext ctx)
{
const char *env_poptrc;
env_poptrc = getenv ("MOCP_POPTRC");
if (env_poptrc)
read_mocp_poptrc (ctx, env_poptrc);
else
read_default_poptrc (ctx);
}
/* Prepend MOCP_OPTS to the command line. */
static void prepend_mocp_opts (poptContext ctx)
{
int rc;
const char *env_opts;
env_opts = getenv ("MOCP_OPTS");
if (env_opts && strlen (env_opts)) {
int env_argc;
const char **env_argv;
rc = poptParseArgvString (env_opts, &env_argc, &env_argv);
if (rc < 0)
fatal ("Error parsing MOCP_OPTS: %s", poptStrerror (rc));
rc = poptStuffArgs (ctx, env_argv);
if (rc < 0)
fatal ("Error prepending MOCP_OPTS: %s", poptStrerror (rc));
free (env_argv);
}
}
static const struct poptOption specials[] = {POPT_AUTOHELP
POPT_AUTOALIAS
POPT_TABLEEND};
/* Return true iff 'opt' is a POPT AutoHelp option. */
static inline bool is_autohelp (const struct poptOption *opt)
{
const struct poptOption *autohelp = &specials[0];
return opt->argInfo == autohelp->argInfo && opt->arg == autohelp->arg;
}
/* Return true iff 'opt' is a POPT AutoAlias option. */
static inline bool is_autoalias (const struct poptOption *opt)
{
const struct poptOption *autoalias = &specials[1];
return opt->argInfo == autoalias->argInfo && opt->arg == autoalias->arg;
}
/* Return true iff 'opt' is the POPT end-of-table marker. */
static inline bool is_tableend (const struct poptOption *opt)
{
const struct poptOption *tableend = &specials[2];
return opt->longName == tableend->longName &&
opt->shortName == tableend->shortName &&
opt->arg == tableend->arg;
}
/* Return a copy of the POPT option table structure which is suitable
* for rendering the POPT expansions of the command line. */
struct poptOption *clone_popt_options (struct poptOption *opts)
{
size_t tally, ix, iy = 0;
struct poptOption *result;
assert (opts);
for (tally = 1; !is_tableend (&opts[tally - 1]); tally += 1);
result = xcalloc (tally, sizeof (struct poptOption));
for (ix = 0; ix < tally; ix += 1) {
if (opts[ix].argInfo == POPT_ARG_CALLBACK)
continue;
if (is_autohelp (&opts[ix]))
continue;
if (is_autoalias (&opts[ix]))
continue;
memcpy (&result[iy], &opts[ix], sizeof (struct poptOption));
if (is_tableend (&opts[ix]))
continue;
if (opts[ix].argInfo == POPT_ARG_INCLUDE_TABLE) {
result[iy++].arg = clone_popt_options (opts[ix].arg);
continue;
}
switch (result[iy].argInfo) {
case POPT_ARG_STRING:
case POPT_ARG_INT:
case POPT_ARG_LONG:
case POPT_ARG_FLOAT:
case POPT_ARG_DOUBLE:
result[iy].argInfo = POPT_ARG_STRING;
break;
case POPT_ARG_VAL:
result[iy].argInfo = POPT_ARG_NONE;
break;
case POPT_ARG_NONE:
break;
default:
fatal ("Unknown POPT option table argInfo type: %d",
result[iy].argInfo);
}
result[iy].arg = NULL;
result[iy++].val = popt_next_val++;
}
return result;
}
/* Free a copied POPT option table structure. */
void free_popt_clone (struct poptOption *opts)
{
int ix;
assert (opts);
for (ix = 0; !is_tableend (&opts[ix]); ix += 1) {
if (opts[ix].argInfo == POPT_ARG_INCLUDE_TABLE)
free_popt_clone (opts[ix].arg);
}
free (opts);
}
/* Return a pointer to the copied POPT option table entry for which the
* 'val' field matches 'wanted'. */
struct poptOption *find_popt_option (struct poptOption *opts, int wanted)
{
assert (opts);
assert (LIMIT(wanted, popt_next_val));
for (size_t ix = 0; !is_tableend (&opts[ix]); ix += 1) {
struct poptOption *result;
assert (opts[ix].argInfo != POPT_ARG_CALLBACK);
if (opts[ix].val == wanted)
return &opts[ix];
switch (opts[ix].argInfo) {
case POPT_ARG_INCLUDE_TABLE:
result = find_popt_option (opts[ix].arg, wanted);
if (result)
return result;
break;
case POPT_ARG_STRING:
case POPT_ARG_INT:
case POPT_ARG_LONG:
case POPT_ARG_FLOAT:
case POPT_ARG_DOUBLE:
case POPT_ARG_VAL:
case POPT_ARG_NONE:
break;
default:
fatal ("Unknown POPT option table argInfo type: %d",
opts[ix].argInfo);
}
}
return NULL;
}
/* Render the command line as interpreted by POPT. */
static char *render_popt_command_line ()
{
int rc;
lists_t_strs *cmdline;
char *result;
const char **rest;
poptContext ctx;
struct poptOption *null_opts;
null_opts = clone_popt_options (mocp_opts);
ctx = poptGetContext ("mocp", mocp_argc, mocp_argv, null_opts,
POPT_CONTEXT_NO_EXEC);
read_popt_config (ctx);
prepend_mocp_opts (ctx);
cmdline = lists_strs_new (mocp_argc * 2);
lists_strs_append (cmdline, mocp_argv[0]);
while (1) {
size_t len;
char *str;
const char *arg;
struct poptOption *opt;
rc = poptGetNextOpt (ctx);
if (rc == -1)
break;
if (rc == POPT_ERROR_BADOPT) {
lists_strs_append (cmdline, poptBadOption (ctx, 0));
continue;
}
opt = find_popt_option (null_opts, rc);
if (!opt) {
result = xstrdup ("Couldn't find option in copied option table!");
goto err;
}
arg = poptGetOptArg (ctx);
if (opt->longName) {
len = strlen (opt->longName) + 3;
if (arg)
len += strlen (arg) + 3;
str = xmalloc (len);
if (arg)
snprintf (str, len, "--%s='%s'", opt->longName, arg);
else
snprintf (str, len, "--%s", opt->longName);
}
else {
len = 3;
if (arg)
len += strlen (arg) + 3;
str = xmalloc (len);
if (arg)
snprintf (str, len, "-%c '%s'", opt->shortName, arg);
else
snprintf (str, len, "-%c", opt->shortName);
}
lists_strs_push (cmdline, str);
free ((void *) arg);
}
rest = poptGetArgs (ctx);
if (rest)
lists_strs_load (cmdline, rest);
result = lists_strs_fmt (cmdline, "%s ");
err:
poptFreeContext (ctx);
free_popt_clone (null_opts);
lists_strs_free (cmdline);
return result;
}
static void override_config_option (const char *arg, lists_t_strs *deferred)
{
int len;
bool append;
char *ptr, *name, *value;
enum option_type type;
assert (arg != NULL);
ptr = strchr (arg, '=');
if (ptr == NULL)
goto error;
/* Allow for list append operator ("+="). */
append = (ptr > arg && *(ptr - 1) == '+');
name = trim (arg, ptr - arg - (append ? 1 : 0));
if (!name || !name[0])
goto error;
type = options_get_type (name);
if (type == OPTION_LIST) {
if (deferred) {
lists_strs_append (deferred, arg);
free (name);
return;
}
}
else if (append)
goto error;
value = trim (ptr + 1, strlen (ptr + 1));
if (!value || !value[0])
goto error;
if (value[0] == '\'' || value[0] == '"') {
len = strlen (value);
if (value[0] != value[len - 1])
goto error;
if (strlen (value) < 2)
goto error;
memmove (value, value + 1, len - 2);
value[len - 2] = 0x00;
}
if (!options_set_pair (name, value, append))
goto error;
options_ignore_config (name);
free (name);
free (value);
return;
error:
fatal ("Malformed override option: %s", arg);
}
static long get_num_param (const char *p,const char ** last)
{
char *e;
long val;
val = strtol (p, &e, 10);
if ((*e&&last==NULL)||e==p)
fatal ("The parameter should be a number!");
if (last)
*last=e;
return val;
}
/* Process the command line options. */
static void process_options (poptContext ctx, lists_t_strs *deferred)
{
int rc;
while ((rc = poptGetNextOpt (ctx)) >= 0) {
const char *jump_type, *arg;
arg = poptGetOptArg (ctx);
switch (rc) {
case CL_SDRIVER:
if (!options_check_list ("SoundDriver", arg))
fatal ("No such sound driver: %s", arg);
options_set_list ("SoundDriver", arg, false);
options_ignore_config ("SoundDriver");
break;
case CL_MUSICDIR:
options_set_bool ("StartInMusicDir", true);
options_ignore_config ("StartInMusicDir");
break;
case CL_NOIFACE:
params.allow_iface = 0;