ezstream.c 19.7 KB
Newer Older
1
2
3
/*
 *  ezstream - source client for Icecast with external en-/decoder support
 *  Copyright (C) 2003, 2004, 2005, 2006  Ed Zaleski <oddsock@oddsock.org>
4
 *  Copyright (C) 2007, 2009, 2015, 2017  Moritz Grimm <mgrimm@mrsserver.net>
5
6
 *
 *  This program is free software; you can redistribute it and/or modify
moritz's avatar
moritz committed
7
8
 *  it under the terms of the GNU General Public License version 2 as
 *  published by the Free Software Foundation.
9
10
11
12
13
14
15
16
17
18
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 */

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
oddsock's avatar
oddsock committed
19

20
21
#include "compat.h"

22
23
#include "ezstream.h"

24
#include <signal.h>
25

26
#include "cfg.h"
27
#include "cmdline.h"
28
#include "log.h"
29
#include "mdata.h"
30
#include "playlist.h"
31
#include "stream.h"
32
#include "util.h"
33
#include "xalloc.h"
34

35
36
37
38
#define STREAM_DONE	0
#define STREAM_CONT	1
#define STREAM_SKIP	2
#define STREAM_SERVERR	3
39
#define STREAM_UPDMDATA 4
40

41
stream_t		 main_stream;
42
43
44
playlist_t		 playlist;
int			 playlistMode;
unsigned int		 resource_errors;
45

46
47
48
const int		 ezstream_signals[] = {
	SIGTERM, SIGINT, SIGHUP, SIGUSR1, SIGUSR2
};
49

50
51
52
53
54
volatile sig_atomic_t	 rereadPlaylist;
volatile sig_atomic_t	 rereadPlaylist_notify;
volatile sig_atomic_t	 skipTrack;
volatile sig_atomic_t	 queryMetadata;
volatile sig_atomic_t	 quit;
oddsock's avatar
oddsock committed
55

56
void		sig_handler(int);
57
58
59
60

static char *	_build_reencode_cmd(const char *, const char *, cfg_stream_t,
				    mdata_t);
static FILE *	openResource(stream_t, const char *, int *, mdata_t *,
61
			     int *, long *);
62
int		reconnect(stream_t);
63
const char *	getTimeString(long);
64
int		sendStream(stream_t, FILE *, const char *, int, const char *,
65
			   struct timespec *);
66
67
int		streamFile(stream_t, const char *);
int		streamPlaylist(stream_t);
68
int		ez_shutdown(int);
oddsock's avatar
oddsock committed
69

70
71
72
73
void
sig_handler(int sig)
{
	switch (sig) {
74
75
76
77
	case SIGTERM:
	case SIGINT:
		quit = 1;
		break;
78
79
80
81
82
83
84
	case SIGHUP:
		rereadPlaylist = 1;
		rereadPlaylist_notify = 1;
		break;
	case SIGUSR1:
		skipTrack = 1;
		break;
85
86
87
	case SIGUSR2:
		queryMetadata = 1;
		break;
88
89
90
91
92
	default:
		break;
	}
}

93
static char *
94
_build_reencode_cmd(const char *extension, const char *filename,
95
    cfg_stream_t cfg_stream, mdata_t md)
96
{
Moritz Grimm's avatar
Moritz Grimm committed
97
98
	cfg_decoder_t		 decoder;
	cfg_encoder_t		 encoder;
99
	char			*artist, *album, *title, *songinfo, *tmp;
Moritz Grimm's avatar
Moritz Grimm committed
100
101
102
103
104
105
	char			*filename_quoted;
	char			*custom_songinfo;
	struct util_dict	 dicts[6];
	char			*dec_str;
	char			*cmd_str;
	size_t			 cmd_str_size;
106

107
	decoder = cfg_decoder_list_findext(cfg_get_decoders(), extension);
108
109
	if (!decoder) {
		log_error("cannot decode: %s: unsupported file extension %s",
110
		    filename, extension);
111
		return (NULL);
112
	}
113
	encoder = cfg_encoder_list_find(cfg_get_encoders(),
114
	    cfg_stream_get_encoder(cfg_stream));
115
116
	if (!encoder) {
		log_error("cannot encode: %s: unknown encoder",
117
		    cfg_stream_get_encoder(cfg_stream));
118
119
120
		return (NULL);
	}

121
	tmp = util_utf82char(mdata_get_artist(md));
122
	artist = util_shellquote(tmp, 0);
123
124
125
	xfree(tmp);

	tmp = util_utf82char(mdata_get_album(md));
126
	album = util_shellquote(tmp, 0);
127
128
129
	xfree(tmp);

	tmp = util_utf82char(mdata_get_title(md));
130
	title = util_shellquote(tmp, 0);
131
132
133
	xfree(tmp);

	tmp = util_utf82char(mdata_get_songinfo(md));
134
	songinfo = util_shellquote(tmp, 0);
135
	xfree(tmp);
Moritz Grimm's avatar
Moritz Grimm committed
136

137
	filename_quoted = util_shellquote(filename, 0);
Moritz Grimm's avatar
Moritz Grimm committed
138

139
	/*
Moritz Grimm's avatar
Moritz Grimm committed
140
141
142
143
144
	 * if (prog && format)
	 *    metatoformat
	 * else
	 *   if (!prog && title)
	 *     emptymeta
145
	 *   else
Moritz Grimm's avatar
Moritz Grimm committed
146
	 *     replacemeta
147
	 */
Moritz Grimm's avatar
Moritz Grimm committed
148
149
	if (cfg_get_metadata_program() &&
	    cfg_get_metadata_format_str()) {
150
151
		char	 buf[BUFSIZ];
		char	*unquoted;
Moritz Grimm's avatar
Moritz Grimm committed
152

153
		mdata_strformat(md, buf, sizeof(buf),
Moritz Grimm's avatar
Moritz Grimm committed
154
		    cfg_get_metadata_format_str());
155
		unquoted = util_utf82char(buf);
156
		custom_songinfo = util_shellquote(unquoted, 0);
Moritz Grimm's avatar
Moritz Grimm committed
157
158
159
160
161
162
		xfree(unquoted);
	} else {
		if (!cfg_get_metadata_program() &&
		    strstr(cfg_decoder_get_program(decoder),
			PLACEHOLDER_TITLE) != NULL) {
			custom_songinfo = xstrdup("");
163
		} else {
Moritz Grimm's avatar
Moritz Grimm committed
164
			custom_songinfo = xstrdup(songinfo);
165
166
		}
	}
Moritz Grimm's avatar
Moritz Grimm committed
167
	xfree(songinfo);
168

Moritz Grimm's avatar
Moritz Grimm committed
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
	memset(dicts, 0, sizeof(dicts));
	dicts[0].from = PLACEHOLDER_ARTIST;
	dicts[0].to = artist;
	dicts[1].from = PLACEHOLDER_ALBUM;
	dicts[1].to = album;
	dicts[2].from = PLACEHOLDER_TITLE;
	dicts[2].to = title;
	dicts[3].from = PLACEHOLDER_TRACK;
	dicts[3].to = filename_quoted;
	dicts[4].from = PLACEHOLDER_METADATA;
	dicts[4].to = custom_songinfo;

	if (!cfg_get_metadata_program() &&
	    strstr(cfg_encoder_get_program(encoder),
		PLACEHOLDER_TITLE) != NULL) {
		xfree(custom_songinfo);
		dicts[4].to = custom_songinfo = xstrdup("");
186
	}
187

188
189
190
	dec_str = util_expand_words(cfg_decoder_get_program(decoder), dicts);
	cmd_str_size = strlen(dec_str) + 1;
	if (cfg_encoder_get_program(encoder)) {
Moritz Grimm's avatar
Moritz Grimm committed
191
192
		char	*enc_str;

193
194
195
196
197
198
199
200
201
202
203
204
		enc_str = util_expand_words(cfg_encoder_get_program(encoder),
		    dicts);
		cmd_str_size += strlen(" | ") + strlen(enc_str);
		cmd_str = xcalloc(cmd_str_size, sizeof(char));
		snprintf(cmd_str, cmd_str_size, "%s | %s", dec_str, enc_str);
		xfree(enc_str);
		xfree(dec_str);
	} else {
		cmd_str = xcalloc(cmd_str_size, sizeof(char));
		snprintf(cmd_str, cmd_str_size, "%s", dec_str);
		xfree(dec_str);
	}
205

Moritz Grimm's avatar
Moritz Grimm committed
206
207
208
209
210
211
212
	xfree(artist);
	xfree(album);
	xfree(title);
	xfree(filename_quoted);
	xfree(custom_songinfo);

	return (cmd_str);
213
}
oddsock's avatar
oddsock committed
214

215
static FILE *
216
217
openResource(stream_t stream, const char *filename, int *popenFlag,
	     mdata_t *md_p, int *isStdin, long *songLen)
218
{
219
220
221
222
	FILE		*filep = NULL;
	char		 extension[25];
	char		*p = NULL;
	char		*pCommandString = NULL;
223
	mdata_t 	 md;
224
	cfg_stream_t	 cfg_stream = stream_get_cfg_stream(stream);
oddsock's avatar
oddsock committed
225

226
227
	if (md_p != NULL)
		*md_p = NULL;
228
229
	if (songLen != NULL)
		*songLen = 0;
230

231
	if ((isStdin && *isStdin) ||
232
	    strcasecmp(filename, "stdin") == 0) {
233
		if (cfg_get_metadata_program()) {
234
235
236
237
			md = mdata_create();

			if (0 > mdata_run_program(md, cfg_get_metadata_program()) ||
			    0 > stream_set_metadata(stream, md, NULL)) {
238
				mdata_destroy(&md);
239
240
				return (NULL);
			}
241

242
243
			if (md_p != NULL)
				*md_p = md;
244
			else
245
				mdata_destroy(&md);
246
		}
247

248
249
		if (isStdin != NULL)
			*isStdin = 1;
250
		filep = stdin;
251
		return (filep);
oddsock's avatar
oddsock committed
252
	}
253

254
255
256
257
	if (isStdin != NULL)
		*isStdin = 0;

	extension[0] = '\0';
258
	p = strrchr(filename, '.');
259
260
261
	if (p != NULL)
		strlcpy(extension, p, sizeof(extension));
	for (p = extension; *p != '\0'; p++)
262
		*p = (char)tolower((int)*p);
263
264

	if (strlen(extension) == 0) {
265
		log_error("%s: cannot determine file type", filename);
266
267
268
		return (filep);
	}

269
	md = mdata_create();
270
	if (cfg_get_metadata_program()) {
271
272
		if (0 > mdata_run_program(md, cfg_get_metadata_program()))
			mdata_destroy(&md);
273
	} else {
274
275
		if (0 > mdata_parse_file(md, filename))
			mdata_destroy(&md);
276
	}
277
278
	if (NULL == md)
		return (NULL);
279
	if (songLen != NULL)
280
		*songLen = mdata_get_length(md);
281
282

	*popenFlag = 0;
283
	if (cfg_stream_get_encoder(cfg_stream)) {
284
		int	stderr_fd = -1;
285

286
		pCommandString = _build_reencode_cmd(extension, filename,
287
		    cfg_stream, md);
288
289
		if (NULL == pCommandString)
			return (NULL);
290
291
		if (md_p != NULL)
			*md_p = md;
292
		else
293
			mdata_destroy(&md);
294
		log_info("running command: %s", pCommandString);
295

296
		if (cfg_get_program_quiet_stderr()) {
297
298
			int fd;

299
			stderr_fd = dup(fileno(stderr));
300
301
302
303
			if (0 > stderr_fd) {
				log_alert("dup: %s", strerror(errno));
				exit(1);
			}
304
			if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) == -1) {
305
306
				log_alert("%s: %s", _PATH_DEVNULL,
				    strerror(errno));
307
				exit(1);
308
309
			}

310
			dup2(fd, fileno(stderr));
311
			close(fd);
312
313
314
315
316
317
318
		}

		fflush(NULL);
		errno = 0;
		if ((filep = popen(pCommandString, "r")) == NULL) {
			/* popen() does not set errno reliably ... */
			if (errno)
319
320
				log_error("execution error: %s: %s",
				    pCommandString, strerror(errno));
321
			else
322
323
				log_error("execution error: %s",
				    pCommandString);
324
325
326
327
		} else {
			*popenFlag = 1;
		}
		xfree(pCommandString);
328

329
		if (cfg_get_program_quiet_stderr())
330
			dup2(stderr_fd, fileno(stderr));
331

332
		if (stderr_fd != -1)
333
			close(stderr_fd);
334

335
		return (filep);
336
	}
337

338
339
	if (md_p != NULL)
		*md_p = md;
340
	else
341
		mdata_destroy(&md);
342

343
344
	if ((filep = fopen(filename, "rb")) == NULL) {
		log_error("%s: %s", filename, strerror(errno));
345
346
		return (NULL);
	}
347
348

	return (filep);
349
350
}

351
int
352
reconnect(stream_t stream)
353
354
{
	unsigned int	i;
355
	cfg_server_t	cfg_server = stream_get_cfg_server(stream);
356
357
358

	i = 0;
	while (++i) {
359
		if (cfg_server_get_reconnect_attempts(cfg_server) > 0)
360
			log_notice("reconnect: %s: attempt #%u/%u ...",
361
362
			    cfg_server_get_hostname(cfg_server), i,
			    cfg_server_get_reconnect_attempts(cfg_server));
363
		else
364
			log_notice("reconnect: %s: attempt #%u ...",
365
			    cfg_server_get_hostname(cfg_server), i);
366

367
368
		stream_disconnect(stream);
		if (0 == stream_connect(stream)) {
369
			log_notice("reconnect: %s: success",
370
			    cfg_server_get_hostname(cfg_server));
371
			return (0);
372
373
		}

374
375
		if (cfg_server_get_reconnect_attempts(cfg_server) > 0 &&
		    i >= cfg_server_get_reconnect_attempts(cfg_server))
376
377
			break;

378
		if (quit)
379
			return (-1);
380
381
		else
			sleep(5);
382
383
	};

384
	log_warning("reconnect failed: giving up");
385
386

	return (-1);
387
388
}

389
const char *
390
getTimeString(long seconds)
391
{
392
	static char	str[25];
393
	long		secs, mins, hours;
394
395
396
397
398
399
400
401
402
403

	if (seconds < 0)
		return (NULL);

	secs = seconds;
	hours = secs / 3600;
	secs %= 3600;
	mins = secs / 60;
	secs %= 60;

404
	snprintf(str, sizeof(str), "%ldh%02ldm%02lds", hours, mins, secs);
405
406
407
	return ((const char *)str);
}

408
int
409
sendStream(stream_t stream, FILE *filepstream, const char *fileName,
410
	   int isStdin, const char *songLenStr, struct timespec *tv)
411
{
412
	char		  buff[4096];
413
414
415
416
417
	size_t		  bytes_read, total, oldTotal;
	int		  ret;
	double		  kbps = -1.0;
	struct timespec	  timeStamp, *startTime = tv;
	struct timespec	  callTime, currentTime;
418
	cfg_server_t	  cfg_server = stream_get_cfg_server(stream);
419
	cfg_intake_t	  cfg_intake = stream_get_cfg_intake(stream);
420

421
	clock_gettime(CLOCK_MONOTONIC, &callTime);
422

423
	timeStamp.tv_sec = startTime->tv_sec;
424
	timeStamp.tv_nsec = startTime->tv_nsec;
425
426

	total = oldTotal = 0;
427
	ret = STREAM_DONE;
428
429
430
	while ((bytes_read = fread(buff, 1, sizeof(buff), filepstream)) > 0) {
		if (!stream_get_connected(stream)) {
			log_warning("%s: connection lost",
431
			    cfg_server_get_hostname(cfg_server));
432
433
434
435
			if (0 > reconnect(stream)) {
				ret = STREAM_SERVERR;
				break;
			}
436
437
		}

438
		stream_sync(stream);
439

440
441
		if (0 > stream_send(stream, buff, bytes_read)) {
			if (0 > reconnect(stream))
442
				ret = STREAM_SERVERR;
443
			break;
444
445
		}

446
447
		if (quit)
			break;
448
449
		if (rereadPlaylist_notify) {
			rereadPlaylist_notify = 0;
450
			if (CFG_INTAKE_PLAYLIST == cfg_intake_get_type(cfg_intake))
451
				log_notice("HUP signal received: playlist re-read scheduled");
452
453
454
		}
		if (skipTrack) {
			skipTrack = 0;
455
			ret = STREAM_SKIP;
456
457
			break;
		}
458

459
		clock_gettime(CLOCK_MONOTONIC, &currentTime);
460
461

		if (queryMetadata ||
462
		    (0 <= cfg_get_metadata_refresh_interval() &&
463
464
			(currentTime.tv_sec - callTime.tv_sec >=
			    cfg_get_metadata_refresh_interval()))) {
465
			queryMetadata = 0;
466
			if (cfg_get_metadata_program()) {
467
				ret = STREAM_UPDMDATA;
468
				break;
oddsock's avatar
oddsock committed
469
			}
470
471
		}

472
		total += bytes_read;
473
		if (cfg_get_program_rtstatus_output()) {
474
			double	oldTime, newTime;
475

476
			if (!isStdin && playlistMode) {
477
478
				if (CFG_INTAKE_PROGRAM == cfg_intake_get_type(cfg_intake)) {
					char *tmp = xstrdup(cfg_intake_get_filename(cfg_intake));
479
					printf("  [%s]", basename(tmp));
480
481
482
					xfree(tmp);
				} else
					printf("  [%4lu/%-4lu]",
483
484
					    playlist_get_position(playlist),
					    playlist_get_num_items(playlist));
485
			}
486
487

			oldTime = (double)timeStamp.tv_sec
488
			    + (double)timeStamp.tv_nsec / 1000000000.0;
489
			newTime = (double)currentTime.tv_sec
490
			    + (double)currentTime.tv_nsec / 1000000000.0;
491
492
			if (songLenStr == NULL)
				printf("  [ %s]",
493
494
				    getTimeString(currentTime.tv_sec -
					startTime->tv_sec));
495
496
			else
				printf("  [ %s/%s]",
497
498
499
				    getTimeString(currentTime.tv_sec -
					startTime->tv_sec),
				    songLenStr);
500
			if (newTime - oldTime >= 1.0) {
501
				kbps = (((double)(total - oldTotal)
502
				    / (newTime - oldTime)) * 8.0) / 1000.0;
503
				timeStamp.tv_sec = currentTime.tv_sec;
504
				timeStamp.tv_nsec = currentTime.tv_nsec;
505
506
507
508
509
510
511
512
513
514
				oldTotal = total;
			}
			if (kbps < 0)
				printf("                 ");
			else
				printf("  [%8.2f kbps]", kbps);

			printf("  \r");
			fflush(stdout);
		}
oddsock's avatar
oddsock committed
515
	}
516
517
518
	if (ferror(filepstream)) {
		if (errno == EINTR) {
			clearerr(filepstream);
519
			ret = STREAM_CONT;
520
		} else if (errno == EBADF && isStdin)
521
			log_notice("no (more) data available on standard input");
522
		else
523
524
			log_error("sendStream: %s: %s", fileName,
			    strerror(errno));
525
526
	}

527
	return (ret);
528
529
530
}

int
531
streamFile(stream_t stream, const char *fileName)
532
533
534
{
	FILE		*filepstream = NULL;
	int		 popenFlag = 0;
535
	char		*songLenStr = NULL;
536
537
	int		 ret, retval = 0;
	long		 songLen;
538
	mdata_t 	 md = NULL;
539
	struct timespec	 startTime;
540
	cfg_stream_t	 cfg_stream = stream_get_cfg_stream(stream);
541
542
	cfg_intake_t	 cfg_intake = stream_get_cfg_intake(stream);
	int		 isStdin = cfg_intake_get_type(cfg_intake) == CFG_INTAKE_STDIN;
543

544
	if ((filepstream = openResource(stream, fileName, &popenFlag, &md, &isStdin, &songLen))
545
	    == NULL) {
546
		mdata_destroy(&md);
547
		if (++resource_errors > 100) {
548
			log_error("too many errors; giving up");
549
550
			return (0);
		}
551
552
		/* Continue with next resource on failure: */
		return (1);
553
554
	}
	resource_errors = 0;
555

556
557
558
	if (md != NULL) {
		const char	*tmp;
		char		*metaData;
559

560
561
562
		tmp = mdata_get_songinfo(md) ?
		    mdata_get_songinfo(md) : mdata_get_name(md);
		metaData = util_utf82char(tmp);
563
564
		log_notice("streaming: %s (%s)", metaData,
		    isStdin ? "stdin" : fileName);
565
		xfree(metaData);
566
567

		/* MP3 streams are special, so set the metadata explicitly: */
568
		if (CFG_STREAM_MP3 == cfg_stream_get_format(cfg_stream))
569
			stream_set_metadata(stream, md, NULL);
570

571
		mdata_destroy(&md);
572
	} else if (isStdin)
573
		log_notice("streaming: standard input");
574

moritz's avatar
moritz committed
575
	if (songLen > 0)
576
		songLenStr = xstrdup(getTimeString(songLen));
577
	clock_gettime(CLOCK_MONOTONIC, &startTime);
578
	do {
579
		ret = sendStream(stream, filepstream, fileName, isStdin,
580
		    songLenStr, &startTime);
581
582
		if (quit)
			break;
583
		if (ret != STREAM_DONE) {
584
585
			if ((skipTrack && rereadPlaylist) ||
			    (skipTrack && queryMetadata)) {
586
				skipTrack = 0;
587
588
589
590
591
				ret = STREAM_CONT;
			}
			if (queryMetadata && rereadPlaylist) {
				queryMetadata = 0;
				ret = STREAM_CONT;
592
			}
593
			if (ret == STREAM_SKIP || skipTrack) {
594
				skipTrack = 0;
595
596
				if (!isStdin)
					log_notice("USR1 signal received: skipping current track");
597
				retval = 1;
598
599
				ret = STREAM_DONE;
			}
600
601
			if (ret == STREAM_UPDMDATA || queryMetadata) {
				queryMetadata = 0;
602
				if (cfg_get_metadata_no_updates())
603
					continue;
604
				if (cfg_get_metadata_program()) {
605
					char		*mdataStr = NULL;
606
					mdata_t 	 prog_md;
607

608
					log_info("running metadata program: %s",
609
					    cfg_get_metadata_program());
610
611
612
613
					prog_md = mdata_create();
					if (0 > mdata_run_program(md, cfg_get_metadata_program()) ||
					    0 > stream_set_metadata(stream, prog_md, &mdataStr)) {
						mdata_destroy(&prog_md);
614
615
						retval = 0;
						ret = STREAM_DONE;
616
						continue;
617
					}
618
					mdata_destroy(&prog_md);
619
					log_info("new metadata: %s", mdataStr);
620
621
622
					xfree(mdataStr);
				}
			}
623
624
625
			if (ret == STREAM_SERVERR) {
				retval = 0;
				ret = STREAM_DONE;
626
627
628
			}
		} else
			retval = 1;
629
	} while (ret != STREAM_DONE);
630
631

	if (popenFlag)
oddsock's avatar
oddsock committed
632
		pclose(filepstream);
Moritz Grimm's avatar
Moritz Grimm committed
633
	else if (!isStdin)
oddsock's avatar
oddsock committed
634
		fclose(filepstream);
635

636
637
638
	if (songLenStr != NULL)
		xfree(songLenStr);

639
	return (retval);
oddsock's avatar
oddsock committed
640
}
641

642
int
643
streamPlaylist(stream_t stream)
644
645
{
	const char	*song;
moritz's avatar
moritz committed
646
	char		 lastSong[PATH_MAX];
647
	cfg_intake_t	 cfg_intake = stream_get_cfg_intake(stream);
648
649

	if (playlist == NULL) {
650
651
652
		switch (cfg_intake_get_type(cfg_intake)) {
		case CFG_INTAKE_PROGRAM:
			if ((playlist = playlist_program(cfg_intake_get_filename(cfg_intake))) == NULL)
653
				return (0);
654
			break;
655
		case CFG_INTAKE_STDIN:
656
657
658
659
			if ((playlist = playlist_read(NULL)) == NULL)
				return (0);
			break;
		default:
660
			if ((playlist = playlist_read(cfg_intake_get_filename(cfg_intake))) == NULL)
661
				return (0);
662
			if (playlist_get_num_items(playlist) == 0)
663
				log_warning("%s: playlist empty",
664
				    cfg_intake_get_filename(cfg_intake));
665
			break;
666
		}
667
	} else {
668
669
670
671
672
		/*
		 * XXX: This preserves traditional behavior, however,
		 *      rereading the playlist after each walkthrough seems a
		 *      bit more logical.
		 */
673
		playlist_rewind(playlist);
674
	}
675

676
677
	if (CFG_INTAKE_PROGRAM != cfg_intake_get_type(cfg_intake) &&
	    cfg_intake_get_shuffle(cfg_intake))
678
679
680
681
		playlist_shuffle(playlist);

	while ((song = playlist_get_next(playlist)) != NULL) {
		strlcpy(lastSong, song, sizeof(lastSong));
682
		if (!streamFile(stream, song))
683
			return (0);
684
685
		if (quit)
			break;
686
687
		if (rereadPlaylist) {
			rereadPlaylist = rereadPlaylist_notify = 0;
688
			if (CFG_INTAKE_PROGRAM == cfg_intake_get_type(cfg_intake))
689
				continue;
690
			log_notice("rereading playlist");
691
692
			if (!playlist_reread(&playlist))
				return (0);
693
			if (cfg_intake_get_shuffle(cfg_intake))
694
695
696
697
				playlist_shuffle(playlist);
			else {
				playlist_goto_entry(playlist, lastSong);
				playlist_skip_next(playlist);
oddsock's avatar
oddsock committed
698
			}
699
			continue;
700
		}
oddsock's avatar
oddsock committed
701
	}
702

703
	return (1);
oddsock's avatar
oddsock committed
704
705
}

706
int
707
ez_shutdown(int exitval)
708
{
709
710
711
	if (main_stream)
		stream_destroy(&main_stream);

712
	stream_exit();
713
	playlist_exit();
Moritz Grimm's avatar
Moritz Grimm committed
714
	log_exit();
715
	cfg_exit();
716
717
718
719

	return (exitval);
}

720
int
721
main(int argc, char *argv[])
oddsock's avatar
oddsock committed
722
{
723
	int		 ret, cont;
724
	const char	*errstr;
725
726
	extern char	*optarg;
	extern int	 optind;
727
	struct sigaction act;
moritz's avatar
moritz committed
728
	unsigned int	 i;
729
730
	cfg_server_t	 cfg_server;
	cfg_stream_t	 cfg_stream;
731
	cfg_intake_t	 cfg_intake;
732

Moritz Grimm's avatar
Moritz Grimm committed
733
	ret = 1;
734
735
	if (0 > cfg_init() ||
	    0 > cmdline_parse(argc, argv, &ret) ||
Moritz Grimm's avatar
Moritz Grimm committed
736
	    0 > log_init(cfg_get_program_name()) ||
737
	    0 > playlist_init() ||
738
	    0 > cfg_file_reload() ||
739
	    0 > stream_init())
Moritz Grimm's avatar
Moritz Grimm committed
740
		return (ez_shutdown(ret));
741

Moritz Grimm's avatar
Moritz Grimm committed
742
743
	log_set_verbosity(cfg_get_program_verbosity());

744
745
	if (0 > cfg_check(&errstr)) {
		log_error("%s: %s", cfg_get_program_config_file(), errstr);
746
		return (ez_shutdown(2));
oddsock's avatar
oddsock committed
747
	}
748

749
750
	main_stream = stream_create(CFG_DEFAULT);
	if (0 > stream_configure(main_stream))
751
		return (ez_shutdown(1));
752
753
	cfg_server = stream_get_cfg_server(main_stream);
	cfg_stream = stream_get_cfg_stream(main_stream);
754
	cfg_intake = stream_get_cfg_intake(main_stream);
oddsock's avatar
oddsock committed
755

756
757
	memset(&act, 0, sizeof(act));
	act.sa_handler = sig_handler;
758
#ifdef SA_RESTART
759
	act.sa_flags = SA_RESTART;
760
#endif
moritz's avatar
moritz committed
761
762
	for (i = 0; i < sizeof(ezstream_signals) / sizeof(int); i++) {
		if (sigaction(ezstream_signals[i], &act, NULL) == -1) {
763
			log_syserr(ERROR, errno, "sigaction");
764
			return (ez_shutdown(1));
moritz's avatar
moritz committed
765
766
		}
	}
767
768
769
770
	/*
	 * Ignore SIGPIPE, which has been seen to give a long-running ezstream
	 * process trouble. EOF and/or EPIPE are also easier to handle.
	 */
771
772
773
#ifndef SIG_IGN
# define SIG_IGN	 (void (*)(int))1
#endif /* !SIG_IGN */
774
775
	act.sa_handler = SIG_IGN;
	if (sigaction(SIGPIPE, &act, NULL) == -1) {
776
		log_syserr(ERROR, errno, "sigaction");
777
778
		return (ez_shutdown(1));
	}
779

780
	if (0 > util_write_pid_file(cfg_get_program_pid_file()))
781
782
		log_syserr(WARNING, errno, cfg_get_program_pid_file());

783
	if (0 > stream_connect(main_stream)) {
784
785
786
787
		log_error("initial server connection failed");
		return (ez_shutdown(1));
	}
	log_notice("connected: %s://%s:%u%s",