forked from ghewgill/nwr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
streamer.cpp
892 lines (851 loc) · 22.7 KB
/
streamer.cpp
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
#include <arpa/inet.h>
#include <assert.h>
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <list>
#include <string>
#include <vector>
//#define TRACE
using namespace std;
const int BUFSIZE = 65536;
struct config_t {
string ConfigFileName;
string Server;
int Port;
string Log;
string Encoder;
string ContentType;
int MaxClients;
string Name;
string Genre;
string URL;
string IRC;
string AIM;
string ICQ;
};
config_t Config = {
"",
"localhost",
8001,
"streamer.log",
"lame -r -m m -s 11.025 -x -b 16 -q 9 - -",
"audio/mpeg",
10
};
#ifdef TRACE
bool Trace;
#endif
FILE *Log;
string Title;
char Buffer[BUFSIZE];
int BufferHead;
int filterpid;
int filterin = -1;
int filterout = -1;
int monitorin = -1;
void filter(pid_t &filterpid, int &filterin, int &filterout)
{
int pin[2], pout[2];
if (pipe(pin) != 0 || pipe(pout) != 0) {
perror("pipe");
exit(1);
}
pid_t child = fork();
if (child == -1) {
perror("fork");
exit(1);
}
if (child == 0) {
dup2(pin[0], 0);
close(pin[1]);
dup2(pout[1], 1);
close(pout[0]);
execl("/bin/sh", "sh", "-c", Config.Encoder.c_str(), NULL);
perror("execl");
exit(127);
}
close(pin[0]);
close(pout[1]);
filterpid = child;
filterin = pin[1];
filterout = pout[0];
// Make the input to the filter nonblocking, so we will never
// deadlock due to reading and writing from the same process.
// The worst effect of this will be short skips as filter input
// is dropped on the floor.
int one = 1;
if (ioctl(filterin, FIONBIO, &one) != 0) {
perror("ioctl");
exit(1);
}
}
string HttpEscape(const string &s)
{
string r;
for (string::const_iterator i = s.begin(); i != s.end(); i++) {
if (isalnum(*i)) {
r += *i;
} else if (*i == ' ') {
r += '+';
} else {
char buf[4];
snprintf(buf, sizeof(buf), "%%%02X", *i);
r += buf;
}
}
return r;
}
void LoadConfig(const char *fn)
{
FILE *f = fopen(fn, "r");
if (f == NULL) {
fprintf(stderr, "streamer: streamer.conf not found: (%d) %s\n", errno, strerror(errno));
exit(1);
}
Config.ConfigFileName = fn;
char buf[1024];
while (fgets(buf, sizeof(buf), f) != NULL) {
if (buf[0] == '#') {
continue;
}
const char *name = strtok(buf, " \t");
if (name == NULL) {
continue;
}
const char *value = strtok(NULL, "\n");
if (value == NULL) {
value = "";
} else {
value += strspn(value, " \t");
}
if (strcasecmp(name, "Server") == 0) {
Config.Server = value;
printf("Server: %s\n", value);
} else if (strcasecmp(name, "Port") == 0) {
Config.Port = atoi(value);
} else if (strcasecmp(name, "Log") == 0) {
Config.Log = value;
} else if (strcasecmp(name, "Encoder") == 0) {
Config.Encoder = value;
} else if (strcasecmp(name, "Content-Type") == 0) {
Config.ContentType = value;
} else if (strcasecmp(name, "MaxClients") == 0) {
Config.MaxClients = atoi(value);
} else if (strcasecmp(name, "Name") == 0) {
Config.Name = value;
} else if (strcasecmp(name, "Genre") == 0) {
Config.Genre = value;
} else if (strcasecmp(name, "URL") == 0) {
Config.URL = value;
} else if (strcasecmp(name, "IRC") == 0) {
Config.IRC = value;
} else if (strcasecmp(name, "AIM") == 0) {
Config.AIM = value;
} else if (strcasecmp(name, "ICQ") == 0) {
Config.ICQ = value;
} else {
fprintf(stderr, "streamer: unknown config option: %s\n", name);
exit(1);
}
}
fclose(f);
}
class Stream {
public:
virtual ~Stream() {}
virtual int getfd() = 0;
virtual bool needWritable() { return false; }
virtual bool notifyRead() { return true; }
virtual bool notifyWrite() { return true; }
virtual bool checkOverflow(int n) { return false; }
};
list<Stream *> Clients;
int TotalClients;
class RawInputStream: public Stream {
public:
virtual int getfd() { return 0; }
virtual bool notifyRead();
};
class TitleMonitor: public Stream {
public:
TitleMonitor();
virtual ~TitleMonitor();
virtual int getfd() { return monitorout; }
virtual bool notifyRead();
private:
pid_t monitorpid;
int monitorout;
string title;
};
class FilteredInputStream: public Stream {
public:
virtual int getfd() { return filterout; }
virtual bool notifyRead();
};
class Listener: public Stream {
public:
Listener();
virtual ~Listener();
virtual int getfd() { return s; }
virtual bool notifyRead();
private:
int s;
};
class ShoutcastDirectory: public Stream {
public:
ShoutcastDirectory();
virtual ~ShoutcastDirectory();
virtual int getfd();
virtual bool needWritable();
virtual bool notifyRead();
virtual bool notifyWrite();
private:
int s;
int id;
bool connected;
int refresh;
time_t nextupdate;
char buf[1024];
int index;
};
class Client: public Stream {
public:
Client(int f, in_addr p);
virtual ~Client();
virtual int getfd() { return fd; }
virtual bool needWritable();
virtual bool notifyRead();
virtual bool notifyWrite();
virtual bool checkOverflow(int n);
private:
const int fd;
const in_addr peer;
const time_t start;
bool streaming;
int tail;
char request[1024];
int index;
};
bool RawInputStream::notifyRead()
{
#ifdef TRACE
if (Trace) printf("%d RawInputStream::notifyRead\n", getpid());
#endif
char buf[4096];
ssize_t n = read(0, buf, sizeof(buf));
if (n < 0) {
perror("read");
exit(1);
} else if (n == 0) {
fprintf(stderr, "streamer: eof on input\n");
exit(0);
}
#ifdef TRACE
if (Trace) printf("%d read raw %d\n", getpid(), n);
#endif
if (filterin != -1) {
ssize_t r = write(filterin, buf, n);
if (r < n) {
perror("filterin write");
}
}
#ifdef TRACE
if (Trace) printf("%d after filter write\n", getpid());
#endif
if (monitorin != -1) {
write(monitorin, buf, n);
}
#ifdef TRACE
if (Trace) printf("%d after monitor write\n", getpid());
#endif
return true;
}
TitleMonitor::TitleMonitor()
{
int pin[2], pout[2];
if (pipe(pin) != 0 || pipe(pout) != 0) {
perror("pipe");
exit(1);
}
monitorpid = fork();
if (monitorpid == -1) {
perror("fork");
exit(1);
}
if (monitorpid == 0) {
dup2(pin[0], 0);
close(pin[1]);
dup2(pout[1], 1);
close(pout[0]);
execl("/bin/sh", "sh", "-c", "./monitor -", NULL);
perror("execl");
exit(127);
}
close(pin[0]);
close(pout[1]);
monitorin = pin[1];
monitorout = pout[0];
}
TitleMonitor::~TitleMonitor()
{
close(monitorin);
int status;
if (waitpid(monitorpid, &status, 0) < 0) {
perror("waitpid");
exit(1);
}
}
bool TitleMonitor::notifyRead()
{
char buf[256];
ssize_t n = read(monitorout, buf, sizeof(buf));
if (n <= 0) {
if (n < 0) {
perror("read");
}
close(filterout);
filterout = -1;
return false;
}
for (int i = 0; i < n; i++) {
if (buf[i] == '\n') {
Title = title;
title.erase();
printf("Title: %s\n", Title.c_str());
} else {
title += buf[i];
}
}
return true;
}
bool FilteredInputStream::notifyRead()
{
#ifdef TRACE
if (Trace) printf("%d FilteredInputStream::notifyRead\n", getpid());
#endif
assert(BufferHead < BUFSIZE);
ssize_t n = read(filterout, Buffer+BufferHead, BUFSIZE-BufferHead);
if (n <= 0) {
if (n < 0) {
perror("read");
}
close(filterout);
filterout = -1;
return false;
}
//printf("read filtered %d\n", n);
for (list<Stream *>::iterator i = Clients.begin(); i != Clients.end(); ) {
if ((*i)->checkOverflow(n)) {
printf("closed client due to overflow\n");
delete *i;
i = Clients.erase(i);
} else {
i++;
}
}
BufferHead = (BufferHead + n) % BUFSIZE;
return true;
}
Listener::Listener()
{
s = socket(AF_INET, SOCK_STREAM, 0);
if (s < 0) {
perror("socket");
exit(1);
}
int one = 1;
if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) != 0) {
perror("setsockopt");
exit(1);
}
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(Config.Port);
addr.sin_addr.s_addr = INADDR_ANY;
if (bind(s, (sockaddr *)&addr, sizeof(addr)) != 0) {
perror("bind");
close(s);
exit(1);
}
if (listen(s, 5) != 0) {
perror("listen");
close(s);
exit(1);
}
}
Listener::~Listener()
{
close(s);
}
bool Listener::notifyRead()
{
#ifdef TRACE
if (Trace) printf("%d Listener::notifyRead\n", getpid());
#endif
sockaddr_in peer;
socklen_t n = sizeof(peer);
int t = accept(s, (sockaddr *)&peer, &n);
if (t < 0) {
perror("accept");
} else if (TotalClients >= Config.MaxClients) {
close(t);
printf("%s turned away\n", inet_ntoa(peer.sin_addr));
fprintf(Log, "%ld %s turned away\n", time(0), inet_ntoa(peer.sin_addr));
fflush(Log);
} else {
Clients.push_back(new Client(t, peer.sin_addr));
printf("%s connected\n", inet_ntoa(peer.sin_addr));
}
return true;
}
ShoutcastDirectory::ShoutcastDirectory()
: s(-1), id(0), nextupdate(0)
{
/* hmm this doesn't work
FILE *f = fopen((Config.ConfigFileName+".id").c_str(), "r");
if (f != NULL) {
fscanf(f, "%d", &id);
fclose(f);
printf("restored id %d from %s\n", id, (Config.ConfigFileName+".id").c_str());
}*/
}
ShoutcastDirectory::~ShoutcastDirectory()
{
if (s != -1) {
close(s);
}
}
int ShoutcastDirectory::getfd()
{
if (s != -1) {
if (time(0) < nextupdate+60) {
return s;
}
close(s);
s = -1;
}
if (time(0) >= nextupdate) {
nextupdate = time(0) + 60;
#ifdef TRACE
if (Trace) printf("%d updating directory\n", getpid());
#endif
s = socket(AF_INET, SOCK_STREAM, 0);
int one = 1;
if (ioctl(s, FIONBIO, &one) != 0) {
perror("ioctl");
close(s);
s = -1;
return -1;
}
sockaddr_in ds;
ds.sin_family = AF_INET;
ds.sin_port = htons(80);
ds.sin_addr.s_addr = inet_addr("205.188.234.56");
connect(s, (sockaddr *)&ds, sizeof(ds));
if (errno != EINPROGRESS) {
perror("connect");
close(s);
s = -1;
return -1;
}
connected = false;
return s;
}
return -1;
}
bool ShoutcastDirectory::needWritable()
{
return s != -1 && !connected;
}
bool ShoutcastDirectory::notifyRead()
{
#ifdef TRACE
if (Trace) printf("%d ShoutcastDirectory::notifyRead\n", getpid());
#endif
ssize_t n = read(s, buf+index, sizeof(buf)-index-1);
if (n <= 0) {
if (n < 0) {
perror("read");
} else {
assert(index < (ssize_t)sizeof(buf));
buf[index] = 0;
if (strstr(buf, "icy-response: ack") == NULL) {
printf("%s\n", buf);
}
if (id == 0) {
const char *p = strstr(buf, "icy-id:");
if (p != NULL) {
id = atoi(p+7);
}
p = strstr(buf, "icy-tchfrq:");
if (p != NULL) {
refresh = atoi(p+11) * 60;
}
if (id == 0) {
nextupdate = time(0) + 300;
} else {
printf("stream id %d (refresh %d)\n", id, refresh);
FILE *f = fopen((Config.ConfigFileName+".id").c_str(), "w");
if (f != NULL) {
fprintf(f, "%d\n", id);
fclose(f);
} else {
perror("fopen id");
}
nextupdate = time(0);
}
} else {
nextupdate = time(0) + refresh;
}
}
close(s);
s = -1;
return true;
}
index += n;
return true;
}
bool ShoutcastDirectory::notifyWrite()
{
int err;
socklen_t n;
if (getsockopt(s, SOL_SOCKET, SO_ERROR, &err, &n) != 0) {
perror("getsockopt");
close(s);
s = -1;
return true;
}
if (err != 0) {
fprintf(stderr, "connect: %s\n", strerror(err));
close(s);
s = -1;
return true;
}
#ifdef TRACE
if (Trace) printf("%d connected\n", getpid());
#endif
connected = true;
index = 0;
char buf[1024];
if (id == 0) {
snprintf(buf, sizeof(buf), "GET /addsrv?v=1&br=16&p=%d&m=%d&t=%s&g=%s&url=%s&irc=%s&aim=%s&icq=%s HTTP/1.0\r\nHost: yp.shoutcast.com\r\n\r\n",
Config.Port,
Config.MaxClients,
HttpEscape(Config.Name).c_str(),
HttpEscape(Config.Genre).c_str(),
HttpEscape(Config.URL).c_str(),
HttpEscape(Config.IRC).c_str(),
HttpEscape(Config.AIM).c_str(),
HttpEscape(Config.ICQ).c_str()
);
} else {
snprintf(buf, sizeof(buf), "GET /cgi-bin/tchsrv?id=%d&p=%d&li=%d&alt=0&ct=%s HTTP/1.0\r\nHost: yp.shoutcast.com\r\n\r\n",
id,
Config.Port,
TotalClients,
HttpEscape(Title).c_str());
}
if (write(s, buf, strlen(buf)) < (ssize_t)strlen(buf)) {
perror("write");
close(s);
s = -1;
return true;
}
return true;
}
Client::Client(int f, in_addr p)
: fd(f), peer(p), start(time(0)), streaming(false), index(0)
{
TotalClients++;
fprintf(Log, "%ld %s connected\n", time(0), inet_ntoa(peer));
fflush(Log);
}
Client::~Client()
{
close(fd);
TotalClients--;
fprintf(Log, "%ld %s disconnected (%ld seconds)\n", time(0), inet_ntoa(peer), time(0)-start);
fflush(Log);
}
bool Client::needWritable()
{
return streaming && tail != BufferHead;
}
bool Client::notifyRead()
{
#ifdef TRACE
if (Trace) printf("%d Client::notifyRead\n", getpid());
#endif
int n = read(fd, request+index, sizeof(request)-index-1);
if (n <= 0) {
if (n < 0) {
perror("read");
}
return false;
}
index += n;
//printf("header: %.*s", Clients[i].index, Clients[i].request);
if (index > 4 && strncmp(request+index-4, "\r\n\r\n", 4) == 0 || strncmp(request+index-2, "\n\n", 2) == 0) {
request[index] = 0;
char *method = strtok(request, " ");
char *url = strtok(NULL, " ");
char response[1024];
bool streamit = false;
if (strcmp(url, "/") == 0) {
snprintf(response, sizeof(response),
"ICY 200 OK\r\n"
"Content-Type: %s\r\n"
//"icy-notice1: <BR>This stream requires <a href=\"http://www.winamp.com/\">Winamp</a><BR>\r\n"
//"icy-notice2: SHOUTcast Distributed Network Audio Server/posix v1.x.x\r\n"
"icy-name: %s\r\n"
"icy-genre: %s\r\n"
"icy-url: %s\r\n"
"icy-pub: 1\r\n"
"icy-br: 16\r\n"
"\r\n",
Config.ContentType.c_str(),
Config.Name.c_str(),
Config.Genre.c_str(),
Config.URL.c_str()
);
streamit = true;
} else if (strcmp(url, "/nwr.spx") == 0) {
snprintf(response, sizeof(response),
"HTTP/1.0 200 OK\r\n"
"Content-Type: %s\r\n"
"ice-name: %s\r\n"
"ice-genre: %s\r\n"
"ice-url: %s\r\n"
"ice-public: 1\r\n"
"ice-bitrate: 16\r\n"
"\r\n",
Config.ContentType.c_str(),
Config.Name.c_str(),
Config.Genre.c_str(),
Config.URL.c_str()
);
streamit = true;
} else if (strcmp(url, "/nwr.ogg") == 0) {
snprintf(response, sizeof(response),
"HTTP/1.0 200 OK\r\n"
"Content-Type: %s\r\n"
"ice-name: %s\r\n"
"ice-genre: %s\r\n"
"ice-url: %s\r\n"
"ice-public: 1\r\n"
"ice-bitrate: 16\r\n"
"\r\n",
Config.ContentType.c_str(),
Config.Name.c_str(),
Config.Genre.c_str(),
Config.URL.c_str()
);
streamit = true;
} else if (strcmp(url, "/playlist.pls") == 0) {
snprintf(response, sizeof(response),
"HTTP/1.0 200 OK\r\n"
"Content-Type: audio/x-scpls\r\n"
"\r\n"
"[playlist]\r\n"
"numberofentries=1\r\n"
"File1=http://%s:%d\r\n",
Config.Server.c_str(),
Config.Port);
} else {
snprintf(response, sizeof(response),
"HTTP/1.0 404 Not Found\r\n"
"\r\n");
}
n = write(fd, response, strlen(response));
if (n <= 0) {
perror("write");
return false;
}
if (strcmp(method, "GET") == 0 && streamit) {
streaming = true;
tail = BufferHead;
} else {
return false;
}
}
return true;
}
bool Client::notifyWrite()
{
int bytes = (BufferHead > tail ? BufferHead : BUFSIZE) - tail;
ssize_t n = write(fd, Buffer+tail, bytes);
//printf("write %d\n", n);
if (n < 0) {
if (errno != EAGAIN) {
perror("write");
printf("closed client\n");
return false;
}
} else {
tail = (tail + n) % BUFSIZE;
}
return true;
}
bool Client::checkOverflow(int n)
{
if (streaming && tail != BufferHead) {
int free = (tail + BUFSIZE - BufferHead) % BUFSIZE;
if (free <= n) {
return true;
}
}
return false;
}
int main(int argc, char *argv[])
{
string config = "streamer.conf";
int a = 1;
while (a < argc && argv[a][0] == '-' && argv[a][1] != 0) {
switch (argv[a][1]) {
case 'c':
if (argv[a][2]) {
config = argv[a]+2;
} else {
a++;
config = argv[a];
}
break;
#ifdef TRACE
case 't':
Trace = true;
break;
#endif
default:
fprintf(stderr, "%s: unknown option %c\n", argv[0], argv[a][1]);
exit(1);
}
a++;
}
signal(SIGPIPE, SIG_IGN);
LoadConfig(config.c_str());
Log = fopen(Config.Log.c_str(), "a");
Clients.push_back(new RawInputStream());
Clients.push_back(new Listener());
if (!Config.Name.empty()) {
Clients.push_back(new TitleMonitor());
Clients.push_back(new ShoutcastDirectory());
}
for (;;) {
fd_set rfds;
fd_set wfds;
FD_ZERO(&rfds);
FD_ZERO(&wfds);
int maxfd = -1;
#ifdef TRACE
if (Trace) printf("%d setup\n", getpid());
#endif
for (list<Stream *>::iterator i = Clients.begin(); i != Clients.end(); i++) {
int fd = (*i)->getfd();
if (fd < 0) {
continue;
}
FD_SET(fd, &rfds);
if (fd > maxfd) {
maxfd = fd;
}
}
for (list<Stream *>::iterator i = Clients.begin(); i != Clients.end(); i++) {
if ((*i)->needWritable()) {
int fd = (*i)->getfd();
assert(fd >= 0);
FD_SET(fd, &wfds);
}
}
#ifdef TRACE
if (Trace) printf("%d select\n", getpid());
#endif
assert(maxfd >= 0);
int r = select(maxfd+1, &rfds, &wfds, NULL, NULL);
if (r < 0) {
perror("select");
break;
}
#ifdef TRACE
if (Trace) printf("%d identify\n", getpid());
#endif
vector<Stream *> readables, writables;
for (list<Stream *>::iterator i = Clients.begin(); i != Clients.end(); i++) {
int fd = (*i)->getfd();
if (fd < 0) {
continue;
}
if (FD_ISSET(fd, &rfds)) {
readables.push_back(*i);
}
if (FD_ISSET(fd, &wfds)) {
writables.push_back(*i);
}
}
#ifdef TRACE
if (Trace) printf("%d handle read\n", getpid());
#endif
for (vector<Stream *>::iterator i = readables.begin(); i != readables.end(); i++) {
if (!(*i)->notifyRead()) {
delete *i;
vector<Stream *>::iterator w = writables.begin();
while (w != writables.end()) {
if (*w == *i) {
break;
}
w++;
}
if (w != writables.end()) {
writables.erase(w);
}
Clients.remove(*i);
}
}
#ifdef TRACE
if (Trace) printf("%d handle write\n", getpid());
#endif
for (vector<Stream *>::iterator i = writables.begin(); i != writables.end(); i++) {
if (!(*i)->notifyWrite()) {
delete *i;
Clients.remove(*i);
}
}
#ifdef TRACE
if (Trace) {
printf("%d TotalClients=%d (%d)\n", getpid(), TotalClients, Clients.size());
printf("filterin=%d filterout=%d\n", filterin, filterout);
}
#endif
if (filterin == -1 && TotalClients > 0) {
printf("starting filter\n");
filter(filterpid, filterin, filterout);
Clients.push_back(new FilteredInputStream());
}
if (filterin != -1 && TotalClients == 0) {
printf("terminating filter\n");
close(filterin);
filterin = -1;
kill(filterpid, SIGTERM);
int status;
if (waitpid(filterpid, &status, 0) < 0) {
perror("waitpid");
exit(1);
}
filterpid = 0;
}
#ifdef TRACE
printf(" %d %ld %d %s\n", getpid(), time(0), TotalClients, config.c_str());
#else
printf(" %ld %d\r", time(0), TotalClients);
#endif
fflush(stdout);
}
return 0;
}