-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathtomcast.c
1325 lines (1221 loc) · 41.9 KB
/
tomcast.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
/*
* tomcast
* Copyright (C) 2010-2013 Unix Solutions Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* 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 (COPYING file) for more details.
*
*/
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <errno.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <signal.h>
#include <fcntl.h>
#include <regex.h>
#include <netdb.h> // for uint32_t
#include "libfuncs/libfuncs.h"
#include "bitstream.h"
#include "config.h"
#include "web_server.h"
#define DNS_RESOLVER_TIMEOUT 5000
#define FDGETLINE_TIMEOUT 500
#define FDGETLINE_RETRIES 30
#define FDREAD_TIMEOUT 1500
#define FDREAD_RETRIES 7
#define FDWRITE_TIMEOUT 1500
#define FDWRITE_RETRIES 7
/* How much to wait for connection to be established with channel source (miliseconds) */
#define PROXY_CONNECT_TIMEOUT 1000
/* Seconds to sleep between retries (miliseconds) */
#define PROXY_RETRY_TIMEOUT 1000
#define TRANSPORT_PACKET_SIZE 188
#define TRANSPORT_EXTEDED_PACKET_SIZE 192
#define TRANSPORT_PACKETS_PER_NETWORK_PACKET 7
#define TRANSPORT_SYNC_BYTE 0x47
#define FRAME_PACKET_SIZE (TRANSPORT_PACKET_SIZE * TRANSPORT_PACKETS_PER_NETWORK_PACKET)
#ifndef FREE
#define FREE(x) if(x) { free(x); x=NULL; }
#endif
#ifndef POLLRDHUP
#define POLLRDHUP 0
#endif
char *server_sig = "tomcast";
char *server_ver = "1.40";
char *copyright = "Copyright (C) 2010-2018 Unix Solutions Ltd.";
static struct config config;
#ifdef __MACH__
#include <mach/clock.h>
#include <mach/mach.h>
#endif
int64_t get_time(void) {
struct timespec ts;
#ifdef __MACH__
// OS X does not have clock_gettime, use clock_get_time
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
ts.tv_sec = mts.tv_sec;
ts.tv_nsec = mts.tv_nsec;
#else
if (clock_gettime(CLOCK_MONOTONIC, &ts) == EINVAL) // Shouldn't happen on modern Linux
clock_gettime(CLOCK_REALTIME, &ts);
#endif
return ts.tv_sec * 1000000ll + ts.tv_nsec / 1000;
}
channel_source get_sproto(char *url) {
return strncmp(url, "http", 4)==0 ? tcp_sock : udp_sock;
}
CHANSRC *init_chansrc(char *url) {
regex_t re;
regmatch_t res[5];
regcomp(&re, "^([a-z]+)://([^:/?]+):?([0-9]*)/?(.*)", REG_EXTENDED);
if (regexec(&re,url,5,res,0)==0) {
char *data = strdup(url);
char *proto, *host, *port, *path;
int iport;
proto= data+res[1].rm_so; data[res[1].rm_eo]=0;
host = data+res[2].rm_so; data[res[2].rm_eo]=0;
port = data+res[3].rm_so; data[res[3].rm_eo]=0;
path = data+res[4].rm_so; data[res[4].rm_eo]=0;
iport = atoi(port);
/* Setup */
CHANSRC *src = calloc(1, sizeof(CHANSRC));
src->proto = strdup(proto);
src->sproto= get_sproto(url);
src->host = strdup(host);
src->port = iport ? iport : 80;
src->path = strdup(path);
FREE(data);
regfree(&re);
return src;
}
regfree(&re);
return NULL;
}
void free_chansrc(CHANSRC *url) {
if (url) {
FREE(url->proto);
FREE(url->host);
FREE(url->path);
FREE(url);
}
};
int is_valid_url(char *url) {
regex_t re;
regmatch_t res[5];
int ret;
regcomp(&re, "^([a-z]+)://([^:/?]+):?([0-9]*)/?(.*)", REG_EXTENDED);
ret = regexec(&re,url,5,res,0);
regfree(&re);
return ret == 0;
}
void add_channel_source(CHANNEL *c, char *src) {
if (c->num_src >= MAX_CHANNEL_SOURCES-1)
return;
c->sources[c->num_src] = strdup(src);
if (c->num_src == 0) /* Set default source to first one */
c->source = c->sources[c->num_src];
c->num_src++;
}
void next_channel_source(CHANNEL *c) {
if (c->num_src <= 1)
return;
// uint8_t old_src = c->curr_src;
c->curr_src++;
if (c->curr_src >= MAX_CHANNEL_SOURCES-1 || c->sources[c->curr_src] == NULL)
c->curr_src = 0;
c->source = c->sources[c->curr_src];
// LOGf("CHAN : Switch source | Channel: %s OldSrc: %d %s NewSrc: %d %s\n", c->name, old_src, c->sources[old_src], c->curr_src, c->source);
}
void set_channel_source(CHANNEL *c, uint8_t src_id) {
if (src_id >= MAX_CHANNEL_SOURCES-1 || c->sources[src_id] == NULL)
return;
// uint8_t old_src = c->curr_src;
c->curr_src = src_id;
c->source = c->sources[c->curr_src];
// LOGf("CHAN : Set source | Channel: %s OldSrc: %d %s NewSrc: %d %s\n", c->name, old_src, c->sources[old_src], c->curr_src, c->source);
}
CHANNEL * new_channel(char *name, char *source, char *dest, int port) {
CHANNEL *c = calloc(1, sizeof(CHANNEL));
c->name = strdup(name);
c->dest_host = strdup(dest);
c->dest_port = port;
add_channel_source(c, source);
return c;
}
void free_channel(CHANNEL *c) {
int i;
for (i=c->num_src-1; i>=0; i--) {
FREE(c->sources[i]);
}
FREE(c->name);
FREE(c->dest_host);
c->source = NULL;
FREE(c);
}
void free_channel_p(void *c) {
free_channel(c);
}
int send_reset_opt = 0;
int multicast_ttl = 1;
int init_chan_stop_opt = 0;
struct in_addr output_intf = { .s_addr = INADDR_ANY };
int connect_multicast(struct sockaddr_in send_to) {
int sendsock = socket(AF_INET, SOCK_DGRAM, 0);
if (sendsock < 0) {
LOGf("socket(SOCK_DGRAM): %s\n", strerror(errno));
return -1;
}
int on = 1;
setsockopt(sendsock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
// subscribe to multicast group
// LOGf("Using ttl %d\n", multicast_ttl);
if (IN_MULTICAST(ntohl(send_to.sin_addr.s_addr))) {
if (setsockopt(sendsock, IPPROTO_IP, IP_MULTICAST_TTL, &multicast_ttl, sizeof(multicast_ttl)) < 0) {
LOGf("setsockopt(IP_MUTICAST_TTL): %s\n", strerror(errno));
close(sendsock);
return -1;
}
if (setsockopt(sendsock, IPPROTO_IP, IP_MULTICAST_IF, &output_intf, sizeof(output_intf)) < 0) {
LOGf("setsockopt(IP_MUTICAST_IF, %s): %s\n", strerror(errno), inet_ntoa(output_intf));
close(sendsock);
return -1;
}
}
int writebuflen = FRAME_PACKET_SIZE * 1000;
if (setsockopt(sendsock, SOL_SOCKET, SO_SNDBUF, (const char *)&writebuflen, sizeof(writebuflen)) < 0)
log_perror("setsockopt(): setsockopt(SO_SNDBUF)", errno);
// call connect to get errors
if (connect(sendsock, (struct sockaddr *)&send_to, sizeof send_to)) {
LOGf("udp_connect() error: %s\n", strerror(errno));
close(sendsock);
return -1;
}
return sendsock;
}
void proxy_set_status(RESTREAMER *r, const char *proxy_status) {
pthread_rwlock_wrlock(&r->lock);
snprintf(r->status, sizeof(r->status), "%s", proxy_status);
pthread_rwlock_unlock(&r->lock);
}
void connect_destination(RESTREAMER *r) {
CHANNEL *c = r->channel;
if (r->clientsock >= 0)
shutdown_fd(&(r->clientsock));
r->clientsock = connect_multicast(r->dst_sockname);
LOGf("CONN : Connected dst_fd: %i | Chan: %s Dest: udp://%s:%d\n", r->clientsock, c->name, c->dest_host, c->dest_port);
}
RESTREAMER * new_restreamer(const char *name, CHANNEL *channel) {
int active = 1;
struct sockaddr_in sockname;
int dret = async_resolve_host(channel->dest_host, channel->dest_port, &sockname, DNS_RESOLVER_TIMEOUT, &active);
if (dret != 0) {
if (dret == 1)
LOGf("ERR : Can't resolve host | Chan: %s Dest: udp://%s:%d\n", channel->name, channel->dest_host, channel->dest_port);
if (dret == 2)
LOGf("ERR : DNS timeout | Chan: %s Dest: udp://%s:%d\n", channel->name, channel->dest_host, channel->dest_port);
return NULL;
}
RESTREAMER *r = calloc(1, sizeof(RESTREAMER));
r->name = strdup(name);
r->sock = -1;
r->channel = channel;
r->clientsock = -1;
r->dst_sockname = sockname;
r->hibernate = init_chan_stop_opt;
pthread_rwlock_init(&r->lock, NULL);
connect_destination(r);
r->last_decrypted_input_ts = get_time();
return r;
}
void free_restreamer(RESTREAMER *r) {
if (r->sock > -1)
shutdown_fd(&(r->sock));
if (r->freechannel)
free_channel(r->channel);
FREE(r->name);
FREE(r);
}
char TS_NULL_FRAME[FRAME_PACKET_SIZE];
regex_t http_response;
void proxy_log(RESTREAMER *r, char *msg, char *info) {
LOGf("%s: %s Chan: %s Src: %s Dst: udp://%s:%d SrcIP: %s SrcFD: %i DstFD: %i\n",
msg,
info,
r->channel->name,
r->channel->source,
r->channel->dest_host,
r->channel->dest_port,
inet_ntoa(r->src_sockname.sin_addr),
r->sock,
r->clientsock
);
}
int load_channels_config(struct config *cfg) {
regex_t re;
regmatch_t res[5];
char line[1024];
int fd;
int num_channels = 0;
if (pthread_mutex_trylock(&cfg->channels_lock) != 0)
return -1;
fd = open(cfg->channels_file, O_RDONLY);
if (fd != -1) {
struct timeval tv;
gettimeofday(&tv, NULL);
unsigned int randstate = tv.tv_usec;
int cookie = rand_r(&randstate);
regcomp(&re, "^([A-Za-z0-9]+)\t+([0-9.]+):([0-9]+)\t+(.*)", REG_EXTENDED);
LIST *old_chanconf;
LIST *new_chanconf = list_new("chanconf");
while (fdgetline(fd,line,sizeof(line)) > 0) {
chomp(line);
if (regexec(&re,line,5,res,0)==0) {
char *name, *dest_host, *dest_port, *source;
char *org = strdup(line);
name = org+res[1].rm_so; org[res[1].rm_eo]=0;
dest_host = org+res[2].rm_so; org[res[2].rm_eo]=0;
dest_port = org+res[3].rm_so; org[res[3].rm_eo]=0;
source = org+res[4].rm_so; org[res[4].rm_eo]=0;
if (!is_valid_url(source)) {
LOGf("CONF : Invalid url: %s\n", source);
FREE(org);
goto report_error;
}
/* Search for already added channel */
LNODE *l, *tmp;
CHANNEL *chan = NULL;
list_for_each_reverse(new_chanconf, l, tmp) {
if (strcmp(name, ((CHANNEL *)l->data)->name)==0) {
chan = l->data;
break;
}
}
if (!chan) {
list_add(new_chanconf, new_channel(name, source, dest_host, atoi(dest_port)));
num_channels++;
} else {
add_channel_source(chan, source);
}
FREE(org);
} else {
report_error:
if (strlen(line) > 2 && line[0] != '#') {
LOGf("CONF : Invalid config line: %s\n", line);
}
}
}
regfree(&re);
shutdown_fd(&fd);
/* Save current chanconf */
old_chanconf = cfg->chanconf;
/* Switch chanconf */
cfg->chanconf = new_chanconf;
/* Rewrite restreamer channels */
LNODE *lc, *lr, *lctmp, *lrtmp;
CHANNEL *chan;
list_lock(cfg->restreamer); // Unlocked after second list_for_each(restreamer)
list_lock(cfg->chanconf);
list_for_each(cfg->chanconf, lc, lctmp) {
chan = lc->data;
list_for_each(cfg->restreamer, lr, lrtmp) {
if (strcmp(chan->name, ((RESTREAMER *)lr->data)->name)==0) {
RESTREAMER *restr = lr->data;
/* Mark the restreamer as valid */
restr->cookie = cookie;
/* Check if current source exists in new channel configuration */
int i, src_found = -1;
char *old_source = restr->channel->source;
for (i=0; i<chan->num_src; i++) {
if (strcmp(old_source, chan->sources[i]) == 0) {
src_found = i;
}
}
if (src_found > -1) {
/* New configuration contains existing source, just update the reference */
set_channel_source(chan, src_found);
restr->channel = chan;
} else {
/* New configuration *DO NOT* contain existing source. Force reconnect */
LOGf("PROXY: Source changed | Channel: %s srv_fd: %d Old:%s New:%s\n", chan->name, restr->sock, restr->channel->source, chan->source);
/* The order is important! */
set_channel_source(chan, chan->num_src-1); /* Set source to last one. On reconnect next source will be used. */
restr->channel = chan;
restr->reconnect = 1;
}
break;
}
}
}
list_unlock(cfg->chanconf);
/* Kill restreamers that serve channels that no longer exist */
list_for_each(cfg->restreamer, lr, lrtmp) {
RESTREAMER *r = lr->data;
/* This restreamer should no longer serve clients */
if (r->cookie != cookie) {
proxy_log(r, "CLEAR", "Channel removed ");
/* Replace channel reference with real object and instruct free_restreamer to free it */
r->channel = new_channel(r->channel->name, r->channel->source, r->channel->dest_host, r->channel->dest_port);
r->freechannel = 1;
r->dienow = 1;
}
}
list_unlock(cfg->restreamer);
/* Free old_chanconf */
list_free(&old_chanconf, free_channel_p, NULL);
} else {
num_channels = -1;
}
pthread_mutex_unlock(&cfg->channels_lock);
if (num_channels == -1)
LOGf("CONF : Error loading channels!\n");
else
LOGf("CONF : %d channels loaded\n", num_channels);
return num_channels;
}
void proxy_close(RESTREAMER *r) {
proxy_log(r, "STOP ","-");
// If there are no clients left, no "Timeout" messages will be logged
list_del_entry(config.restreamer, r);
free_restreamer(r);
}
/*
On the last try, send no-signal to clients and exit
otherwise wait a little bit before trying again
*/
#define DO_RECONNECT do \
{ \
free_chansrc(src); \
if (retries == 0) { \
return -1; \
} else { \
if (errno != EHOSTUNREACH) /* When host is unreachable there is already a delay of ~4 secs per try so no sleep is needed */ \
usleep(PROXY_RETRY_TIMEOUT * 1000); \
return 1; \
} \
} while(0)
#define FATAL_ERROR do \
{ \
free_chansrc(src); \
return -1; \
} while (0)
/*
Returns:
-1 = exit thread
1 = retry
0 = connected ok
*/
int connect_source(RESTREAMER *r, int retries, int readbuflen, int *http_code, char *url, int depth) {
CHANSRC *src = init_chansrc(url);
if (depth > 4) {
LOGf("ERR : Redirect loop detected, depth: %d | Channel: %s Source: %s\n", depth, r->channel->name, url);
FATAL_ERROR;
}
if (!src) {
LOGf("ERR : Can't parse channel source | Channel: %s Source: %s\n", r->channel->name, r->channel->source);
FATAL_ERROR;
}
r->connected = 0;
r->reconnect = 0;
int active = 1;
int dret = async_resolve_host(src->host, src->port, &(r->src_sockname), DNS_RESOLVER_TIMEOUT, &active);
if (dret != 0) {
if (dret == 1) {
proxy_log(r, "ERR ","Can't resolve src host");
proxy_set_status(r, "ERROR: Can not resolve source host");
}
if (dret == 2) {
proxy_log(r, "ERR ","Timeout resolving src host");
proxy_set_status(r, "ERROR: Dns resolve timeout");
}
DO_RECONNECT;
}
char buf[1024];
*http_code = 0;
if (src->sproto == tcp_sock) {
r->sock = socket(PF_INET, SOCK_STREAM, 0);
if (r->sock < 0) {
log_perror("play(): Could not create SOCK_STREAM socket.", errno);
FATAL_ERROR;
}
if (depth == 0) {
proxy_log(r, "NEW ", "-");
} else {
proxy_log(r, "NEW ", url);
}
if (do_connect(r->sock, (struct sockaddr *)&(r->src_sockname), sizeof(r->src_sockname), PROXY_CONNECT_TIMEOUT) < 0) {
LOGf("ERR : Error connecting to %s srv_fd: %i err: %s\n", r->channel->source, r->sock, strerror(errno));
proxy_set_status(r, "ERROR: Can not connect to source");
DO_RECONNECT;
}
snprintf(buf,sizeof(buf)-1, "GET /%s HTTP/1.0\r\nHost: %s:%u\r\nX-Smart-Client: yes\r\nUser-Agent: %s %s (%s)\r\n\r\n",
src->path, src->host, src->port, server_sig, server_ver, config.ident);
buf[sizeof(buf)-1] = 0;
fdwrite(r->sock, buf, strlen(buf));
char redirect_to[1024];
memset(redirect_to, 0, sizeof(redirect_to));
char xresponse[128];
memset(xresponse, 0, sizeof(xresponse));
memset(buf, 0, sizeof(buf));
regmatch_t res[4];
while (fdgetline(r->sock,buf,sizeof(buf)-1)) {
if (buf[0] == '\n' || buf[0] == '\r')
break;
if (strstr(buf,"HTTP/1.") != NULL) {
if (regexec(&http_response,buf,3,res,0) != REG_NOMATCH) {
char codestr[4];
if ((unsigned long)(res[1].rm_eo - res[1].rm_so) < sizeof(xresponse)) {
strncpy(xresponse, &buf[res[1].rm_so], res[1].rm_eo-res[1].rm_so);
xresponse[res[1].rm_eo-res[1].rm_so] = '\0';
chomp(xresponse);
strncpy(codestr, &buf[res[2].rm_so], res[2].rm_eo-res[2].rm_so);
codestr[3] = 0;
*http_code = atoi(codestr);
}
}
}
if (*http_code == 504) { // Extract extra error code
if (strstr(buf, "X-ErrorCode: ") != NULL) {
*http_code = atoi(buf+13);
break;
}
}
if (strstr(buf, "Location: ") == buf) {
// Remove new line
char *new_line = strchr(buf, '\r');
if (new_line) *new_line = '\0';
new_line = strchr(buf, '\n');
if (new_line) *new_line = '\0';
snprintf(redirect_to, sizeof(redirect_to)-1, "%s", buf + 10);
if (strstr(redirect_to, "http://") != redirect_to) {
// Assume that the redirect is relative, add proto, host and port
snprintf(redirect_to, sizeof(redirect_to)-1, "http://%s:%d%s",
src->host, src->port, buf + 10);
LOGf("DEBUG: Converted relative location to: %s | srv_fd: %i\n", redirect_to, r->sock);
}
}
}
if (*http_code == 0) { // No valid HTTP response, retry
LOGf("DEBUG: Server returned not valid HTTP code | srv_fd: %i\n", r->sock);
proxy_set_status(r, "ERROR: Source returned invalid HTTP code");
DO_RECONNECT;
}
if (*http_code == 504) { // No signal, exit
LOGf("ERR : Get no-signal for %s from %s on srv_fd: %i\n", r->channel->name, r->channel->source, r->sock);
proxy_set_status(r, "ERROR: Source returned no-signal");
FATAL_ERROR;
}
if (*http_code == 301 || *http_code == 302) { // Handle redirects
if (redirect_to[0]) {
LOGf("REDIR: Get code %i for %s from %s on srv_fd: %i, handling redirect to: %s\n", *http_code, r->channel->name, r->channel->source, r->sock, redirect_to);
free_chansrc(src);
shutdown_fd(&(r->sock));
return connect_source(r, retries, readbuflen, http_code, redirect_to, ++depth);
}
// Redirect connect is OK, continue
} else if (*http_code > 300) { // Unhandled or error codes, exit
LOGf("ERR : Get code %i for %s from %s on srv_fd: %i exiting.\n", *http_code, r->channel->name, r->channel->source, r->sock);
proxy_set_status(r, "ERROR: Source returned unhandled error code");
FATAL_ERROR;
}
// connected ok, continue
} else {
if (!IN_MULTICAST(ntohl(r->src_sockname.sin_addr.s_addr))) {
LOGf("ERR : %s is not multicast address\n", r->channel->source);
FATAL_ERROR;
}
struct ip_mreq mreq;
struct sockaddr_in receiving_from;
r->sock = socket(PF_INET, SOCK_DGRAM, 0);
if (r->sock < 0) {
log_perror("play(): Could not create SOCK_DGRAM socket.", errno);
FATAL_ERROR;
}
LOGf("CONN : Listening on multicast socket %s srv_fd: %i retries left: %i\n", r->channel->source, r->sock, retries);
int on = 1;
setsockopt(r->sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
// subscribe to multicast group
memcpy(&mreq.imr_multiaddr, &(r->src_sockname.sin_addr), sizeof(struct in_addr));
mreq.imr_interface.s_addr = htonl(INADDR_ANY);
if (setsockopt(r->sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) {
LOGf("ERR : Failed to add IP membership on %s srv_fd: %i\n", r->channel->source, r->sock);
FATAL_ERROR;
}
// bind to the socket so data can be read
memset(&receiving_from, 0, sizeof(receiving_from));
receiving_from.sin_family = AF_INET;
receiving_from.sin_addr = r->src_sockname.sin_addr;
receiving_from.sin_port = htons(src->port);
if (bind(r->sock, (struct sockaddr *) &receiving_from, sizeof(receiving_from)) < 0) {
LOGf("ERR : Failed to bind to %s srv_fd: %i\n", r->channel->source, r->sock);
FATAL_ERROR;
}
}
if (setsockopt(r->sock, SOL_SOCKET, SO_RCVBUF, (const char *)&readbuflen, sizeof(readbuflen)) < 0)
log_perror("play(): setsockopt(SO_RCVBUF)", errno);
proxy_set_status(r, "Connected");
r->connected = 1;
free_chansrc(src);
return 0;
}
int check_restreamer_state(RESTREAMER *r) {
if (r->dienow) {
// LOGf("PROXY: Forced disconnect on srv_fd: %i | Channel: %s Source: %s\n", r->sock, r->channel->name, r->channel->source);
proxy_set_status(r, "Dying");
return 2;
}
if (r->hibernate) {
proxy_set_status(r, "Hibernating");
return 3;
}
if (r->reconnect) {
LOGf("PROXY: Forced reconnect on srv_fd: %i | Channel: %s Source: %s\n", r->sock, r->channel->name, r->channel->source);
proxy_set_status(r, "Forced reconnect");
return 1;
}
return 0;
}
/*
Returns:
-1 = channel not found
0 = channel not changed the hibernation status
N = channel updated
*/
int set_hibernate(int k, const char *channel) {
int found = -1;
int i = 0;
LNODE *lr, *lrtmp;
list_lock(config.restreamer);
list_for_each(config.restreamer, lr, lrtmp)
{
RESTREAMER *r = lr->data;
i++;
if(strcmp(r->channel->name,channel) == 0)
{
found = i;
if (!r->hibernate && k == 1) {
r->hibernate = 1;
proxy_set_status(r, "Hibernating");
break;
}
if (r->hibernate && k == 0) {
r->hibernate = 0;
r->reconnect = 1;
LOGf("DEBUG: restarting from hibernation | Channel: %s\n", r->channel->name);
proxy_set_status(r, "Reconnecting");
break;
}
found = 0;
break;
}
}
list_unlock(config.restreamer);
//LOGf("DEBUG: Call to set_hibernate(%i,%s) and return: %i\n", k, channel, found);
return found;
}
#define MAX_ZERO_READS 3
/* Start: 3 seconds on connect */
/* In connection: Max UDP timeout == 3 seconds (read) + 2 seconds (connect) == 5 seconds */
#define UDP_READ_RETRIES 3
#define UDP_READ_TIMEOUT 1000
/* Start: 1/4 seconds on connect */
/* In connection: Max TCP timeout == 5 seconds (read) + 2 seconds (connect) == 7 seconds */
/* In connection: Max TCP timeout == 5 seconds (read) + 8 seconds (connect, host unrch) == 13 seconds */
#define TCP_READ_RETRIES 5
#define TCP_READ_TIMEOUT 1000
/*
Returns:
0 = synced ok
1 = not synced, reconnect
*/
int mpeg_sync(RESTREAMER *r, int proxysock, char *channel, channel_source source_proto) {
time_t sync_start = time(NULL);
unsigned int sync_packets = 0;
unsigned int read_bytes = 0;
char syncframe[188];
int _timeout = TCP_READ_TIMEOUT;
int _retries = TCP_READ_RETRIES;
if (source_proto == udp_sock) {
_timeout = UDP_READ_TIMEOUT;
_retries = UDP_READ_RETRIES;
}
do {
resync:
if (fdread_ex(proxysock, syncframe, 1, _timeout, _retries, 1) != 1) {
LOGf("DEBUG: mpeg_sync fdread() timeout | Channel: %s\n", channel);
proxy_set_status(r, "ERROR: fdread() timeout while syncing mpeg");
return 1; // reconnect
}
// LOGf("DEBUG: Read 0x%02x Offset %u Sync: %u\n", (uint8_t)syncframe[0], read_bytes, sync_packets);
read_bytes++;
if (syncframe[0] == 0x47) {
ssize_t rdsz = fdread_ex(proxysock, syncframe, 188-1, _timeout, _retries, 1);
if (rdsz != 188-1) {
LOGf("DEBUG: mpeg_sync fdread() timeout | Channel: %s\n", channel);
proxy_set_status(r, "ERROR: fdread() timeout while syncing mpeg");
return 1; // reconnect
}
read_bytes += 188-1;
if (++sync_packets == 7) // sync 7 packets
break;
goto resync;
} else {
sync_packets = 0;
}
if (read_bytes > FRAME_PACKET_SIZE) { // Can't sync in 1316 bytes
LOGf("DEBUG: Can't sync after %d bytes | Channel: %s\n", FRAME_PACKET_SIZE, channel);
proxy_set_status(r, "ERROR: Can not sync mpeg");
return 1; // reconnect
}
if (sync_start+2 <= time(NULL)) { // Do not sync in two seconds
LOGf("DEBUG: Timeout while syncing (read %u bytes) | Channel: %s\n", read_bytes, channel);
proxy_set_status(r, "ERROR: Timeout while syncing mpeg");
return 1; // reconnect
}
} while (1);
pthread_rwlock_wrlock(&r->lock);
r->conn_ts = time(NULL);
r->read_bytes = read_bytes;
pthread_rwlock_unlock(&r->lock);
LOGf("SYNC : TS synced after %u bytes | Channel: %s\n", read_bytes-FRAME_PACKET_SIZE, channel);
proxy_set_status(r, "Working");
return 0;
}
char reset[FRAME_PACKET_SIZE] = {
0x47,0x40,0x00,0x10,0x00,0x00,0xB0,0x09,0x27,0x10,0xC1,0x00,
0x00,0x3C,0xDD,0xFF,0xB8,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x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02 - PTS was found
ret & 0x04 == 0x04 - DTS was found
*/
static unsigned int ts_have_valid_pes(uint8_t *buf, unsigned int buffer_size) {
unsigned int ret = 0;
uint8_t *buf_end = buf + buffer_size;
while (buf < buf_end && ts_validate(buf)) {
uint16_t header_size = TS_HEADER_SIZE + (ts_has_adaptation(buf) ? 1 : 0) + ts_get_adaptation(buf);
if (ts_get_unitstart(buf) && ts_has_payload(buf) && header_size + PES_HEADER_SIZE_PTS <= TS_SIZE) {
//printf("Got payload\n");
if (pes_validate(buf + header_size) && pes_get_streamid(buf + header_size) != PES_STREAM_ID_PRIVATE_2 && pes_validate_header(buf + header_size)) {
//printf("Got PES\n");
ret |= 0x01;
if (pes_has_pts(buf + header_size) && pes_validate_pts(buf + header_size)) {
ret |= 0x02;
//printf("Got PTS\n");
if (header_size + PES_HEADER_SIZE_PTSDTS <= TS_SIZE && pes_has_dts(buf + header_size) && pes_validate_dts(buf + header_size)) {
//printf("Got DTS\n");
ret |= 0x04;
}
}
}
}
buf += TS_SIZE;
}
return ret;
}
void * proxy_ts_stream(void *self) {
RESTREAMER *r = self;
char buf[FRAME_PACKET_SIZE];
signal(SIGPIPE, SIG_IGN);
proxy_set_status(r, "Initialized");
int http_code = 0;
while (1) {
r->conn_ts = 0;
r->read_bytes = 0;
if (r->hibernate) {
sleep(1);
continue;
}
int result = connect_source(self, 1, FRAME_PACKET_SIZE * 1000, &http_code, r->channel->source, 0);
if (result > 0)
goto RECONNECT;
channel_source sproto = get_sproto(r->channel->source);
int mpgsync = mpeg_sync(r, r->sock, r->channel->name, sproto);
if (mpgsync == 1) // Timeout
goto RECONNECT;
ssize_t readen, written;
int max_zero_reads = MAX_ZERO_READS;
int send_reset = send_reset_opt;
for (;;) {
switch (check_restreamer_state(r)) {
case 1: goto RECONNECT; // r->reconnect is on
case 2: goto QUIT; // r->dienow is on
case 3: goto HIBERNATE; // r->hibernate is on
}
if (sproto == tcp_sock) {
readen = fdread_ex(r->sock, buf, FRAME_PACKET_SIZE, TCP_READ_TIMEOUT, TCP_READ_RETRIES, 1);
} else {
readen = fdread_ex(r->sock, buf, FRAME_PACKET_SIZE, UDP_READ_TIMEOUT, UDP_READ_RETRIES, 0);
}
if (readen < 0)
goto RECONNECT;
if (readen == 0) { // ho, hum, wtf is going on here?
LOGf("PROXY: zero read on srv_fd: %i | Channel: %s Source: %s\n", r->sock, r->channel->name, r->channel->source);
if (--max_zero_reads == 0) {
LOGf("PROXY: %d zero reads on srv_fd: %i | Channel: %s Source: %s\n", MAX_ZERO_READS, r->sock, r->channel->name, r->channel->source);
proxy_set_status(r, "ERROR: Too many zero reads");
break;
}
continue;
}
max_zero_reads = MAX_ZERO_READS;
// Fill short frame with NULL packets
if (readen < FRAME_PACKET_SIZE) {
//LOGf("DEBUG: Short read (%d) on retreamer srv_fd: %i | Channel: %s\n", readen, sock, chan->name);
memcpy(buf+readen, TS_NULL_FRAME+readen, FRAME_PACKET_SIZE - readen);
}
pthread_rwlock_wrlock(&r->lock);
r->read_bytes += readen;
pthread_rwlock_unlock(&r->lock);
if (send_reset) {
send_reset = 0;
fdwrite(r->clientsock, reset, FRAME_PACKET_SIZE);
}
if (config.detect_encrypted_input) {
int64_t now = get_time();
int ret;
if ((ret = ts_have_valid_pes((uint8_t *)buf, readen)) == 0) { // Is the output encrypted?
/* The output is encrypted, check if 1000 ms have passed and if such, notify that we probably have invalid key */
if (now > r->last_decrypted_input_ts + 500000) {
proxy_log(r, "ERR ","Scrambled input");
proxy_set_status(r, "ERROR: Encrypted stream input");
goto RECONNECT;
}
} else {
r->last_decrypted_input_ts = now;
}
}
written = fdwrite(r->clientsock, buf, FRAME_PACKET_SIZE);
if (written == -1) {
LOGf("PROXY: Error writing to dst_fd: %i on srv_fd: %i | Channel: %s Source: %s\n", r->clientsock, r->sock, r->channel->name, r->channel->source);