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 36KB

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