tomcast reads mpeg transport streams over http or udp (multicast or unicast) and outputs them to chosen multicast group. Basically a simple http2multicast daemon designed to work 24/7.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

tomcast.c 35KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126
  1. /*
  2. * tomcast
  3. * Copyright (C) 2010-2013 Unix Solutions Ltd.
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License version 2
  7. * as published by the Free Software Foundation.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License (COPYING file) for more details.
  13. *
  14. */
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include <unistd.h>
  18. #include <string.h>
  19. #include <pthread.h>
  20. #include <errno.h>
  21. #include <arpa/inet.h>
  22. #include <netinet/in.h>
  23. #include <sys/types.h>
  24. #include <sys/socket.h>
  25. #include <sys/types.h>
  26. #include <sys/stat.h>
  27. #include <sys/time.h>
  28. #include <signal.h>
  29. #include <fcntl.h>
  30. #include <regex.h>
  31. #include <netdb.h> // for uint32_t
  32. #include "libfuncs/libfuncs.h"
  33. #define DNS_RESOLVER_TIMEOUT 5000
  34. #define FDGETLINE_TIMEOUT 500
  35. #define FDGETLINE_RETRIES 30
  36. #define FDREAD_TIMEOUT 1500
  37. #define FDREAD_RETRIES 7
  38. #define FDWRITE_TIMEOUT 1500
  39. #define FDWRITE_RETRIES 7
  40. /* How much to wait for connection to be established with channel source (miliseconds) */
  41. #define PROXY_CONNECT_TIMEOUT 1000
  42. /* Seconds to sleep between retries (miliseconds) */
  43. #define PROXY_RETRY_TIMEOUT 1000
  44. #define TRANSPORT_PACKET_SIZE 188
  45. #define TRANSPORT_EXTEDED_PACKET_SIZE 192
  46. #define TRANSPORT_PACKETS_PER_NETWORK_PACKET 7
  47. #define TRANSPORT_SYNC_BYTE 0x47
  48. #define FRAME_PACKET_SIZE (TRANSPORT_PACKET_SIZE * TRANSPORT_PACKETS_PER_NETWORK_PACKET)
  49. #ifndef FREE
  50. #define FREE(x) if(x) { free(x); x=NULL; }
  51. #endif
  52. #ifndef POLLRDHUP
  53. #define POLLRDHUP 0
  54. #endif
  55. char *server_sig = "tomcast";
  56. char *server_ver = "1.15";
  57. char *copyright = "Copyright (C) 2010-2013 Unix Solutions Ltd.";
  58. typedef enum { udp_sock, tcp_sock } channel_source;
  59. typedef struct {
  60. channel_source sproto;
  61. char *proto;
  62. char *host;
  63. char *path;
  64. unsigned int port;
  65. } CHANSRC;
  66. #define MAX_CHANNEL_SOURCES 8
  67. typedef struct {
  68. char *name;
  69. char *source; /* Full source url */
  70. char *sources[MAX_CHANNEL_SOURCES];
  71. uint8_t num_src;
  72. uint8_t curr_src;
  73. char *dest_host;
  74. int dest_port;
  75. } CHANNEL;
  76. typedef struct {
  77. char *name;
  78. CHANNEL *channel;
  79. int sock; /* Server socket */
  80. struct sockaddr_in src_sockname;
  81. int clientsock; /* The udp socket */
  82. struct sockaddr_in dst_sockname;
  83. int reconnect:1, /* Set to 1 to force proxy reconnect */
  84. connected:1, /* It's set to 1 when proxy is connected and serving clients */
  85. dienow:1, /* Stop serving clients and exit now */
  86. freechannel:1; /* Free channel data on object free (this is used in chanconf) */
  87. int cookie; /* Used in chanconf to determine if the restreamer is alrady checked */
  88. pthread_t thread;
  89. } RESTREAMER;
  90. channel_source get_sproto(char *url) {
  91. return strncmp(url, "http", 4)==0 ? tcp_sock : udp_sock;
  92. }
  93. CHANSRC *init_chansrc(char *url) {
  94. regex_t re;
  95. regmatch_t res[5];
  96. regcomp(&re, "^([a-z]+)://([^:/?]+):?([0-9]*)/?(.*)", REG_EXTENDED);
  97. if (regexec(&re,url,5,res,0)==0) {
  98. char *data = strdup(url);
  99. char *proto, *host, *port, *path;
  100. int iport;
  101. proto= data+res[1].rm_so; data[res[1].rm_eo]=0;
  102. host = data+res[2].rm_so; data[res[2].rm_eo]=0;
  103. port = data+res[3].rm_so; data[res[3].rm_eo]=0;
  104. path = data+res[4].rm_so; data[res[4].rm_eo]=0;
  105. iport = atoi(port);
  106. /* Setup */
  107. CHANSRC *src = calloc(1, sizeof(CHANSRC));
  108. src->proto = strdup(proto);
  109. src->sproto= get_sproto(url);
  110. src->host = strdup(host);
  111. src->port = iport ? iport : 80;
  112. src->path = strdup(path);
  113. FREE(data);
  114. regfree(&re);
  115. return src;
  116. }
  117. regfree(&re);
  118. return NULL;
  119. }
  120. void free_chansrc(CHANSRC *url) {
  121. if (url) {
  122. FREE(url->proto);
  123. FREE(url->host);
  124. FREE(url->path);
  125. FREE(url);
  126. }
  127. };
  128. int is_valid_url(char *url) {
  129. regex_t re;
  130. regmatch_t res[5];
  131. int ret;
  132. regcomp(&re, "^([a-z]+)://([^:/?]+):?([0-9]*)/?(.*)", REG_EXTENDED);
  133. ret = regexec(&re,url,5,res,0);
  134. regfree(&re);
  135. return ret == 0;
  136. }
  137. void add_channel_source(CHANNEL *c, char *src) {
  138. if (c->num_src >= MAX_CHANNEL_SOURCES-1)
  139. return;
  140. c->sources[c->num_src] = strdup(src);
  141. if (c->num_src == 0) /* Set default source to first one */
  142. c->source = c->sources[c->num_src];
  143. c->num_src++;
  144. }
  145. void next_channel_source(CHANNEL *c) {
  146. if (c->num_src <= 1)
  147. return;
  148. // uint8_t old_src = c->curr_src;
  149. c->curr_src++;
  150. if (c->curr_src >= MAX_CHANNEL_SOURCES-1 || c->sources[c->curr_src] == NULL)
  151. c->curr_src = 0;
  152. c->source = c->sources[c->curr_src];
  153. // 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);
  154. }
  155. void set_channel_source(CHANNEL *c, uint8_t src_id) {
  156. if (src_id >= MAX_CHANNEL_SOURCES-1 || c->sources[src_id] == NULL)
  157. return;
  158. // uint8_t old_src = c->curr_src;
  159. c->curr_src = src_id;
  160. c->source = c->sources[c->curr_src];
  161. // 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);
  162. }
  163. CHANNEL * new_channel(char *name, char *source, char *dest, int port) {
  164. CHANNEL *c = calloc(1, sizeof(CHANNEL));
  165. c->name = strdup(name);
  166. c->dest_host = strdup(dest);
  167. c->dest_port = port;
  168. add_channel_source(c, source);
  169. return c;
  170. }
  171. void free_channel(CHANNEL *c) {
  172. int i;
  173. for (i=c->num_src-1; i>=0; i--) {
  174. FREE(c->sources[i]);
  175. }
  176. FREE(c->name);
  177. FREE(c->dest_host);
  178. c->source = NULL;
  179. FREE(c);
  180. }
  181. void free_channel_p(void *c) {
  182. free_channel(c);
  183. }
  184. int send_reset_opt = 0;
  185. int multicast_ttl = 1;
  186. struct in_addr output_intf = { .s_addr = INADDR_ANY };
  187. int connect_multicast(struct sockaddr_in send_to) {
  188. int sendsock = socket(AF_INET, SOCK_DGRAM, 0);
  189. if (sendsock < 0) {
  190. LOGf("socket(SOCK_DGRAM): %s\n", strerror(errno));
  191. return -1;
  192. }
  193. int on = 1;
  194. setsockopt(sendsock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
  195. // subscribe to multicast group
  196. // LOGf("Using ttl %d\n", multicast_ttl);
  197. if (IN_MULTICAST(ntohl(send_to.sin_addr.s_addr))) {
  198. if (setsockopt(sendsock, IPPROTO_IP, IP_MULTICAST_TTL, &multicast_ttl, sizeof(multicast_ttl)) < 0) {
  199. LOGf("setsockopt(IP_MUTICAST_TTL): %s\n", strerror(errno));
  200. close(sendsock);
  201. return -1;
  202. }
  203. if (setsockopt(sendsock, IPPROTO_IP, IP_MULTICAST_IF, &output_intf, sizeof(output_intf)) < 0) {
  204. LOGf("setsockopt(IP_MUTICAST_IF, %s): %s\n", strerror(errno), inet_ntoa(output_intf));
  205. close(sendsock);
  206. return -1;
  207. }
  208. }
  209. int writebuflen = FRAME_PACKET_SIZE * 1000;
  210. if (setsockopt(sendsock, SOL_SOCKET, SO_SNDBUF, (const char *)&writebuflen, sizeof(writebuflen)) < 0)
  211. log_perror("setsockopt(): setsockopt(SO_SNDBUF)", errno);
  212. // call connect to get errors
  213. if (connect(sendsock, (struct sockaddr *)&send_to, sizeof send_to)) {
  214. LOGf("udp_connect() error: %s\n", strerror(errno));
  215. close(sendsock);
  216. return -1;
  217. }
  218. return sendsock;
  219. }
  220. void connect_destination(RESTREAMER *r) {
  221. CHANNEL *c = r->channel;
  222. if (r->clientsock >= 0)
  223. shutdown_fd(&(r->clientsock));
  224. r->clientsock = connect_multicast(r->dst_sockname);
  225. LOGf("CONN : Connected dst_fd: %i | Chan: %s Dest: udp://%s:%d\n", r->clientsock, c->name, c->dest_host, c->dest_port);
  226. }
  227. RESTREAMER * new_restreamer(const char *name, CHANNEL *channel) {
  228. int active = 1;
  229. struct sockaddr_in sockname;
  230. int dret = async_resolve_host(channel->dest_host, channel->dest_port, &sockname, DNS_RESOLVER_TIMEOUT, &active);
  231. if (dret != 0) {
  232. if (dret == 1)
  233. LOGf("ERR : Can't resolve host | Chan: %s Dest: udp://%s:%d\n", channel->name, channel->dest_host, channel->dest_port);
  234. if (dret == 2)
  235. LOGf("ERR : DNS timeout | Chan: %s Dest: udp://%s:%d\n", channel->name, channel->dest_host, channel->dest_port);
  236. return NULL;
  237. }
  238. RESTREAMER *r = calloc(1, sizeof(RESTREAMER));
  239. r->name = strdup(name);
  240. r->sock = -1;
  241. r->channel = channel;
  242. r->clientsock = -1;
  243. r->dst_sockname = sockname;
  244. connect_destination(r);
  245. return r;
  246. }
  247. void free_restreamer(RESTREAMER *r) {
  248. if (r->sock > -1)
  249. shutdown_fd(&(r->sock));
  250. if (r->freechannel)
  251. free_channel(r->channel);
  252. FREE(r->name);
  253. FREE(r);
  254. }
  255. char *pidfile = NULL;
  256. char *ident = NULL;
  257. char *logident = NULL;
  258. char *loghost = NULL;
  259. int logport = 514;
  260. char *channels_file = NULL;
  261. int syslog_active = 0;
  262. char TS_NULL_FRAME[FRAME_PACKET_SIZE];
  263. regex_t http_response;
  264. LIST *chanconf = NULL;
  265. LIST *restreamer = NULL;
  266. static pthread_mutex_t channels_lock = PTHREAD_MUTEX_INITIALIZER;
  267. void proxy_log(RESTREAMER *r, char *msg, char *info) {
  268. LOGf("%s: %sChan: %s Src: %s Dst: udp://%s:%d SrcIP: %s SrcFD: %i DstFD: %i\n",
  269. msg,
  270. info,
  271. r->channel->name,
  272. r->channel->source,
  273. r->channel->dest_host,
  274. r->channel->dest_port,
  275. inet_ntoa(r->src_sockname.sin_addr),
  276. r->sock,
  277. r->clientsock
  278. );
  279. }
  280. int load_channels_config() {
  281. regex_t re;
  282. regmatch_t res[5];
  283. char line[1024];
  284. int fd;
  285. int num_channels = 0;
  286. if (pthread_mutex_trylock(&channels_lock) != 0)
  287. return -1;
  288. fd = open(channels_file, O_RDONLY);
  289. if (fd != -1) {
  290. struct timeval tv;
  291. gettimeofday(&tv, NULL);
  292. unsigned int randstate = tv.tv_usec;
  293. int cookie = rand_r(&randstate);
  294. regcomp(&re, "^([A-Za-z0-9]+)\t+([0-9.]+):([0-9]+)\t+(.*)", REG_EXTENDED);
  295. LIST *old_chanconf;
  296. LIST *new_chanconf = list_new("chanconf");
  297. while (fdgetline(fd,line,sizeof(line)) > 0) {
  298. chomp(line);
  299. if (regexec(&re,line,5,res,0)==0) {
  300. char *name, *dest_host, *dest_port, *source;
  301. char *org = strdup(line);
  302. name = org+res[1].rm_so; org[res[1].rm_eo]=0;
  303. dest_host = org+res[2].rm_so; org[res[2].rm_eo]=0;
  304. dest_port = org+res[3].rm_so; org[res[3].rm_eo]=0;
  305. source = org+res[4].rm_so; org[res[4].rm_eo]=0;
  306. if (!is_valid_url(source)) {
  307. LOGf("CONF : Invalid url: %s\n", source);
  308. FREE(org);
  309. goto report_error;
  310. }
  311. /* Search for already added channel */
  312. LNODE *l, *tmp;
  313. CHANNEL *chan = NULL;
  314. list_for_each_reverse(new_chanconf, l, tmp) {
  315. if (strcmp(name, ((CHANNEL *)l->data)->name)==0) {
  316. chan = l->data;
  317. break;
  318. }
  319. }
  320. if (!chan) {
  321. list_add(new_chanconf, new_channel(name, source, dest_host, atoi(dest_port)));
  322. num_channels++;
  323. } else {
  324. add_channel_source(chan, source);
  325. }
  326. FREE(org);
  327. } else {
  328. report_error:
  329. if (strlen(line) > 2 && line[0] != '#') {
  330. LOGf("CONF : Invalid config line: %s\n", line);
  331. }
  332. }
  333. }
  334. regfree(&re);
  335. shutdown_fd(&fd);
  336. /* Save current chanconf */
  337. old_chanconf = chanconf;
  338. /* Switch chanconf */
  339. chanconf = new_chanconf;
  340. /* Rewrite restreamer channels */
  341. LNODE *lc, *lr, *lctmp, *lrtmp;
  342. CHANNEL *chan;
  343. list_lock(restreamer); // Unlocked after second list_for_each(restreamer)
  344. list_lock(chanconf);
  345. list_for_each(chanconf, lc, lctmp) {
  346. chan = lc->data;
  347. list_for_each(restreamer, lr, lrtmp) {
  348. if (strcmp(chan->name, ((RESTREAMER *)lr->data)->name)==0) {
  349. RESTREAMER *restr = lr->data;
  350. /* Mark the restreamer as valid */
  351. restr->cookie = cookie;
  352. /* Check if current source exists in new channel configuration */
  353. int i, src_found = -1;
  354. char *old_source = restr->channel->source;
  355. for (i=0; i<chan->num_src; i++) {
  356. if (strcmp(old_source, chan->sources[i]) == 0) {
  357. src_found = i;
  358. }
  359. }
  360. if (src_found > -1) {
  361. /* New configuration contains existing source, just update the reference */
  362. set_channel_source(chan, src_found);
  363. restr->channel = chan;
  364. } else {
  365. /* New configuration *DO NOT* contain existing source. Force reconnect */
  366. LOGf("PROXY: Source changed | Channel: %s srv_fd: %d Old:%s New:%s\n", chan->name, restr->sock, restr->channel->source, chan->source);
  367. /* The order is important! */
  368. set_channel_source(chan, chan->num_src-1); /* Set source to last one. On reconnect next source will be used. */
  369. restr->channel = chan;
  370. restr->reconnect = 1;
  371. }
  372. break;
  373. }
  374. }
  375. }
  376. list_unlock(chanconf);
  377. /* Kill restreamers that serve channels that no longer exist */
  378. list_for_each(restreamer, lr, lrtmp) {
  379. RESTREAMER *r = lr->data;
  380. /* This restreamer should no longer serve clients */
  381. if (r->cookie != cookie) {
  382. proxy_log(r, "CLEAR", "Channel removed ");
  383. /* Replace channel reference with real object and instruct free_restreamer to free it */
  384. r->channel = new_channel(r->channel->name, r->channel->source, r->channel->dest_host, r->channel->dest_port);
  385. r->freechannel = 1;
  386. r->dienow = 1;
  387. }
  388. }
  389. list_unlock(restreamer);
  390. /* Free old_chanconf */
  391. list_free(&old_chanconf, free_channel_p, NULL);
  392. } else {
  393. num_channels = -1;
  394. }
  395. pthread_mutex_unlock(&channels_lock);
  396. if (num_channels == -1)
  397. LOGf("CONF : Error loading channels!\n");
  398. else
  399. LOGf("CONF : %d channels loaded\n", num_channels);
  400. return num_channels;
  401. }
  402. void proxy_close(RESTREAMER *r) {
  403. proxy_log(r, "STOP ","");
  404. // If there are no clients left, no "Timeout" messages will be logged
  405. list_del_entry(restreamer, r);
  406. free_restreamer(r);
  407. }
  408. /*
  409. On the last try, send no-signal to clients and exit
  410. otherwise wait a little bit before trying again
  411. */
  412. #define DO_RECONNECT do \
  413. { \
  414. free_chansrc(src); \
  415. if (retries == 0) { \
  416. return -1; \
  417. } else { \
  418. if (errno != EHOSTUNREACH) /* When host is unreachable there is already a delay of ~4 secs per try so no sleep is needed */ \
  419. usleep(PROXY_RETRY_TIMEOUT * 1000); \
  420. return 1; \
  421. } \
  422. } while(0)
  423. #define FATAL_ERROR do \
  424. { \
  425. free_chansrc(src); \
  426. return -1; \
  427. } while (0)
  428. /*
  429. Returns:
  430. -1 = exit thread
  431. 1 = retry
  432. 0 = connected ok
  433. */
  434. int connect_source(RESTREAMER *r, int retries, int readbuflen, int *http_code) {
  435. CHANSRC *src = init_chansrc(r->channel->source);
  436. if (!src) {
  437. LOGf("ERR : Can't parse channel source | Channel: %s Source: %s\n", r->channel->name, r->channel->source);
  438. FATAL_ERROR;
  439. }
  440. r->connected = 0;
  441. r->reconnect = 0;
  442. int active = 1;
  443. int dret = async_resolve_host(src->host, src->port, &(r->src_sockname), DNS_RESOLVER_TIMEOUT, &active);
  444. if (dret != 0) {
  445. if (dret == 1)
  446. proxy_log(r, "ERR ","Can't resolve src host");
  447. if (dret == 2)
  448. proxy_log(r, "ERR ","Timeout resolving src host");
  449. DO_RECONNECT;
  450. }
  451. char buf[1024];
  452. *http_code = 0;
  453. if (src->sproto == tcp_sock) {
  454. r->sock = socket(PF_INET, SOCK_STREAM, 0);
  455. if (r->sock < 0) {
  456. log_perror("play(): Could not create SOCK_STREAM socket.", errno);
  457. FATAL_ERROR;
  458. }
  459. proxy_log(r, "NEW ","");
  460. if (do_connect(r->sock, (struct sockaddr *)&(r->src_sockname), sizeof(r->src_sockname), PROXY_CONNECT_TIMEOUT) < 0) {
  461. LOGf("ERR : Error connecting to %s srv_fd: %i err: %s\n", r->channel->source, r->sock, strerror(errno));
  462. DO_RECONNECT;
  463. }
  464. snprintf(buf,sizeof(buf)-1, "GET /%s HTTP/1.0\nHost: %s:%u\nX-Smart-Client: yes\nUser-Agent: %s %s (%s)\n\n",
  465. src->path, src->host, src->port, server_sig, server_ver, ident);
  466. buf[sizeof(buf)-1] = 0;
  467. fdwrite(r->sock, buf, strlen(buf));
  468. char xresponse[128];
  469. memset(xresponse, 0, sizeof(xresponse));
  470. memset(buf, 0, sizeof(buf));
  471. regmatch_t res[4];
  472. while (fdgetline(r->sock,buf,sizeof(buf)-1)) {
  473. if (buf[0] == '\n' || buf[0] == '\r')
  474. break;
  475. if (strstr(buf,"HTTP/1.") != NULL) {
  476. if (regexec(&http_response,buf,3,res,0) != REG_NOMATCH) {
  477. char codestr[4];
  478. if ((unsigned int)res[1].rm_eo-res[1].rm_so < sizeof(xresponse)) {
  479. strncpy(xresponse, &buf[res[1].rm_so], res[1].rm_eo-res[1].rm_so);
  480. xresponse[res[1].rm_eo-res[1].rm_so] = '\0';
  481. chomp(xresponse);
  482. strncpy(codestr, &buf[res[2].rm_so], res[2].rm_eo-res[2].rm_so);
  483. codestr[3] = 0;
  484. *http_code = atoi(codestr);
  485. }
  486. }
  487. }
  488. if (*http_code == 504) { // Extract extra error code
  489. if (strstr(buf, "X-ErrorCode: ") != NULL) {
  490. *http_code = atoi(buf+13);
  491. break;
  492. }
  493. }
  494. }
  495. if (*http_code == 0) { // No valid HTTP response, retry
  496. LOGf("DEBUG: Server returned not valid HTTP code | srv_fd: %i\n", r->sock);
  497. DO_RECONNECT;
  498. }
  499. if (*http_code == 504) { // No signal, exit
  500. LOGf("ERR : Get no-signal for %s from %s on srv_fd: %i\n", r->channel->name, r->channel->source, r->sock);
  501. FATAL_ERROR;
  502. }
  503. if (*http_code > 300) { // Unhandled or error codes, exit
  504. 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);
  505. FATAL_ERROR;
  506. }
  507. // connected ok, continue
  508. } else {
  509. if (!IN_MULTICAST(ntohl(r->src_sockname.sin_addr.s_addr))) {
  510. LOGf("ERR : %s is not multicast address\n", r->channel->source);
  511. FATAL_ERROR;
  512. }
  513. struct ip_mreq mreq;
  514. struct sockaddr_in receiving_from;
  515. r->sock = socket(PF_INET, SOCK_DGRAM, 0);
  516. if (r->sock < 0) {
  517. log_perror("play(): Could not create SOCK_DGRAM socket.", errno);
  518. FATAL_ERROR;
  519. }
  520. LOGf("CONN : Listening on multicast socket %s srv_fd: %i retries left: %i\n", r->channel->source, r->sock, retries);
  521. int on = 1;
  522. setsockopt(r->sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
  523. // subscribe to multicast group
  524. memcpy(&mreq.imr_multiaddr, &(r->src_sockname.sin_addr), sizeof(struct in_addr));
  525. mreq.imr_interface.s_addr = htonl(INADDR_ANY);
  526. if (setsockopt(r->sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) {
  527. LOGf("ERR : Failed to add IP membership on %s srv_fd: %i\n", r->channel->source, r->sock);
  528. FATAL_ERROR;
  529. }
  530. // bind to the socket so data can be read
  531. memset(&receiving_from, 0, sizeof(receiving_from));
  532. receiving_from.sin_family = AF_INET;
  533. receiving_from.sin_addr = r->src_sockname.sin_addr;
  534. receiving_from.sin_port = htons(src->port);
  535. if (bind(r->sock, (struct sockaddr *) &receiving_from, sizeof(receiving_from)) < 0) {
  536. LOGf("ERR : Failed to bind to %s srv_fd: %i\n", r->channel->source, r->sock);
  537. FATAL_ERROR;
  538. }
  539. }
  540. if (setsockopt(r->sock, SOL_SOCKET, SO_RCVBUF, (const char *)&readbuflen, sizeof(readbuflen)) < 0)
  541. log_perror("play(): setsockopt(SO_RCVBUF)", errno);
  542. r->connected = 1;
  543. free_chansrc(src);
  544. return 0;
  545. }
  546. int check_restreamer_state(RESTREAMER *r) {
  547. if (r->dienow) {
  548. // LOGf("PROXY: Forced disconnect on srv_fd: %i | Channel: %s Source: %s\n", r->sock, r->channel->name, r->channel->source);
  549. return 2;
  550. }
  551. if (r->reconnect) {
  552. LOGf("PROXY: Forced reconnect on srv_fd: %i | Channel: %s Source: %s\n", r->sock, r->channel->name, r->channel->source);
  553. return 1;
  554. }
  555. return 0;
  556. }
  557. #define MAX_ZERO_READS 3
  558. /* Start: 3 seconds on connect */
  559. /* In connection: Max UDP timeout == 3 seconds (read) + 2 seconds (connect) == 5 seconds */
  560. #define UDP_READ_RETRIES 3
  561. #define UDP_READ_TIMEOUT 1000
  562. /* Start: 1/4 seconds on connect */
  563. /* In connection: Max TCP timeout == 5 seconds (read) + 2 seconds (connect) == 7 seconds */
  564. /* In connection: Max TCP timeout == 5 seconds (read) + 8 seconds (connect, host unrch) == 13 seconds */
  565. #define TCP_READ_RETRIES 5
  566. #define TCP_READ_TIMEOUT 1000
  567. /*
  568. Returns:
  569. 0 = synced ok
  570. 1 = not synced, reconnect
  571. */
  572. int mpeg_sync(int proxysock, char *channel, channel_source source_proto) {
  573. time_t sync_start = time(NULL);
  574. unsigned int sync_packets = 0;
  575. unsigned int read_bytes = 0;
  576. char syncframe[188];
  577. int _timeout = TCP_READ_TIMEOUT;
  578. int _retries = TCP_READ_RETRIES;
  579. if (source_proto == udp_sock) {
  580. _timeout = UDP_READ_TIMEOUT;
  581. _retries = UDP_READ_RETRIES;
  582. }
  583. do {
  584. resync:
  585. if (fdread_ex(proxysock, syncframe, 1, _timeout, _retries, 1) != 1) {
  586. LOGf("DEBUG: mpeg_sync fdread() timeout | Channel: %s\n", channel);
  587. return 1; // reconnect
  588. }
  589. // LOGf("DEBUG: Read 0x%02x Offset %u Sync: %u\n", (uint8_t)syncframe[0], read_bytes, sync_packets);
  590. read_bytes++;
  591. if (syncframe[0] == 0x47) {
  592. ssize_t rdsz = fdread_ex(proxysock, syncframe, 188-1, _timeout, _retries, 1);
  593. if (rdsz != 188-1) {
  594. LOGf("DEBUG: mpeg_sync fdread() timeout | Channel: %s\n", channel);
  595. return 1; // reconnect
  596. }
  597. read_bytes += 188-1;
  598. if (++sync_packets == 7) // sync 7 packets
  599. break;
  600. goto resync;
  601. } else {
  602. sync_packets = 0;
  603. }
  604. if (read_bytes > FRAME_PACKET_SIZE) { // Can't sync in 1316 bytes
  605. LOGf("DEBUG: Can't sync after %d bytes | Channel: %s\n", FRAME_PACKET_SIZE, channel);
  606. return 1; // reconnect
  607. }
  608. if (sync_start+2 <= time(NULL)) { // Do not sync in two seconds
  609. LOGf("DEBUG: Timeout while syncing (read %u bytes) | Channel: %s\n", read_bytes, channel);
  610. return 1; // reconnect
  611. }
  612. } while (1);
  613. LOGf("SYNC : TS synced after %u bytes | Channel: %s\n", read_bytes-FRAME_PACKET_SIZE, channel);
  614. return 0;
  615. }
  616. char reset[FRAME_PACKET_SIZE] = {
  617. 0x47,0x40,0x00,0x10,0x00,0x00,0xB0,0x09,0x27,0x10,0xC1,0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,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  714. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  715. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  716. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  717. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  718. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  719. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  720. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  721. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  722. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  723. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  724. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  725. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  726. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF
  727. };
  728. void * proxy_ts_stream(void *self) {
  729. RESTREAMER *r = self;
  730. char buf[FRAME_PACKET_SIZE];
  731. signal(SIGPIPE, SIG_IGN);
  732. int http_code = 0;
  733. while (1) {
  734. int result = connect_source(self, 1, FRAME_PACKET_SIZE * 1000, &http_code);
  735. if (result > 0)
  736. goto RECONNECT;
  737. channel_source sproto = get_sproto(r->channel->source);
  738. int mpgsync = mpeg_sync(r->sock, r->channel->name, sproto);
  739. if (mpgsync == 1) // Timeout
  740. goto RECONNECT;
  741. ssize_t readen, written;
  742. int max_zero_reads = MAX_ZERO_READS;
  743. int send_reset = send_reset_opt;
  744. for (;;) {
  745. switch (check_restreamer_state(r)) {
  746. case 1: goto RECONNECT; // r->reconnect is on
  747. case 2: goto QUIT; // r->dienow is on
  748. }
  749. if (sproto == tcp_sock) {
  750. readen = fdread_ex(r->sock, buf, FRAME_PACKET_SIZE, TCP_READ_TIMEOUT, TCP_READ_RETRIES, 1);
  751. } else {
  752. readen = fdread_ex(r->sock, buf, FRAME_PACKET_SIZE, UDP_READ_TIMEOUT, UDP_READ_RETRIES, 0);
  753. }
  754. if (readen < 0)
  755. goto RECONNECT;
  756. if (readen == 0) { // ho, hum, wtf is going on here?
  757. LOGf("PROXY: zero read on srv_fd: %i | Channel: %s Source: %s\n", r->sock, r->channel->name, r->channel->source);
  758. if (--max_zero_reads == 0) {
  759. 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);
  760. break;
  761. }
  762. continue;
  763. }
  764. max_zero_reads = MAX_ZERO_READS;
  765. // Fill short frame with NULL packets
  766. if (readen < FRAME_PACKET_SIZE) {
  767. //LOGf("DEBUG: Short read (%d) on retreamer srv_fd: %i | Channel: %s\n", readen, sock, chan->name);
  768. memcpy(buf+readen, TS_NULL_FRAME+readen, FRAME_PACKET_SIZE - readen);
  769. }
  770. if (send_reset) {
  771. send_reset = 0;
  772. written = fdwrite(r->clientsock, reset, FRAME_PACKET_SIZE);
  773. }
  774. written = fdwrite(r->clientsock, buf, FRAME_PACKET_SIZE);
  775. if (written == -1) {
  776. 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);
  777. connect_destination(r);
  778. }
  779. }
  780. LOGf("DEBUG: fdread timeout restreamer srv_fd: %i | Channel: %s\n", r->sock, r->channel->name);
  781. RECONNECT:
  782. LOGf("DEBUG: reconnect srv_fd: %i | Channel: %s\n", r->sock, r->channel->name);
  783. shutdown_fd(&(r->sock));
  784. next_channel_source(r->channel);
  785. continue;
  786. QUIT:
  787. LOGf("DEBUG: quit srv_fd: %i | Channel: %s\n", r->sock, r->channel->name);
  788. break;
  789. }
  790. proxy_close(r);
  791. return 0;
  792. }
  793. static int copyright_shown = 0;
  794. void show_usage(int ident_only) {
  795. if (!copyright_shown) {
  796. printf("%s %s\n", server_sig, server_ver);
  797. puts(copyright);
  798. puts("");
  799. copyright_shown = 1;
  800. }
  801. if (ident_only)
  802. return;
  803. puts("Usage: tomcast -c config_file");
  804. puts("");
  805. puts("\t-c file\t\tChannels configuration file");
  806. puts("\t-i ident\tServer ident. Must be formated as PROVIDER/SERVER");
  807. puts("\t-d pidfile\tDaemonize and write daemon pid into pidfile");
  808. puts("\t-t ttl\t\tSet multicast ttl (default: 1)");
  809. puts("\t-o ip\t\tOutput interface address (default: 0.0.0.0)");
  810. puts("\t-l host\t\tSyslog host (default: disabled)");
  811. puts("\t-L port\t\tSyslog port (default: 514)");
  812. puts("\t-R\t\tSend reset packets when changing sources.");
  813. puts("");
  814. }
  815. void set_ident(char *new_ident) {
  816. ident = new_ident;
  817. logident = strdup(ident);
  818. char *c = logident;
  819. while (*c) {
  820. if (*c=='/')
  821. *c='-';
  822. c++;
  823. }
  824. }
  825. void parse_options(int argc, char **argv) {
  826. int j, ttl;
  827. while ((j = getopt(argc, argv, "i:c:d:t:o:l:L:RHh")) != -1) {
  828. switch (j) {
  829. case 'i':
  830. set_ident(optarg);
  831. break;
  832. case 'c':
  833. channels_file = optarg;
  834. break;
  835. case 'd':
  836. pidfile = optarg;
  837. break;
  838. case 'o':
  839. if (inet_aton(optarg, &output_intf) == 0) {
  840. fprintf(stderr, "Invalid interface address: %s\n", optarg);
  841. exit(1);
  842. }
  843. break;
  844. case 't':
  845. ttl = atoi(optarg);
  846. multicast_ttl = (ttl && ttl < 127) ? ttl : 1;
  847. break;
  848. case 'l':
  849. loghost = optarg;
  850. syslog_active = 1;
  851. break;
  852. case 'L':
  853. logport = atoi(optarg);
  854. break;
  855. case 'R':
  856. send_reset_opt = 1;
  857. break;
  858. case 'H':
  859. case 'h':
  860. show_usage(0);
  861. exit(0);
  862. break;
  863. }
  864. }
  865. if (!channels_file) {
  866. show_usage(0);
  867. fprintf(stderr, "ERROR: No channels file is set (use -c option).\n");
  868. exit(1);
  869. }
  870. if (!ident) {
  871. set_ident("unixsol/tomcast");
  872. }
  873. printf("Configuration:\n");
  874. printf("\tServer ident : %s\n", ident);
  875. printf("\tChannels file : %s\n", channels_file);
  876. printf("\tOutput iface addr : %s\n", inet_ntoa(output_intf));
  877. printf("\tMulticast ttl : %d\n", multicast_ttl);
  878. if (syslog_active) {
  879. printf("\tSyslog host : %s\n", loghost);
  880. printf("\tSyslog port : %d\n", logport);
  881. } else {
  882. printf("\tSyslog disabled.\n");
  883. }
  884. if (send_reset_opt)
  885. printf("\tSend reset packets.\n");
  886. if (pidfile) {
  887. printf("\tDaemonize : %s\n", pidfile);
  888. } else {
  889. printf("\tDo not daemonize.\n");
  890. }
  891. }
  892. void init_vars() {
  893. restreamer = list_new("restreamer");
  894. regcomp(&http_response, "^HTTP/1.[0-1] (([0-9]{3}) .*)", REG_EXTENDED);
  895. memset(&TS_NULL_FRAME, 0xff, FRAME_PACKET_SIZE);
  896. int i;
  897. for (i=0; i<FRAME_PACKET_SIZE; i=i+188) {
  898. TS_NULL_FRAME[i+0] = 0x47;
  899. TS_NULL_FRAME[i+1] = 0x1f;
  900. TS_NULL_FRAME[i+2] = 0xff;
  901. TS_NULL_FRAME[i+3] = 0x00;
  902. }
  903. }
  904. void spawn_proxy_threads() {
  905. LNODE *lc, *lctmp;
  906. LNODE *lr, *lrtmp;
  907. int spawned = 0;
  908. list_for_each(chanconf, lc, lctmp) {
  909. CHANNEL *c = lc->data;
  910. int restreamer_active = 0;
  911. list_lock(restreamer);
  912. list_for_each(restreamer, lr, lrtmp) {
  913. RESTREAMER *r = lr->data;
  914. if (strcmp(r->name, c->name)==0) {
  915. restreamer_active = 1;
  916. break;
  917. }
  918. }
  919. list_unlock(restreamer);
  920. if (!restreamer_active) {
  921. RESTREAMER *nr = new_restreamer(c->name, c);
  922. if (nr->clientsock < 0) {
  923. LOGf("Error creating proxy socket for %s\n", c->name);
  924. } else {
  925. list_add(restreamer, nr);
  926. if (pthread_create(&nr->thread, NULL, &proxy_ts_stream, nr) == 0) {
  927. spawned++;
  928. pthread_detach(nr->thread);
  929. } else {
  930. LOGf("Error creating proxy for %s\n", c->name);
  931. }
  932. }
  933. }
  934. }
  935. LOGf("INFO : %d proxy threads spawned\n", spawned);
  936. }
  937. void kill_proxy_threads() {
  938. LNODE *l, *tmp;
  939. int killed = 0;
  940. list_lock(restreamer);
  941. list_for_each(restreamer, l, tmp) {
  942. RESTREAMER *r = l->data;
  943. r->dienow = 1;
  944. killed++;
  945. }
  946. list_unlock(restreamer);
  947. LOGf("INFO : %d proxy threads killed\n", killed);
  948. }
  949. void signal_quit(int sig) {
  950. kill_proxy_threads();
  951. usleep(500000);
  952. LOGf("KILL : Signal %i | %s %s (%s)\n", sig, server_sig, server_ver, ident);
  953. usleep(100000);
  954. log_close();
  955. if (pidfile && strlen(pidfile))
  956. unlink(pidfile);
  957. signal(sig, SIG_DFL);
  958. raise(sig);
  959. }
  960. void do_reconnect() {
  961. LNODE *l, *tmp;
  962. list_lock(restreamer);
  963. list_for_each(restreamer, l, tmp) {
  964. RESTREAMER *r = l->data;
  965. r->reconnect = 1;
  966. }
  967. list_unlock(restreamer);
  968. }
  969. void do_reconf() {
  970. load_channels_config();
  971. spawn_proxy_threads();
  972. }
  973. void init_signals() {
  974. signal(SIGCHLD, SIG_IGN);
  975. signal(SIGPIPE, SIG_IGN);
  976. signal(SIGHUP , do_reconf);
  977. signal(SIGUSR1, do_reconnect);
  978. signal(SIGINT , signal_quit);
  979. signal(SIGTERM, signal_quit);
  980. }
  981. void do_daemonize() {
  982. if (!pidfile)
  983. return;
  984. fprintf(stderr, "Daemonizing.\n");
  985. pid_t pid = fork();
  986. if (pid > 0) {
  987. FILE *F = fopen(pidfile,"w");
  988. if (F) {
  989. fprintf(F,"%i\n",pid);
  990. fclose(F);
  991. }
  992. exit(0);
  993. }
  994. // Child process continues...
  995. setsid(); // request a new session (job control)
  996. freopen("/dev/null", "r", stdin);
  997. freopen("/dev/null", "w", stdout);
  998. freopen("/dev/null", "w", stderr);
  999. }
  1000. /* Must be called after daemonize! */
  1001. void init_logger() {
  1002. if (syslog_active)
  1003. fprintf(stderr, "Logging to %s:%d\n", loghost, logport);
  1004. log_init(logident, syslog_active, pidfile == NULL, loghost, logport);
  1005. }
  1006. int main(int argc, char **argv) {
  1007. set_http_response_server_ident(server_sig, server_ver);
  1008. show_usage(1); // Show copyright and version
  1009. init_vars();
  1010. parse_options(argc, argv);
  1011. do_daemonize();
  1012. init_logger();
  1013. init_signals();
  1014. LOGf("INIT : %s %s (%s)\n" , server_sig, server_ver, ident);
  1015. load_channels_config();
  1016. spawn_proxy_threads();
  1017. do {
  1018. sleep(60);
  1019. } while(1);
  1020. signal_quit(15);
  1021. exit(0);
  1022. }