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

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