This repository has been archived by the owner on Jan 29, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfIcy.cc
643 lines (542 loc) · 12.5 KB
/
fIcy.cc
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
/*
* fIcy - HTTP/1.0-ICY stream extractor/separator - implementation
* Copyright(c) 2003-2017 of wave++ (Yuri D'Elia) <wavexx@thregr.org>
* Distributed under GNU LGPL without ANY warranty.
*/
// local headers
#include "fIcy.hh"
#include "icy.hh"
#include "htfollow.hh"
#include "sanitize.hh"
#include "tmparse.hh"
#include "authparse.hh"
#include "rewrite.hh"
#include "match.hh"
#include "msg.hh"
using std::string;
using std::map;
// system headers
#include <iostream>
using std::cout;
using std::cerr;
#include <fstream>
using std::ofstream;
#include <stdexcept>
using std::runtime_error;
#include <limits>
#include <memory>
using std::auto_ptr;
// c system headers
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
#include <stdarg.h>
#include <signal.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
// globals (urgh)
enum file_mode { fm_overwrite, fm_append, fm_noclobber };
namespace
{
bool dupStdout = true;
char* lastFName = NULL;
bool rmPartial = false;
file_mode fileMode = fm_overwrite;
}
void
shwIcyHdr(const map<string, string>& headers, const char* search,
const char* name)
{
map<string, string>::const_iterator it;
if((it = headers.find(search)) != headers.end())
cerr << name << it->second << std::endl;
}
// return a new file opened for writing according to the default open mode
ofstream*
newFileName(const char* file)
{
// use open directly to avoid races
int flags = O_WRONLY|O_CREAT;
if(fileMode == fm_overwrite) flags |= O_TRUNC;
else if(fileMode == fm_append) flags |= O_APPEND;
else if(fileMode == fm_noclobber) flags |= O_EXCL;
int fd = open(file, flags, 00666);
if(fd == -1)
return NULL;
ofstream* ret = new ofstream(file, std::ios_base::out|std::ios_base::app);
close(fd);
return ret;
}
// return a new file opened for writing (file is updated to the final path)
ofstream*
newFileName(string& file, bool enumerate)
{
ofstream* out = newFileName(file.c_str());
if(!out)
{
if(!enumerate)
throw runtime_error(string("cannot write to `") + file + "'");
else
{
char buf[16];
for(size_t n = 0; n != std::numeric_limits<size_t>::max(); ++n)
{
snprintf(buf, sizeof(buf), ".%lu", n);
if((out = newFileName((file + buf).c_str())))
{
file += buf;
break;
}
}
if(!out)
throw runtime_error(string("no free files for `") + file + "'");
}
}
return out;
}
// SIGPIPE handler
void
sigPipe(const int)
{
msg("broken pipe: disabling duping.");
dupStdout = false;
// close the descriptor: this is needed to release the resource
close(STDOUT_FILENO);
}
// termination handler
void
sigTerm(const int sig)
{
if(rmPartial && lastFName)
{
msg("removing incomplete last file: %s", lastFName);
unlink(lastFName);
}
exit((sig == SIGTERM || sig == SIGALRM? Exit::success:
(sig == SIGPIPE? Exit::args:
Exit::fail)));
}
// signal installers
void
sigPipeInst()
{
signal(SIGPIPE, SIG_IGN);
}
void
sigTermInst(const bool handlePipe)
{
signal(SIGTERM, sigTerm);
signal(SIGINT, sigTerm);
signal(SIGHUP, sigTerm);
if(handlePipe)
signal(SIGPIPE, sigTerm);
}
// current song status
std::ostream&
hour(std::ostream& fd)
{
fd.setf(std::ios_base::right);
fd.width(2);
fd.fill('0');
return fd;
}
/*
* function naming scheme: yep. I'm again in a new coding style internal fight.
* But this time, I've been seriously tainted by functional/logical programming
* so be patient. When I'll come up with clear ideas, I will uniform the code.
*/
time_t
display_status(const string& title, const size_t num, const time_t last)
{
time_t now(time(NULL));
if(last)
{
// show the song duration
cerr << " [" << hour << ((now - last) / 60) << ":" <<
hour << ((now - last) % 60) << "]\n";
}
cerr << "playing #" << num << ": " << title << std::flush;
return now;
}
// update the sequence file
void
write_seq(ofstream& out, const char* file)
{
if(out.rdbuf()->is_open())
{
out << file << std::endl << std::flush;
if(!out)
throw runtime_error("cannot append to sequence file");
}
}
// find a free file number when using -E
size_t
findFreeFile(const char* prefix)
{
// decompose prefix to dir/prefix
string dir;
string pre;
const char* sep;
if((sep = strrchr(prefix, '/')))
{
dir.assign(prefix, sep - prefix);
pre = sep + 1;
}
else
{
dir = ".";
pre = prefix;
}
// start reading
DIR* dirSt = opendir(dir.c_str());
if(!dirSt)
throw runtime_error(string("cannot list ") + dir);
size_t enu = 1;
dirent* entry;
while((entry = readdir(dirSt)))
{
const char* name = entry->d_name;
if(pre.size())
{
if(strlen(name) > pre.size() &&
!pre.compare(0, pre.size(), name, pre.size()))
name += pre.size();
else
continue;
}
// support our two formats %lu and [%lu]
if(*name && *name == '[')
++name;
size_t tmp;
if(sscanf(name, "%lu", &tmp) == 1)
{
if(tmp >= enu)
enu = tmp + 1;
if(enu <= tmp)
throw runtime_error("no free files found");
}
}
closedir(dirSt);
return enu;
}
// implementation
int
main(int argc, char* const argv[]) try
{
// option defaults
prg = argv[0];
string outFile;
char* suffix = NULL;
char* auth = NULL;
ofstream seq;
bool enumFiles = false;
bool nameFiles = false;
bool showMeta = false;
bool numEFiles = false;
bool instSignal = false;
time_t maxTime = 0;
time_t idleTime = 0;
size_t maxFollow = fIcy::maxFollow;
size_t enu = 1;
char* rewriteArg = NULL;
Rewrite::arg_t rewriteType;
const char* coproc = fIcy::coproc;
BMatch match;
int arg;
while((arg = getopt(argc, argv, "do:E:mvtcAs:nprhq:x:X:I:f:F:C:M:l:a:i:")) != -1)
switch(arg)
{
case 'd':
dupStdout = false;
break;
case 'o':
outFile = optarg;
break;
case 'E':
enumFiles = true;
enu = atol(optarg);
break;
case 'm':
nameFiles = true;
break;
case 'v':
verbose = true;
break;
case 't':
showMeta = true;
break;
case 'c':
fileMode = fm_noclobber;
break;
case 'A':
fileMode = fm_append;
break;
case 's':
suffix = optarg;
break;
case 'n':
fileMode = fm_noclobber;
numEFiles = true;
break;
case 'p':
instSignal = true;
break;
case 'r':
rmPartial = true;
break;
case 'q':
seq.open(optarg, std::ios_base::out | std::ios_base::app);
if(!seq)
{
err("cannot open `%s' for appending", optarg);
return Exit::fail;
}
break;
case 'x':
match.include(optarg);
break;
case 'X':
match.exclude(optarg);
break;
case 'I':
match.load(optarg);
break;
case 'f':
rewriteArg = optarg;
rewriteType = Rewrite::expr;
break;
case 'F':
rewriteArg = optarg;
rewriteType = Rewrite::file;
break;
case 'C':
coproc = optarg;
break;
case 'M':
maxTime = tmParse(optarg);
break;
case 'l':
maxFollow = atol(optarg);
break;
case 'i':
idleTime = tmParse(optarg);
break;
case 'a':
auth = optarg;
break;
case 'h':
cout << prg << fIcy::fIcyHelp << prg << " v" << fIcy::version <<
" is\n" << fIcy::copyright;
default:
return Exit::args;
}
argc -= optind;
if(argc < 1 || argc > 3)
{
err("bad parameters; see %s -h", prg);
return Exit::args;
}
// connection parameters
URL url;
if(argc == 1)
{
// avoid the need of the protocol on the command line
url = argv[optind++];
if(!url.proto.size())
url.proto = Http::Proto::proto;
else if(url.proto != Http::Proto::proto)
throw runtime_error(string("unknown protocol ") + url.proto);
}
else
{
// 1.0.4 compatibility
url.proto = Http::Proto::proto;
url.server = argv[optind++];
url.port = argv[optind++];
url.path = (argc == 3? argv[optind++]: "/");
}
// check for parameters consistency
bool useMeta(enumFiles || nameFiles || !match.empty());
bool reqMeta(useMeta || showMeta);
auto_ptr<Rewrite> rewrite(rewriteArg?
new Rewrite(rewriteArg, coproc, rewriteType): NULL);
// enumFiles and nameFiles requires a prefix
if(useMeta && !outFile.size())
{
err("a prefix is required (-o) when writing files");
return Exit::args;
}
// numEFiles and append aren't compatible
if(numEFiles && fileMode == fm_append)
{
err("cannot append (-A) with numeric suffixes (-n)");
return Exit::args;
}
// you cannot disable duping if you don't write anything!
if(!(outFile.size() || dupStdout))
{
err("an output file (-o) is required when stdout is disabled (-d)");
return Exit::args;
}
// find the starting number when requested
if(!enu)
{
enu = findFreeFile(outFile.c_str());
msg("enumeration starting from %lu", enu);
}
// install the signals
instSignal = (instSignal && dupStdout);
rmPartial = (rmPartial && useMeta);
sigTermInst(!(instSignal || rewrite.get()));
if(instSignal)
sigPipeInst();
// setup headers
Http::Header qHeaders;
qHeaders.push_back(fIcy::userAgent);
if(reqMeta)
qHeaders.push_back(ICY::Proto::reqMeta);
// authorization
if(auth)
{
Http::Auth authData;
authParse(authData, auth);
qHeaders.push_back(authData.basicHeader());
}
// setup the timer
if(maxTime)
{
signal(SIGALRM, sigTerm);
alarm(maxTime);
}
// establish the connection
map<string, string> pReply;
auto_ptr<Socket> s(htFollow(pReply, url, qHeaders, maxFollow, idleTime));
if(reqMeta && pReply.find(ICY::Proto::metaint) == pReply.end())
{
err("requested metadata, but got nothing.");
return Exit::fail;
}
// show some headers (crappy)
if(verbose)
{
shwIcyHdr(pReply, ICY::Proto::notice1, "Notice: ");
shwIcyHdr(pReply, ICY::Proto::notice2, "Notice: ");
shwIcyHdr(pReply, ICY::Proto::title, "Title: ");
shwIcyHdr(pReply, ICY::Proto::genre, "Genre: ");
shwIcyHdr(pReply, ICY::Proto::url, "URL: ");
shwIcyHdr(pReply, ICY::Proto::br, "Bit Rate: ");
}
// start reading
size_t metaInt(reqMeta?
strtoul(pReply.find(ICY::Proto::metaint)->second.c_str(), NULL, 0):
fIcy::bufSz);
if(reqMeta && !metaInt)
throw std::runtime_error("bad value for metaint");
ICY::Reader reader(*s, fIcy::bufSz);
time_t tStamp(0);
string lastTitle;
// initial file
auto_ptr<std::ostream> out;
if(outFile.size() && !useMeta)
out.reset(newFileName(outFile, numEFiles));
else
// the first filename is unknown as the metadata block will
// arrive in the next metaInt bytes
out.reset();
for(;;)
{
if(dupStdout && !cout)
{
// try an empty write to determine if the file is ready
if(!write(STDOUT_FILENO, NULL, 0))
cout.clear();
}
// read the stream
if(reader.dup(out.get(), metaInt, dupStdout) != metaInt)
{
msg("connection terminated");
break;
}
if(!(outFile.size() || dupStdout))
break;
// read metadata
if(reqMeta)
{
map<string, string> data;
if(reader.readMeta(data))
{
map<string, string>::const_iterator it(
data.find(ICY::Proto::mTitle));
// de-uglify
string title;
if(it != data.end())
{
// sanitize immediately, we don't want \n for sed
title = sanitize_esc(it->second);
if(rewrite.get())
(*rewrite)(title);
}
if(title.size() && (title != lastTitle))
{
string newFName;
if(showMeta)
tStamp = display_status(title, enu, tStamp);
// skip the first filename generation when discarding partials
// or when the title doesn't match
if(useMeta)
{
if((enu || !rmPartial) && match(title.c_str()))
{
newFName = outFile;
if(enumFiles)
{
char buf[16];
snprintf(buf, sizeof(buf), (nameFiles? "[%lu] ": "%lu"), enu);
newFName += buf;
}
if(nameFiles)
newFName += sanitize_file(title);
if(suffix)
newFName += suffix;
// open the new file
out.reset(newFileName(newFName, numEFiles));
}
else
out.reset();
}
// update the last filename pointer
if(lastFName)
{
write_seq(seq, lastFName);
free(lastFName);
}
if(out.get())
{
lastFName = strdup(newFName.c_str());
msg("file changed to: %s", lastFName);
}
else if(lastFName)
{
lastFName = NULL;
msg("file reset");
}
// update stream number
lastTitle = title;
++enu;
}
}
}
}
return Exit::success;
}
catch(runtime_error& err)
{
::err("%s", err.what());
return Exit::fail;
}
catch(...)
{
err("unknown error, aborting");
abort();
}