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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260
  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 <stdbool.h>
  17. #include <stdlib.h>
  18. #include <unistd.h>
  19. #include <string.h>
  20. #include <pthread.h>
  21. #include <errno.h>
  22. #include <arpa/inet.h>
  23. #include <netinet/in.h>
  24. #include <sys/types.h>
  25. #include <sys/socket.h>
  26. #include <sys/types.h>
  27. #include <sys/stat.h>
  28. #include <sys/time.h>
  29. #include <signal.h>
  30. #include <fcntl.h>
  31. #include <regex.h>
  32. #include <netdb.h> // for uint32_t
  33. #include "libfuncs/libfuncs.h"
  34. #include "bitstream.h"
  35. #include "config.h"
  36. #include "web_server.h"
  37. #define DNS_RESOLVER_TIMEOUT 5000
  38. #define FDGETLINE_TIMEOUT 500
  39. #define FDGETLINE_RETRIES 30
  40. #define FDREAD_TIMEOUT 1500
  41. #define FDREAD_RETRIES 7
  42. #define FDWRITE_TIMEOUT 1500
  43. #define FDWRITE_RETRIES 7
  44. /* How much to wait for connection to be established with channel source (miliseconds) */
  45. #define PROXY_CONNECT_TIMEOUT 1000
  46. /* Seconds to sleep between retries (miliseconds) */
  47. #define PROXY_RETRY_TIMEOUT 1000
  48. #define TRANSPORT_PACKET_SIZE 188
  49. #define TRANSPORT_EXTEDED_PACKET_SIZE 192
  50. #define TRANSPORT_PACKETS_PER_NETWORK_PACKET 7
  51. #define TRANSPORT_SYNC_BYTE 0x47
  52. #define FRAME_PACKET_SIZE (TRANSPORT_PACKET_SIZE * TRANSPORT_PACKETS_PER_NETWORK_PACKET)
  53. #ifndef FREE
  54. #define FREE(x) if(x) { free(x); x=NULL; }
  55. #endif
  56. #ifndef POLLRDHUP
  57. #define POLLRDHUP 0
  58. #endif
  59. char *server_sig = "tomcast";
  60. char *server_ver = "1.40";
  61. char *copyright = "Copyright (C) 2010-2018 Unix Solutions Ltd.";
  62. static struct config config;
  63. #ifdef __MACH__
  64. #include <mach/clock.h>
  65. #include <mach/mach.h>
  66. #endif
  67. int64_t get_time(void) {
  68. struct timespec ts;
  69. #ifdef __MACH__
  70. // OS X does not have clock_gettime, use clock_get_time
  71. clock_serv_t cclock;
  72. mach_timespec_t mts;
  73. host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
  74. clock_get_time(cclock, &mts);
  75. mach_port_deallocate(mach_task_self(), cclock);
  76. ts.tv_sec = mts.tv_sec;
  77. ts.tv_nsec = mts.tv_nsec;
  78. #else
  79. if (clock_gettime(CLOCK_MONOTONIC, &ts) == EINVAL) // Shouldn't happen on modern Linux
  80. clock_gettime(CLOCK_REALTIME, &ts);
  81. #endif
  82. return ts.tv_sec * 1000000ll + ts.tv_nsec / 1000;
  83. }
  84. channel_source get_sproto(char *url) {
  85. return strncmp(url, "http", 4)==0 ? tcp_sock : udp_sock;
  86. }
  87. CHANSRC *init_chansrc(char *url) {
  88. regex_t re;
  89. regmatch_t res[5];
  90. regcomp(&re, "^([a-z]+)://([^:/?]+):?([0-9]*)/?(.*)", REG_EXTENDED);
  91. if (regexec(&re,url,5,res,0)==0) {
  92. char *data = strdup(url);
  93. char *proto, *host, *port, *path;
  94. int iport;
  95. proto= data+res[1].rm_so; data[res[1].rm_eo]=0;
  96. host = data+res[2].rm_so; data[res[2].rm_eo]=0;
  97. port = data+res[3].rm_so; data[res[3].rm_eo]=0;
  98. path = data+res[4].rm_so; data[res[4].rm_eo]=0;
  99. iport = atoi(port);
  100. /* Setup */
  101. CHANSRC *src = calloc(1, sizeof(CHANSRC));
  102. src->proto = strdup(proto);
  103. src->sproto= get_sproto(url);
  104. src->host = strdup(host);
  105. src->port = iport ? iport : 80;
  106. src->path = strdup(path);
  107. FREE(data);
  108. regfree(&re);
  109. return src;
  110. }
  111. regfree(&re);
  112. return NULL;
  113. }
  114. void free_chansrc(CHANSRC *url) {
  115. if (url) {
  116. FREE(url->proto);
  117. FREE(url->host);
  118. FREE(url->path);
  119. FREE(url);
  120. }
  121. };
  122. int is_valid_url(char *url) {
  123. regex_t re;
  124. regmatch_t res[5];
  125. int ret;
  126. regcomp(&re, "^([a-z]+)://([^:/?]+):?([0-9]*)/?(.*)", REG_EXTENDED);
  127. ret = regexec(&re,url,5,res,0);
  128. regfree(&re);
  129. return ret == 0;
  130. }
  131. void add_channel_source(CHANNEL *c, char *src) {
  132. if (c->num_src >= MAX_CHANNEL_SOURCES-1)
  133. return;
  134. c->sources[c->num_src] = strdup(src);
  135. if (c->num_src == 0) /* Set default source to first one */
  136. c->source = c->sources[c->num_src];
  137. c->num_src++;
  138. }
  139. void next_channel_source(CHANNEL *c) {
  140. if (c->num_src <= 1)
  141. return;
  142. // uint8_t old_src = c->curr_src;
  143. c->curr_src++;
  144. if (c->curr_src >= MAX_CHANNEL_SOURCES-1 || c->sources[c->curr_src] == NULL)
  145. c->curr_src = 0;
  146. c->source = c->sources[c->curr_src];
  147. // 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);
  148. }
  149. void set_channel_source(CHANNEL *c, uint8_t src_id) {
  150. if (src_id >= MAX_CHANNEL_SOURCES-1 || c->sources[src_id] == NULL)
  151. return;
  152. // uint8_t old_src = c->curr_src;
  153. c->curr_src = src_id;
  154. c->source = c->sources[c->curr_src];
  155. // 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);
  156. }
  157. CHANNEL * new_channel(char *name, char *source, char *dest, int port) {
  158. CHANNEL *c = calloc(1, sizeof(CHANNEL));
  159. c->name = strdup(name);
  160. c->dest_host = strdup(dest);
  161. c->dest_port = port;
  162. add_channel_source(c, source);
  163. return c;
  164. }
  165. void free_channel(CHANNEL *c) {
  166. int i;
  167. for (i=c->num_src-1; i>=0; i--) {
  168. FREE(c->sources[i]);
  169. }
  170. FREE(c->name);
  171. FREE(c->dest_host);
  172. c->source = NULL;
  173. FREE(c);
  174. }
  175. void free_channel_p(void *c) {
  176. free_channel(c);
  177. }
  178. int send_reset_opt = 0;
  179. int multicast_ttl = 1;
  180. struct in_addr output_intf = { .s_addr = INADDR_ANY };
  181. int connect_multicast(struct sockaddr_in send_to) {
  182. int sendsock = socket(AF_INET, SOCK_DGRAM, 0);
  183. if (sendsock < 0) {
  184. LOGf("socket(SOCK_DGRAM): %s\n", strerror(errno));
  185. return -1;
  186. }
  187. int on = 1;
  188. setsockopt(sendsock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
  189. // subscribe to multicast group
  190. // LOGf("Using ttl %d\n", multicast_ttl);
  191. if (IN_MULTICAST(ntohl(send_to.sin_addr.s_addr))) {
  192. if (setsockopt(sendsock, IPPROTO_IP, IP_MULTICAST_TTL, &multicast_ttl, sizeof(multicast_ttl)) < 0) {
  193. LOGf("setsockopt(IP_MUTICAST_TTL): %s\n", strerror(errno));
  194. close(sendsock);
  195. return -1;
  196. }
  197. if (setsockopt(sendsock, IPPROTO_IP, IP_MULTICAST_IF, &output_intf, sizeof(output_intf)) < 0) {
  198. LOGf("setsockopt(IP_MUTICAST_IF, %s): %s\n", strerror(errno), inet_ntoa(output_intf));
  199. close(sendsock);
  200. return -1;
  201. }
  202. }
  203. int writebuflen = FRAME_PACKET_SIZE * 1000;
  204. if (setsockopt(sendsock, SOL_SOCKET, SO_SNDBUF, (const char *)&writebuflen, sizeof(writebuflen)) < 0)
  205. log_perror("setsockopt(): setsockopt(SO_SNDBUF)", errno);
  206. // call connect to get errors
  207. if (connect(sendsock, (struct sockaddr *)&send_to, sizeof send_to)) {
  208. LOGf("udp_connect() error: %s\n", strerror(errno));
  209. close(sendsock);
  210. return -1;
  211. }
  212. return sendsock;
  213. }
  214. void proxy_set_status(RESTREAMER *r, const char *proxy_status) {
  215. pthread_rwlock_wrlock(&r->lock);
  216. snprintf(r->status, sizeof(r->status), "%s", proxy_status);
  217. pthread_rwlock_unlock(&r->lock);
  218. }
  219. void connect_destination(RESTREAMER *r) {
  220. CHANNEL *c = r->channel;
  221. if (r->clientsock >= 0)
  222. shutdown_fd(&(r->clientsock));
  223. r->clientsock = connect_multicast(r->dst_sockname);
  224. LOGf("CONN : Connected dst_fd: %i | Chan: %s Dest: udp://%s:%d\n", r->clientsock, c->name, c->dest_host, c->dest_port);
  225. }
  226. RESTREAMER * new_restreamer(const char *name, CHANNEL *channel) {
  227. int active = 1;
  228. struct sockaddr_in sockname;
  229. int dret = async_resolve_host(channel->dest_host, channel->dest_port, &sockname, DNS_RESOLVER_TIMEOUT, &active);
  230. if (dret != 0) {
  231. if (dret == 1)
  232. LOGf("ERR : Can't resolve host | Chan: %s Dest: udp://%s:%d\n", channel->name, channel->dest_host, channel->dest_port);
  233. if (dret == 2)
  234. LOGf("ERR : DNS timeout | Chan: %s Dest: udp://%s:%d\n", channel->name, channel->dest_host, channel->dest_port);
  235. return NULL;
  236. }
  237. RESTREAMER *r = calloc(1, sizeof(RESTREAMER));
  238. r->name = strdup(name);
  239. r->sock = -1;
  240. r->channel = channel;
  241. r->clientsock = -1;
  242. r->dst_sockname = sockname;
  243. pthread_rwlock_init(&r->lock, NULL);
  244. connect_destination(r);
  245. r->last_decrypted_input_ts = get_time();
  246. return r;
  247. }
  248. void free_restreamer(RESTREAMER *r) {
  249. if (r->sock > -1)
  250. shutdown_fd(&(r->sock));
  251. if (r->freechannel)
  252. free_channel(r->channel);
  253. FREE(r->name);
  254. FREE(r);
  255. }
  256. char TS_NULL_FRAME[FRAME_PACKET_SIZE];
  257. regex_t http_response;
  258. void proxy_log(RESTREAMER *r, char *msg, char *info) {
  259. LOGf("%s: %s Chan: %s Src: %s Dst: udp://%s:%d SrcIP: %s SrcFD: %i DstFD: %i\n",
  260. msg,
  261. info,
  262. r->channel->name,
  263. r->channel->source,
  264. r->channel->dest_host,
  265. r->channel->dest_port,
  266. inet_ntoa(r->src_sockname.sin_addr),
  267. r->sock,
  268. r->clientsock
  269. );
  270. }
  271. int load_channels_config(struct config *cfg) {
  272. regex_t re;
  273. regmatch_t res[5];
  274. char line[1024];
  275. int fd;
  276. int num_channels = 0;
  277. if (pthread_mutex_trylock(&cfg->channels_lock) != 0)
  278. return -1;
  279. fd = open(cfg->channels_file, O_RDONLY);
  280. if (fd != -1) {
  281. struct timeval tv;
  282. gettimeofday(&tv, NULL);
  283. unsigned int randstate = tv.tv_usec;
  284. int cookie = rand_r(&randstate);
  285. regcomp(&re, "^([A-Za-z0-9]+)\t+([0-9.]+):([0-9]+)\t+(.*)", REG_EXTENDED);
  286. LIST *old_chanconf;
  287. LIST *new_chanconf = list_new("chanconf");
  288. while (fdgetline(fd,line,sizeof(line)) > 0) {
  289. chomp(line);
  290. if (regexec(&re,line,5,res,0)==0) {
  291. char *name, *dest_host, *dest_port, *source;
  292. char *org = strdup(line);
  293. name = org+res[1].rm_so; org[res[1].rm_eo]=0;
  294. dest_host = org+res[2].rm_so; org[res[2].rm_eo]=0;
  295. dest_port = org+res[3].rm_so; org[res[3].rm_eo]=0;
  296. source = org+res[4].rm_so; org[res[4].rm_eo]=0;
  297. if (!is_valid_url(source)) {
  298. LOGf("CONF : Invalid url: %s\n", source);
  299. FREE(org);
  300. goto report_error;
  301. }
  302. /* Search for already added channel */
  303. LNODE *l, *tmp;
  304. CHANNEL *chan = NULL;
  305. list_for_each_reverse(new_chanconf, l, tmp) {
  306. if (strcmp(name, ((CHANNEL *)l->data)->name)==0) {
  307. chan = l->data;
  308. break;
  309. }
  310. }
  311. if (!chan) {
  312. list_add(new_chanconf, new_channel(name, source, dest_host, atoi(dest_port)));
  313. num_channels++;
  314. } else {
  315. add_channel_source(chan, source);
  316. }
  317. FREE(org);
  318. } else {
  319. report_error:
  320. if (strlen(line) > 2 && line[0] != '#') {
  321. LOGf("CONF : Invalid config line: %s\n", line);
  322. }
  323. }
  324. }
  325. regfree(&re);
  326. shutdown_fd(&fd);
  327. /* Save current chanconf */
  328. old_chanconf = cfg->chanconf;
  329. /* Switch chanconf */
  330. cfg->chanconf = new_chanconf;
  331. /* Rewrite restreamer channels */
  332. LNODE *lc, *lr, *lctmp, *lrtmp;
  333. CHANNEL *chan;
  334. list_lock(cfg->restreamer); // Unlocked after second list_for_each(restreamer)
  335. list_lock(cfg->chanconf);
  336. list_for_each(cfg->chanconf, lc, lctmp) {
  337. chan = lc->data;
  338. list_for_each(cfg->restreamer, lr, lrtmp) {
  339. if (strcmp(chan->name, ((RESTREAMER *)lr->data)->name)==0) {
  340. RESTREAMER *restr = lr->data;
  341. /* Mark the restreamer as valid */
  342. restr->cookie = cookie;
  343. /* Check if current source exists in new channel configuration */
  344. int i, src_found = -1;
  345. char *old_source = restr->channel->source;
  346. for (i=0; i<chan->num_src; i++) {
  347. if (strcmp(old_source, chan->sources[i]) == 0) {
  348. src_found = i;
  349. }
  350. }
  351. if (src_found > -1) {
  352. /* New configuration contains existing source, just update the reference */
  353. set_channel_source(chan, src_found);
  354. restr->channel = chan;
  355. } else {
  356. /* New configuration *DO NOT* contain existing source. Force reconnect */
  357. LOGf("PROXY: Source changed | Channel: %s srv_fd: %d Old:%s New:%s\n", chan->name, restr->sock, restr->channel->source, chan->source);
  358. /* The order is important! */
  359. set_channel_source(chan, chan->num_src-1); /* Set source to last one. On reconnect next source will be used. */
  360. restr->channel = chan;
  361. restr->reconnect = 1;
  362. }
  363. break;
  364. }
  365. }
  366. }
  367. list_unlock(cfg->chanconf);
  368. /* Kill restreamers that serve channels that no longer exist */
  369. list_for_each(cfg->restreamer, lr, lrtmp) {
  370. RESTREAMER *r = lr->data;
  371. /* This restreamer should no longer serve clients */
  372. if (r->cookie != cookie) {
  373. proxy_log(r, "CLEAR", "Channel removed ");
  374. /* Replace channel reference with real object and instruct free_restreamer to free it */
  375. r->channel = new_channel(r->channel->name, r->channel->source, r->channel->dest_host, r->channel->dest_port);
  376. r->freechannel = 1;
  377. r->dienow = 1;
  378. }
  379. }
  380. list_unlock(cfg->restreamer);
  381. /* Free old_chanconf */
  382. list_free(&old_chanconf, free_channel_p, NULL);
  383. } else {
  384. num_channels = -1;
  385. }
  386. pthread_mutex_unlock(&cfg->channels_lock);
  387. if (num_channels == -1)
  388. LOGf("CONF : Error loading channels!\n");
  389. else
  390. LOGf("CONF : %d channels loaded\n", num_channels);
  391. return num_channels;
  392. }
  393. void proxy_close(RESTREAMER *r) {
  394. proxy_log(r, "STOP ","-");
  395. // If there are no clients left, no "Timeout" messages will be logged
  396. list_del_entry(config.restreamer, r);
  397. free_restreamer(r);
  398. }
  399. /*
  400. On the last try, send no-signal to clients and exit
  401. otherwise wait a little bit before trying again
  402. */
  403. #define DO_RECONNECT do \
  404. { \
  405. free_chansrc(src); \
  406. if (retries == 0) { \
  407. return -1; \
  408. } else { \
  409. if (errno != EHOSTUNREACH) /* When host is unreachable there is already a delay of ~4 secs per try so no sleep is needed */ \
  410. usleep(PROXY_RETRY_TIMEOUT * 1000); \
  411. return 1; \
  412. } \
  413. } while(0)
  414. #define FATAL_ERROR do \
  415. { \
  416. free_chansrc(src); \
  417. return -1; \
  418. } while (0)
  419. /*
  420. Returns:
  421. -1 = exit thread
  422. 1 = retry
  423. 0 = connected ok
  424. */
  425. int connect_source(RESTREAMER *r, int retries, int readbuflen, int *http_code, char *url, int depth) {
  426. CHANSRC *src = init_chansrc(url);
  427. if (depth > 4) {
  428. LOGf("ERR : Redirect loop detected, depth: %d | Channel: %s Source: %s\n", depth, r->channel->name, url);
  429. FATAL_ERROR;
  430. }
  431. if (!src) {
  432. LOGf("ERR : Can't parse channel source | Channel: %s Source: %s\n", r->channel->name, r->channel->source);
  433. FATAL_ERROR;
  434. }
  435. r->connected = 0;
  436. r->reconnect = 0;
  437. int active = 1;
  438. int dret = async_resolve_host(src->host, src->port, &(r->src_sockname), DNS_RESOLVER_TIMEOUT, &active);
  439. if (dret != 0) {
  440. if (dret == 1) {
  441. proxy_log(r, "ERR ","Can't resolve src host");
  442. proxy_set_status(r, "ERROR: Can not resolve source host");
  443. }
  444. if (dret == 2) {
  445. proxy_log(r, "ERR ","Timeout resolving src host");
  446. proxy_set_status(r, "ERROR: Dns resolve timeout");
  447. }
  448. DO_RECONNECT;
  449. }
  450. char buf[1024];
  451. *http_code = 0;
  452. if (src->sproto == tcp_sock) {
  453. r->sock = socket(PF_INET, SOCK_STREAM, 0);
  454. if (r->sock < 0) {
  455. log_perror("play(): Could not create SOCK_STREAM socket.", errno);
  456. FATAL_ERROR;
  457. }
  458. if (depth == 0) {
  459. proxy_log(r, "NEW ", "-");
  460. } else {
  461. proxy_log(r, "NEW ", url);
  462. }
  463. if (do_connect(r->sock, (struct sockaddr *)&(r->src_sockname), sizeof(r->src_sockname), PROXY_CONNECT_TIMEOUT) < 0) {
  464. LOGf("ERR : Error connecting to %s srv_fd: %i err: %s\n", r->channel->source, r->sock, strerror(errno));
  465. proxy_set_status(r, "ERROR: Can not connect to source");
  466. DO_RECONNECT;
  467. }
  468. 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",
  469. src->path, src->host, src->port, server_sig, server_ver, config.ident);
  470. buf[sizeof(buf)-1] = 0;
  471. fdwrite(r->sock, buf, strlen(buf));
  472. char redirect_to[1024];
  473. memset(redirect_to, 0, sizeof(redirect_to));
  474. char xresponse[128];
  475. memset(xresponse, 0, sizeof(xresponse));
  476. memset(buf, 0, sizeof(buf));
  477. regmatch_t res[4];
  478. while (fdgetline(r->sock,buf,sizeof(buf)-1)) {
  479. if (buf[0] == '\n' || buf[0] == '\r')
  480. break;
  481. if (strstr(buf,"HTTP/1.") != NULL) {
  482. if (regexec(&http_response,buf,3,res,0) != REG_NOMATCH) {
  483. char codestr[4];
  484. if ((unsigned long)(res[1].rm_eo - res[1].rm_so) < sizeof(xresponse)) {
  485. strncpy(xresponse, &buf[res[1].rm_so], res[1].rm_eo-res[1].rm_so);
  486. xresponse[res[1].rm_eo-res[1].rm_so] = '\0';
  487. chomp(xresponse);
  488. strncpy(codestr, &buf[res[2].rm_so], res[2].rm_eo-res[2].rm_so);
  489. codestr[3] = 0;
  490. *http_code = atoi(codestr);
  491. }
  492. }
  493. }
  494. if (*http_code == 504) { // Extract extra error code
  495. if (strstr(buf, "X-ErrorCode: ") != NULL) {
  496. *http_code = atoi(buf+13);
  497. break;
  498. }
  499. }
  500. if (strstr(buf, "Location: ") == buf) {
  501. // Remove new line
  502. char *new_line = strchr(buf, '\r');
  503. if (new_line) *new_line = '\0';
  504. new_line = strchr(buf, '\n');
  505. if (new_line) *new_line = '\0';
  506. snprintf(redirect_to, sizeof(redirect_to)-1, "%s", buf + 10);
  507. if (strstr(redirect_to, "http://") != redirect_to) {
  508. // Assume that the redirect is relative, add proto, host and port
  509. snprintf(redirect_to, sizeof(redirect_to)-1, "http://%s:%d%s",
  510. src->host, src->port, buf + 10);
  511. LOGf("DEBUG: Converted relative location to: %s | srv_fd: %i\n", redirect_to, r->sock);
  512. }
  513. }
  514. }
  515. if (*http_code == 0) { // No valid HTTP response, retry
  516. LOGf("DEBUG: Server returned not valid HTTP code | srv_fd: %i\n", r->sock);
  517. proxy_set_status(r, "ERROR: Source returned invalid HTTP code");
  518. DO_RECONNECT;
  519. }
  520. if (*http_code == 504) { // No signal, exit
  521. LOGf("ERR : Get no-signal for %s from %s on srv_fd: %i\n", r->channel->name, r->channel->source, r->sock);
  522. proxy_set_status(r, "ERROR: Source returned no-signal");
  523. FATAL_ERROR;
  524. }
  525. if (*http_code == 301 || *http_code == 302) { // Handle redirects
  526. if (redirect_to[0]) {
  527. LOGf("REDIR: Get code %i for %s from %s on srv_fd: %i, handling redirect to: %s\n", *http_code, r->channel->name, r->channel->source, r->sock, redirect_to);
  528. free_chansrc(src);
  529. shutdown_fd(&(r->sock));
  530. return connect_source(r, retries, readbuflen, http_code, redirect_to, ++depth);
  531. }
  532. // Redirect connect is OK, continue
  533. } else if (*http_code > 300) { // Unhandled or error codes, exit
  534. 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);
  535. proxy_set_status(r, "ERROR: Source returned unhandled error code");
  536. FATAL_ERROR;
  537. }
  538. // connected ok, continue
  539. } else {
  540. if (!IN_MULTICAST(ntohl(r->src_sockname.sin_addr.s_addr))) {
  541. LOGf("ERR : %s is not multicast address\n", r->channel->source);
  542. FATAL_ERROR;
  543. }
  544. struct ip_mreq mreq;
  545. struct sockaddr_in receiving_from;
  546. r->sock = socket(PF_INET, SOCK_DGRAM, 0);
  547. if (r->sock < 0) {
  548. log_perror("play(): Could not create SOCK_DGRAM socket.", errno);
  549. FATAL_ERROR;
  550. }
  551. LOGf("CONN : Listening on multicast socket %s srv_fd: %i retries left: %i\n", r->channel->source, r->sock, retries);
  552. int on = 1;
  553. setsockopt(r->sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
  554. // subscribe to multicast group
  555. memcpy(&mreq.imr_multiaddr, &(r->src_sockname.sin_addr), sizeof(struct in_addr));
  556. mreq.imr_interface.s_addr = htonl(INADDR_ANY);
  557. if (setsockopt(r->sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) {
  558. LOGf("ERR : Failed to add IP membership on %s srv_fd: %i\n", r->channel->source, r->sock);
  559. FATAL_ERROR;
  560. }
  561. // bind to the socket so data can be read
  562. memset(&receiving_from, 0, sizeof(receiving_from));
  563. receiving_from.sin_family = AF_INET;
  564. receiving_from.sin_addr = r->src_sockname.sin_addr;
  565. receiving_from.sin_port = htons(src->port);
  566. if (bind(r->sock, (struct sockaddr *) &receiving_from, sizeof(receiving_from)) < 0) {
  567. LOGf("ERR : Failed to bind to %s srv_fd: %i\n", r->channel->source, r->sock);
  568. FATAL_ERROR;
  569. }
  570. }
  571. if (setsockopt(r->sock, SOL_SOCKET, SO_RCVBUF, (const char *)&readbuflen, sizeof(readbuflen)) < 0)
  572. log_perror("play(): setsockopt(SO_RCVBUF)", errno);
  573. proxy_set_status(r, "Connected");
  574. r->connected = 1;
  575. free_chansrc(src);
  576. return 0;
  577. }
  578. int check_restreamer_state(RESTREAMER *r) {
  579. if (r->dienow) {
  580. // LOGf("PROXY: Forced disconnect on srv_fd: %i | Channel: %s Source: %s\n", r->sock, r->channel->name, r->channel->source);
  581. proxy_set_status(r, "Dying");
  582. return 2;
  583. }
  584. if (r->reconnect) {
  585. LOGf("PROXY: Forced reconnect on srv_fd: %i | Channel: %s Source: %s\n", r->sock, r->channel->name, r->channel->source);
  586. proxy_set_status(r, "Forced reconnect");
  587. return 1;
  588. }
  589. return 0;
  590. }
  591. #define MAX_ZERO_READS 3
  592. /* Start: 3 seconds on connect */
  593. /* In connection: Max UDP timeout == 3 seconds (read) + 2 seconds (connect) == 5 seconds */
  594. #define UDP_READ_RETRIES 3
  595. #define UDP_READ_TIMEOUT 1000
  596. /* Start: 1/4 seconds on connect */
  597. /* In connection: Max TCP timeout == 5 seconds (read) + 2 seconds (connect) == 7 seconds */
  598. /* In connection: Max TCP timeout == 5 seconds (read) + 8 seconds (connect, host unrch) == 13 seconds */
  599. #define TCP_READ_RETRIES 5
  600. #define TCP_READ_TIMEOUT 1000
  601. /*
  602. Returns:
  603. 0 = synced ok
  604. 1 = not synced, reconnect
  605. */
  606. int mpeg_sync(RESTREAMER *r, int proxysock, char *channel, channel_source source_proto) {
  607. time_t sync_start = time(NULL);
  608. unsigned int sync_packets = 0;
  609. unsigned int read_bytes = 0;
  610. char syncframe[188];
  611. int _timeout = TCP_READ_TIMEOUT;
  612. int _retries = TCP_READ_RETRIES;
  613. if (source_proto == udp_sock) {
  614. _timeout = UDP_READ_TIMEOUT;
  615. _retries = UDP_READ_RETRIES;
  616. }
  617. do {
  618. resync:
  619. if (fdread_ex(proxysock, syncframe, 1, _timeout, _retries, 1) != 1) {
  620. LOGf("DEBUG: mpeg_sync fdread() timeout | Channel: %s\n", channel);
  621. proxy_set_status(r, "ERROR: fdread() timeout while syncing mpeg");
  622. return 1; // reconnect
  623. }
  624. // LOGf("DEBUG: Read 0x%02x Offset %u Sync: %u\n", (uint8_t)syncframe[0], read_bytes, sync_packets);
  625. read_bytes++;
  626. if (syncframe[0] == 0x47) {
  627. ssize_t rdsz = fdread_ex(proxysock, syncframe, 188-1, _timeout, _retries, 1);
  628. if (rdsz != 188-1) {
  629. LOGf("DEBUG: mpeg_sync fdread() timeout | Channel: %s\n", channel);
  630. proxy_set_status(r, "ERROR: fdread() timeout while syncing mpeg");
  631. return 1; // reconnect
  632. }
  633. read_bytes += 188-1;
  634. if (++sync_packets == 7) // sync 7 packets
  635. break;
  636. goto resync;
  637. } else {
  638. sync_packets = 0;
  639. }
  640. if (read_bytes > FRAME_PACKET_SIZE) { // Can't sync in 1316 bytes
  641. LOGf("DEBUG: Can't sync after %d bytes | Channel: %s\n", FRAME_PACKET_SIZE, channel);
  642. proxy_set_status(r, "ERROR: Can not sync mpeg");
  643. return 1; // reconnect
  644. }
  645. if (sync_start+2 <= time(NULL)) { // Do not sync in two seconds
  646. LOGf("DEBUG: Timeout while syncing (read %u bytes) | Channel: %s\n", read_bytes, channel);
  647. proxy_set_status(r, "ERROR: Timeout while syncing mpeg");
  648. return 1; // reconnect
  649. }
  650. } while (1);
  651. pthread_rwlock_wrlock(&r->lock);
  652. r->conn_ts = time(NULL);
  653. r->read_bytes = read_bytes;
  654. pthread_rwlock_unlock(&r->lock);
  655. LOGf("SYNC : TS synced after %u bytes | Channel: %s\n", read_bytes-FRAME_PACKET_SIZE, channel);
  656. proxy_set_status(r, "Working");
  657. return 0;
  658. }
  659. char reset[FRAME_PACKET_SIZE] = {
  660. 0x47,0x40,0x00,0x10,0x00,0x00,0xB0,0x09,0x27,0x10,0xC1,0x00,
  661. 0x00,0x3C,0xDD,0xFF,0xB8,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  662. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  663. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  664. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  665. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  666. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  667. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  668. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  669. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  670. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xF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,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  767. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  768. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  769. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF
  770. };
  771. /*
  772. Return value:
  773. ret == 0 - No valid payload was found
  774. ret & 0x01 == 0x01 - PES was found
  775. ret & 0x02 == 0x02 - PTS was found
  776. ret & 0x04 == 0x04 - DTS was found
  777. */
  778. static unsigned int ts_have_valid_pes(uint8_t *buf, unsigned int buffer_size) {
  779. unsigned int ret = 0;
  780. uint8_t *buf_end = buf + buffer_size;
  781. while (buf < buf_end && ts_validate(buf)) {
  782. uint16_t header_size = TS_HEADER_SIZE + (ts_has_adaptation(buf) ? 1 : 0) + ts_get_adaptation(buf);
  783. if (ts_get_unitstart(buf) && ts_has_payload(buf) && header_size + PES_HEADER_SIZE_PTS <= TS_SIZE) {
  784. //printf("Got payload\n");
  785. if (pes_validate(buf + header_size) && pes_get_streamid(buf + header_size) != PES_STREAM_ID_PRIVATE_2 && pes_validate_header(buf + header_size)) {
  786. //printf("Got PES\n");
  787. ret |= 0x01;
  788. if (pes_has_pts(buf + header_size) && pes_validate_pts(buf + header_size)) {
  789. ret |= 0x02;
  790. //printf("Got PTS\n");
  791. if (header_size + PES_HEADER_SIZE_PTSDTS <= TS_SIZE && pes_has_dts(buf + header_size) && pes_validate_dts(buf + header_size)) {
  792. //printf("Got DTS\n");
  793. ret |= 0x04;
  794. }
  795. }
  796. }
  797. }
  798. buf += TS_SIZE;
  799. }
  800. return ret;
  801. }
  802. void * proxy_ts_stream(void *self) {
  803. RESTREAMER *r = self;
  804. char buf[FRAME_PACKET_SIZE];
  805. signal(SIGPIPE, SIG_IGN);
  806. int http_code = 0;
  807. while (1) {
  808. r->conn_ts = 0;
  809. r->read_bytes = 0;
  810. int result = connect_source(self, 1, FRAME_PACKET_SIZE * 1000, &http_code, r->channel->source, 0);
  811. if (result > 0)
  812. goto RECONNECT;
  813. channel_source sproto = get_sproto(r->channel->source);
  814. int mpgsync = mpeg_sync(r, r->sock, r->channel->name, sproto);
  815. if (mpgsync == 1) // Timeout
  816. goto RECONNECT;
  817. ssize_t readen, written;
  818. int max_zero_reads = MAX_ZERO_READS;
  819. int send_reset = send_reset_opt;
  820. for (;;) {
  821. switch (check_restreamer_state(r)) {
  822. case 1: goto RECONNECT; // r->reconnect is on
  823. case 2: goto QUIT; // r->dienow is on
  824. }
  825. if (sproto == tcp_sock) {
  826. readen = fdread_ex(r->sock, buf, FRAME_PACKET_SIZE, TCP_READ_TIMEOUT, TCP_READ_RETRIES, 1);
  827. } else {
  828. readen = fdread_ex(r->sock, buf, FRAME_PACKET_SIZE, UDP_READ_TIMEOUT, UDP_READ_RETRIES, 0);
  829. }
  830. if (readen < 0)
  831. goto RECONNECT;
  832. if (readen == 0) { // ho, hum, wtf is going on here?
  833. LOGf("PROXY: zero read on srv_fd: %i | Channel: %s Source: %s\n", r->sock, r->channel->name, r->channel->source);
  834. if (--max_zero_reads == 0) {
  835. 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);
  836. proxy_set_status(r, "ERROR: Too many zero reads");
  837. break;
  838. }
  839. continue;
  840. }
  841. max_zero_reads = MAX_ZERO_READS;
  842. // Fill short frame with NULL packets
  843. if (readen < FRAME_PACKET_SIZE) {
  844. //LOGf("DEBUG: Short read (%d) on retreamer srv_fd: %i | Channel: %s\n", readen, sock, chan->name);
  845. memcpy(buf+readen, TS_NULL_FRAME+readen, FRAME_PACKET_SIZE - readen);
  846. }
  847. pthread_rwlock_wrlock(&r->lock);
  848. r->read_bytes += readen;
  849. pthread_rwlock_unlock(&r->lock);
  850. if (send_reset) {
  851. send_reset = 0;
  852. fdwrite(r->clientsock, reset, FRAME_PACKET_SIZE);
  853. }
  854. if (config.detect_encrypted_input) {
  855. int64_t now = get_time();
  856. int ret;
  857. if ((ret = ts_have_valid_pes((uint8_t *)buf, readen)) == 0) { // Is the output encrypted?
  858. /* The output is encrypted, check if 1000 ms have passed and if such, notify that we probably have invalid key */
  859. if (now > r->last_decrypted_input_ts + 500000) {
  860. proxy_log(r, "ERR ","Scrambled input");
  861. proxy_set_status(r, "ERROR: Encrypted stream input");
  862. goto RECONNECT;
  863. }
  864. } else {
  865. r->last_decrypted_input_ts = now;
  866. }
  867. }
  868. written = fdwrite(r->clientsock, buf, FRAME_PACKET_SIZE);
  869. if (written == -1) {
  870. 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);
  871. connect_destination(r);
  872. }
  873. }
  874. LOGf("DEBUG: fdread timeout restreamer srv_fd: %i | Channel: %s\n", r->sock, r->channel->name);
  875. proxy_set_status(r, "ERROR: Read timeout");
  876. RECONNECT:
  877. pthread_rwlock_wrlock(&r->lock);
  878. r->conn_ts = 0;
  879. pthread_rwlock_unlock(&r->lock);
  880. LOGf("DEBUG: reconnect srv_fd: %i | Channel: %s\n", r->sock, r->channel->name);
  881. proxy_set_status(r, "Reconnecting");
  882. shutdown_fd(&(r->sock));
  883. next_channel_source(r->channel);
  884. continue;
  885. QUIT:
  886. LOGf("DEBUG: quit srv_fd: %i | Channel: %s\n", r->sock, r->channel->name);
  887. break;
  888. }
  889. proxy_close(r);
  890. return 0;
  891. }
  892. static int copyright_shown = 0;
  893. void show_usage(int ident_only) {
  894. if (!copyright_shown) {
  895. printf("%s %s\n", server_sig, server_ver);
  896. puts(copyright);
  897. puts("");
  898. copyright_shown = 1;
  899. }
  900. if (ident_only)
  901. return;
  902. puts("Usage: tomcast [opts] -c config_file");
  903. puts("");
  904. puts(" Options:");
  905. puts("\t-c file\t\tChannels configuration file");
  906. puts("\t-i ident\tServer ident. Must be formated as PROVIDER/SERVER");
  907. puts("\t-d pidfile\tDaemonize and write daemon pid into pidfile");
  908. puts("\t-t ttl\t\tSet multicast ttl (default: 1)");
  909. puts("\t-o ip\t\tOutput interface address (default: 0.0.0.0)");
  910. puts("\t-l host\t\tSyslog host (default: disabled)");
  911. puts("\t-L port\t\tSyslog port (default: 514)");
  912. puts("\t-R\t\tSend reset packets when changing sources.");
  913. puts("\t-E\t\tDetect encrypted input (default: false)");
  914. puts("");
  915. puts(" Web server options:");
  916. puts("\t-b addr\t\tLocal IP address to bind. (default: 0.0.0.0)");
  917. puts("\t-p port\t\tPort to listen. (default: disabled)");
  918. puts("");
  919. }
  920. void set_ident(char *new_ident, struct config *cfg) {
  921. cfg->ident = new_ident;
  922. cfg->logident = strdup(new_ident);
  923. char *c = cfg->logident;
  924. while (*c) {
  925. if (*c=='/')
  926. *c='-';
  927. c++;
  928. }
  929. }
  930. void parse_options(int argc, char **argv, struct config *cfg) {
  931. int j, ttl;
  932. cfg->server_socket = -1;
  933. cfg->logport = 514;
  934. pthread_mutex_init(&cfg->channels_lock, NULL);
  935. while ((j = getopt(argc, argv, "i:b:p:c:d:t:o:l:L:REHh")) != -1) {
  936. switch (j) {
  937. case 'b':
  938. cfg->server_addr = optarg;
  939. break;
  940. case 'p':
  941. cfg->server_port = atoi(optarg);
  942. break;
  943. case 'i':
  944. set_ident(optarg, cfg);
  945. break;
  946. case 'c':
  947. cfg->channels_file = optarg;
  948. break;
  949. case 'd':
  950. cfg->pidfile = optarg;
  951. break;
  952. case 'o':
  953. if (inet_aton(optarg, &output_intf) == 0) {
  954. fprintf(stderr, "Invalid interface address: %s\n", optarg);
  955. exit(1);
  956. }
  957. break;
  958. case 't':
  959. ttl = atoi(optarg);
  960. multicast_ttl = (ttl && ttl < 127) ? ttl : 1;
  961. break;
  962. case 'l':
  963. cfg->loghost = optarg;
  964. cfg->syslog_active = 1;
  965. break;
  966. case 'L':
  967. cfg->logport = atoi(optarg);
  968. break;
  969. case 'R':
  970. send_reset_opt = 1;
  971. break;
  972. case 'E':
  973. cfg->detect_encrypted_input = 1;
  974. break;
  975. case 'H':
  976. case 'h':
  977. show_usage(0);
  978. exit(0);
  979. break;
  980. }
  981. }
  982. if (!cfg->channels_file) {
  983. show_usage(0);
  984. fprintf(stderr, "ERROR: No channels file is set (use -c option).\n");
  985. exit(1);
  986. }
  987. if (!cfg->ident) {
  988. set_ident("unixsol/tomcast", cfg);
  989. }
  990. printf("Configuration:\n");
  991. printf("\tServer ident : %s\n", cfg->ident);
  992. printf("\tChannels file : %s\n", cfg->channels_file);
  993. printf("\tOutput iface addr : %s\n", inet_ntoa(output_intf));
  994. printf("\tMulticast ttl : %d\n", multicast_ttl);
  995. if (cfg->syslog_active) {
  996. printf("\tSyslog host : %s\n", cfg->loghost);
  997. printf("\tSyslog port : %d\n", cfg->logport);
  998. } else {
  999. printf("\tSyslog disabled.\n");
  1000. }
  1001. if (send_reset_opt)
  1002. printf("\tSend reset packets.\n");
  1003. if (cfg->detect_encrypted_input)
  1004. printf("\tDetect encrypted input.\n");
  1005. if (cfg->pidfile) {
  1006. printf("\tDaemonize : %s\n", cfg->pidfile);
  1007. } else {
  1008. printf("\tDo not daemonize.\n");
  1009. }
  1010. if (cfg->server_port) {
  1011. init_server_socket(cfg->server_addr, cfg->server_port, &cfg->server, &cfg->server_socket);
  1012. printf("\tStarting web srv : http://%s:%d/status (sock: %d)\n",
  1013. cfg->server_addr ? cfg->server_addr : "*", cfg->server_port, cfg->server_socket);
  1014. } else {
  1015. printf("\tNo web server\n");
  1016. }
  1017. }
  1018. void init_vars(struct config *cfg) {
  1019. cfg->restreamer = list_new("restreamer");
  1020. regcomp(&http_response, "^HTTP/1.[0-1] (([0-9]{3}) .*)", REG_EXTENDED);
  1021. memset(&TS_NULL_FRAME, 0xff, FRAME_PACKET_SIZE);
  1022. int i;
  1023. for (i=0; i<FRAME_PACKET_SIZE; i=i+188) {
  1024. TS_NULL_FRAME[i+0] = 0x47;
  1025. TS_NULL_FRAME[i+1] = 0x1f;
  1026. TS_NULL_FRAME[i+2] = 0xff;
  1027. TS_NULL_FRAME[i+3] = 0x00;
  1028. }
  1029. }
  1030. void spawn_proxy_threads(struct config *cfg) {
  1031. LNODE *lc, *lctmp;
  1032. LNODE *lr, *lrtmp;
  1033. int spawned = 0;
  1034. list_for_each(cfg->chanconf, lc, lctmp) {
  1035. CHANNEL *c = lc->data;
  1036. int restreamer_active = 0;
  1037. list_lock(cfg->restreamer);
  1038. list_for_each(cfg->restreamer, lr, lrtmp) {
  1039. RESTREAMER *r = lr->data;
  1040. if (strcmp(r->name, c->name)==0) {
  1041. restreamer_active = 1;
  1042. break;
  1043. }
  1044. }
  1045. list_unlock(cfg->restreamer);
  1046. if (!restreamer_active) {
  1047. RESTREAMER *nr = new_restreamer(c->name, c);
  1048. if (nr->clientsock < 0) {
  1049. LOGf("Error creating proxy socket for %s\n", c->name);
  1050. free_restreamer(nr);
  1051. } else {
  1052. list_add(cfg->restreamer, nr);
  1053. if (pthread_create(&nr->thread, NULL, &proxy_ts_stream, nr) == 0) {
  1054. spawned++;
  1055. pthread_detach(nr->thread);
  1056. } else {
  1057. LOGf("Error creating proxy for %s\n", c->name);
  1058. }
  1059. }
  1060. }
  1061. }
  1062. LOGf("INFO : %d proxy threads spawned\n", spawned);
  1063. }
  1064. void kill_proxy_threads(struct config *cfg) {
  1065. LNODE *l, *tmp;
  1066. int killed = 0;
  1067. list_lock(cfg->restreamer);
  1068. list_for_each(cfg->restreamer, l, tmp) {
  1069. RESTREAMER *r = l->data;
  1070. r->dienow = 1;
  1071. killed++;
  1072. }
  1073. list_unlock(cfg->restreamer);
  1074. LOGf("INFO : %d proxy threads killed\n", killed);
  1075. }
  1076. int keep_going = 1;
  1077. void signal_quit(int sig) {
  1078. keep_going = 0;
  1079. kill_proxy_threads(&config);
  1080. usleep(500000);
  1081. LOGf("KILL : Signal %i | %s %s (%s)\n", sig, server_sig, server_ver, config.ident);
  1082. usleep(100000);
  1083. log_close();
  1084. if (config.pidfile && strlen(config.pidfile))
  1085. unlink(config.pidfile);
  1086. signal(sig, SIG_DFL);
  1087. raise(sig);
  1088. }
  1089. struct config *get_config(void) {
  1090. return &config;
  1091. }
  1092. void do_reconnect(int sig) {
  1093. (void)sig;
  1094. LNODE *l, *tmp;
  1095. list_lock(config.restreamer);
  1096. list_for_each(config.restreamer, l, tmp) {
  1097. RESTREAMER *r = l->data;
  1098. r->reconnect = 1;
  1099. }
  1100. list_unlock(config.restreamer);
  1101. }
  1102. void do_reconf(int sig) {
  1103. (void)sig;
  1104. load_channels_config(&config);
  1105. spawn_proxy_threads(&config);
  1106. }
  1107. void init_signals(void) {
  1108. signal(SIGCHLD, SIG_IGN);
  1109. signal(SIGPIPE, SIG_IGN);
  1110. signal(SIGHUP , do_reconf);
  1111. signal(SIGUSR1, do_reconnect);
  1112. signal(SIGINT , signal_quit);
  1113. signal(SIGTERM, signal_quit);
  1114. }
  1115. void do_daemonize(struct config *cfg) {
  1116. if (!cfg->pidfile)
  1117. return;
  1118. fprintf(stderr, "Daemonizing.\n");
  1119. pid_t pid = fork();
  1120. if (pid > 0) {
  1121. FILE *F = fopen(cfg->pidfile,"w");
  1122. if (F) {
  1123. fprintf(F,"%i\n",pid);
  1124. fclose(F);
  1125. }
  1126. exit(0);
  1127. }
  1128. // Child process continues...
  1129. setsid(); // request a new session (job control)
  1130. freopen("/dev/null", "r", stdin);
  1131. freopen("/dev/null", "w", stdout);
  1132. freopen("/dev/null", "w", stderr);
  1133. }
  1134. /* Must be called after daemonize! */
  1135. void init_logger(struct config *cfg) {
  1136. if (cfg->syslog_active)
  1137. fprintf(stderr, "Logging to %s:%d\n", cfg->loghost, cfg->logport);
  1138. log_init(cfg->logident, cfg->syslog_active, cfg->pidfile == NULL, cfg->loghost, cfg->logport);
  1139. }
  1140. int main(int argc, char **argv) {
  1141. set_http_response_server_ident(server_sig, server_ver);
  1142. show_usage(1); // Show copyright and version
  1143. init_vars(&config);
  1144. parse_options(argc, argv, &config);
  1145. do_daemonize(&config);
  1146. init_logger(&config);
  1147. init_signals();
  1148. LOGf("INIT : %s %s (%s)\n" , server_sig, server_ver, config.ident);
  1149. load_channels_config(&config);
  1150. spawn_proxy_threads(&config);
  1151. web_server_start(&config);
  1152. do {
  1153. sleep(60);
  1154. } while(1);
  1155. signal_quit(15);
  1156. exit(0);
  1157. }