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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179
  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: %s Chan: %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, char *url, int depth) {
  402. CHANSRC *src = init_chansrc(url);
  403. if (depth > 4) {
  404. LOGf("ERR : Redirect loop detected, depth: %d | Channel: %s Source: %s\n", depth, r->channel->name, url);
  405. FATAL_ERROR;
  406. }
  407. if (!src) {
  408. LOGf("ERR : Can't parse channel source | Channel: %s Source: %s\n", r->channel->name, r->channel->source);
  409. FATAL_ERROR;
  410. }
  411. r->connected = 0;
  412. r->reconnect = 0;
  413. int active = 1;
  414. int dret = async_resolve_host(src->host, src->port, &(r->src_sockname), DNS_RESOLVER_TIMEOUT, &active);
  415. if (dret != 0) {
  416. if (dret == 1) {
  417. proxy_log(r, "ERR ","Can't resolve src host");
  418. proxy_set_status(r, "ERROR: Can not resolve source host");
  419. }
  420. if (dret == 2) {
  421. proxy_log(r, "ERR ","Timeout resolving src host");
  422. proxy_set_status(r, "ERROR: Dns resolve timeout");
  423. }
  424. DO_RECONNECT;
  425. }
  426. char buf[1024];
  427. *http_code = 0;
  428. if (src->sproto == tcp_sock) {
  429. r->sock = socket(PF_INET, SOCK_STREAM, 0);
  430. if (r->sock < 0) {
  431. log_perror("play(): Could not create SOCK_STREAM socket.", errno);
  432. FATAL_ERROR;
  433. }
  434. if (depth == 0) {
  435. proxy_log(r, "NEW ", "-");
  436. } else {
  437. proxy_log(r, "NEW ", url);
  438. }
  439. if (do_connect(r->sock, (struct sockaddr *)&(r->src_sockname), sizeof(r->src_sockname), PROXY_CONNECT_TIMEOUT) < 0) {
  440. LOGf("ERR : Error connecting to %s srv_fd: %i err: %s\n", r->channel->source, r->sock, strerror(errno));
  441. proxy_set_status(r, "ERROR: Can not connect to source");
  442. DO_RECONNECT;
  443. }
  444. 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",
  445. src->path, src->host, src->port, server_sig, server_ver, config.ident);
  446. buf[sizeof(buf)-1] = 0;
  447. fdwrite(r->sock, buf, strlen(buf));
  448. char redirect_to[1024];
  449. memset(redirect_to, 0, sizeof(redirect_to));
  450. char xresponse[128];
  451. memset(xresponse, 0, sizeof(xresponse));
  452. memset(buf, 0, sizeof(buf));
  453. regmatch_t res[4];
  454. while (fdgetline(r->sock,buf,sizeof(buf)-1)) {
  455. if (buf[0] == '\n' || buf[0] == '\r')
  456. break;
  457. if (strstr(buf,"HTTP/1.") != NULL) {
  458. if (regexec(&http_response,buf,3,res,0) != REG_NOMATCH) {
  459. char codestr[4];
  460. if ((unsigned long)(res[1].rm_eo - res[1].rm_so) < sizeof(xresponse)) {
  461. strncpy(xresponse, &buf[res[1].rm_so], res[1].rm_eo-res[1].rm_so);
  462. xresponse[res[1].rm_eo-res[1].rm_so] = '\0';
  463. chomp(xresponse);
  464. strncpy(codestr, &buf[res[2].rm_so], res[2].rm_eo-res[2].rm_so);
  465. codestr[3] = 0;
  466. *http_code = atoi(codestr);
  467. }
  468. }
  469. }
  470. if (*http_code == 504) { // Extract extra error code
  471. if (strstr(buf, "X-ErrorCode: ") != NULL) {
  472. *http_code = atoi(buf+13);
  473. break;
  474. }
  475. }
  476. if (strstr(buf, "Location: ") == buf) {
  477. // Remove new line
  478. char *new_line = strchr(buf, '\r');
  479. if (new_line) *new_line = '\0';
  480. new_line = strchr(buf, '\n');
  481. if (new_line) *new_line = '\0';
  482. snprintf(redirect_to, sizeof(redirect_to)-1, "%s", buf + 10);
  483. if (strstr(redirect_to, "http://") != redirect_to) {
  484. // Assume that the redirect is relative, add proto, host and port
  485. snprintf(redirect_to, sizeof(redirect_to)-1, "http://%s:%d%s",
  486. src->host, src->port, buf + 10);
  487. LOGf("DEBUG: Converted relative location to: %s | srv_fd: %i\n", redirect_to, r->sock);
  488. }
  489. }
  490. }
  491. if (*http_code == 0) { // No valid HTTP response, retry
  492. LOGf("DEBUG: Server returned not valid HTTP code | srv_fd: %i\n", r->sock);
  493. proxy_set_status(r, "ERROR: Source returned invalid HTTP code");
  494. DO_RECONNECT;
  495. }
  496. if (*http_code == 504) { // No signal, exit
  497. LOGf("ERR : Get no-signal for %s from %s on srv_fd: %i\n", r->channel->name, r->channel->source, r->sock);
  498. proxy_set_status(r, "ERROR: Source returned no-signal");
  499. FATAL_ERROR;
  500. }
  501. if (*http_code == 301 || *http_code == 302) { // Handle redirects
  502. if (redirect_to[0]) {
  503. 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);
  504. free_chansrc(src);
  505. shutdown_fd(&(r->sock));
  506. return connect_source(r, retries, readbuflen, http_code, redirect_to, ++depth);
  507. }
  508. // Redirect connect is OK, continue
  509. } else if (*http_code > 300) { // Unhandled or error codes, exit
  510. 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);
  511. proxy_set_status(r, "ERROR: Source returned unhandled error code");
  512. FATAL_ERROR;
  513. }
  514. // connected ok, continue
  515. } else {
  516. if (!IN_MULTICAST(ntohl(r->src_sockname.sin_addr.s_addr))) {
  517. LOGf("ERR : %s is not multicast address\n", r->channel->source);
  518. FATAL_ERROR;
  519. }
  520. struct ip_mreq mreq;
  521. struct sockaddr_in receiving_from;
  522. r->sock = socket(PF_INET, SOCK_DGRAM, 0);
  523. if (r->sock < 0) {
  524. log_perror("play(): Could not create SOCK_DGRAM socket.", errno);
  525. FATAL_ERROR;
  526. }
  527. LOGf("CONN : Listening on multicast socket %s srv_fd: %i retries left: %i\n", r->channel->source, r->sock, retries);
  528. int on = 1;
  529. setsockopt(r->sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
  530. // subscribe to multicast group
  531. memcpy(&mreq.imr_multiaddr, &(r->src_sockname.sin_addr), sizeof(struct in_addr));
  532. mreq.imr_interface.s_addr = htonl(INADDR_ANY);
  533. if (setsockopt(r->sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) {
  534. LOGf("ERR : Failed to add IP membership on %s srv_fd: %i\n", r->channel->source, r->sock);
  535. FATAL_ERROR;
  536. }
  537. // bind to the socket so data can be read
  538. memset(&receiving_from, 0, sizeof(receiving_from));
  539. receiving_from.sin_family = AF_INET;
  540. receiving_from.sin_addr = r->src_sockname.sin_addr;
  541. receiving_from.sin_port = htons(src->port);
  542. if (bind(r->sock, (struct sockaddr *) &receiving_from, sizeof(receiving_from)) < 0) {
  543. LOGf("ERR : Failed to bind to %s srv_fd: %i\n", r->channel->source, r->sock);
  544. FATAL_ERROR;
  545. }
  546. }
  547. if (setsockopt(r->sock, SOL_SOCKET, SO_RCVBUF, (const char *)&readbuflen, sizeof(readbuflen)) < 0)
  548. log_perror("play(): setsockopt(SO_RCVBUF)", errno);
  549. proxy_set_status(r, "Connected");
  550. r->connected = 1;
  551. free_chansrc(src);
  552. return 0;
  553. }
  554. int check_restreamer_state(RESTREAMER *r) {
  555. if (r->dienow) {
  556. // LOGf("PROXY: Forced disconnect on srv_fd: %i | Channel: %s Source: %s\n", r->sock, r->channel->name, r->channel->source);
  557. proxy_set_status(r, "Dying");
  558. return 2;
  559. }
  560. if (r->reconnect) {
  561. LOGf("PROXY: Forced reconnect on srv_fd: %i | Channel: %s Source: %s\n", r->sock, r->channel->name, r->channel->source);
  562. proxy_set_status(r, "Forced reconnect");
  563. return 1;
  564. }
  565. return 0;
  566. }
  567. #define MAX_ZERO_READS 3
  568. /* Start: 3 seconds on connect */
  569. /* In connection: Max UDP timeout == 3 seconds (read) + 2 seconds (connect) == 5 seconds */
  570. #define UDP_READ_RETRIES 3
  571. #define UDP_READ_TIMEOUT 1000
  572. /* Start: 1/4 seconds on connect */
  573. /* In connection: Max TCP timeout == 5 seconds (read) + 2 seconds (connect) == 7 seconds */
  574. /* In connection: Max TCP timeout == 5 seconds (read) + 8 seconds (connect, host unrch) == 13 seconds */
  575. #define TCP_READ_RETRIES 5
  576. #define TCP_READ_TIMEOUT 1000
  577. /*
  578. Returns:
  579. 0 = synced ok
  580. 1 = not synced, reconnect
  581. */
  582. int mpeg_sync(RESTREAMER *r, int proxysock, char *channel, channel_source source_proto) {
  583. time_t sync_start = time(NULL);
  584. unsigned int sync_packets = 0;
  585. unsigned int read_bytes = 0;
  586. char syncframe[188];
  587. int _timeout = TCP_READ_TIMEOUT;
  588. int _retries = TCP_READ_RETRIES;
  589. if (source_proto == udp_sock) {
  590. _timeout = UDP_READ_TIMEOUT;
  591. _retries = UDP_READ_RETRIES;
  592. }
  593. do {
  594. resync:
  595. if (fdread_ex(proxysock, syncframe, 1, _timeout, _retries, 1) != 1) {
  596. LOGf("DEBUG: mpeg_sync fdread() timeout | Channel: %s\n", channel);
  597. proxy_set_status(r, "ERROR: fdread() timeout while syncing mpeg");
  598. return 1; // reconnect
  599. }
  600. // LOGf("DEBUG: Read 0x%02x Offset %u Sync: %u\n", (uint8_t)syncframe[0], read_bytes, sync_packets);
  601. read_bytes++;
  602. if (syncframe[0] == 0x47) {
  603. ssize_t rdsz = fdread_ex(proxysock, syncframe, 188-1, _timeout, _retries, 1);
  604. if (rdsz != 188-1) {
  605. LOGf("DEBUG: mpeg_sync fdread() timeout | Channel: %s\n", channel);
  606. proxy_set_status(r, "ERROR: fdread() timeout while syncing mpeg");
  607. return 1; // reconnect
  608. }
  609. read_bytes += 188-1;
  610. if (++sync_packets == 7) // sync 7 packets
  611. break;
  612. goto resync;
  613. } else {
  614. sync_packets = 0;
  615. }
  616. if (read_bytes > FRAME_PACKET_SIZE) { // Can't sync in 1316 bytes
  617. LOGf("DEBUG: Can't sync after %d bytes | Channel: %s\n", FRAME_PACKET_SIZE, channel);
  618. proxy_set_status(r, "ERROR: Can not sync mpeg");
  619. return 1; // reconnect
  620. }
  621. if (sync_start+2 <= time(NULL)) { // Do not sync in two seconds
  622. LOGf("DEBUG: Timeout while syncing (read %u bytes) | Channel: %s\n", read_bytes, channel);
  623. proxy_set_status(r, "ERROR: Timeout while syncing mpeg");
  624. return 1; // reconnect
  625. }
  626. } while (1);
  627. pthread_rwlock_wrlock(&r->lock);
  628. r->conn_ts = time(NULL);
  629. r->read_bytes = read_bytes;
  630. pthread_rwlock_unlock(&r->lock);
  631. LOGf("SYNC : TS synced after %u bytes | Channel: %s\n", read_bytes-FRAME_PACKET_SIZE, channel);
  632. proxy_set_status(r, "Working");
  633. return 0;
  634. }
  635. char reset[FRAME_PACKET_SIZE] = {
  636. 0x47,0x40,0x00,0x10,0x00,0x00,0xB0,0x09,0x27,0x10,0xC1,0x00,
  637. 0x00,0x3C,0xDD,0xFF,0xB8,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  638. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  639. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x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F,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  736. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  737. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  738. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  739. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  740. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  741. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  742. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  743. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  744. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  745. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF
  746. };
  747. void * proxy_ts_stream(void *self) {
  748. RESTREAMER *r = self;
  749. char buf[FRAME_PACKET_SIZE];
  750. signal(SIGPIPE, SIG_IGN);
  751. int http_code = 0;
  752. while (1) {
  753. r->conn_ts = 0;
  754. r->read_bytes = 0;
  755. int result = connect_source(self, 1, FRAME_PACKET_SIZE * 1000, &http_code, r->channel->source, 0);
  756. if (result > 0)
  757. goto RECONNECT;
  758. channel_source sproto = get_sproto(r->channel->source);
  759. int mpgsync = mpeg_sync(r, r->sock, r->channel->name, sproto);
  760. if (mpgsync == 1) // Timeout
  761. goto RECONNECT;
  762. ssize_t readen, written;
  763. int max_zero_reads = MAX_ZERO_READS;
  764. int send_reset = send_reset_opt;
  765. for (;;) {
  766. switch (check_restreamer_state(r)) {
  767. case 1: goto RECONNECT; // r->reconnect is on
  768. case 2: goto QUIT; // r->dienow is on
  769. }
  770. if (sproto == tcp_sock) {
  771. readen = fdread_ex(r->sock, buf, FRAME_PACKET_SIZE, TCP_READ_TIMEOUT, TCP_READ_RETRIES, 1);
  772. } else {
  773. readen = fdread_ex(r->sock, buf, FRAME_PACKET_SIZE, UDP_READ_TIMEOUT, UDP_READ_RETRIES, 0);
  774. }
  775. if (readen < 0)
  776. goto RECONNECT;
  777. if (readen == 0) { // ho, hum, wtf is going on here?
  778. LOGf("PROXY: zero read on srv_fd: %i | Channel: %s Source: %s\n", r->sock, r->channel->name, r->channel->source);
  779. if (--max_zero_reads == 0) {
  780. 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);
  781. proxy_set_status(r, "ERROR: Too many zero reads");
  782. break;
  783. }
  784. continue;
  785. }
  786. max_zero_reads = MAX_ZERO_READS;
  787. // Fill short frame with NULL packets
  788. if (readen < FRAME_PACKET_SIZE) {
  789. //LOGf("DEBUG: Short read (%d) on retreamer srv_fd: %i | Channel: %s\n", readen, sock, chan->name);
  790. memcpy(buf+readen, TS_NULL_FRAME+readen, FRAME_PACKET_SIZE - readen);
  791. }
  792. pthread_rwlock_wrlock(&r->lock);
  793. r->read_bytes += readen;
  794. pthread_rwlock_unlock(&r->lock);
  795. if (send_reset) {
  796. send_reset = 0;
  797. fdwrite(r->clientsock, reset, FRAME_PACKET_SIZE);
  798. }
  799. written = fdwrite(r->clientsock, buf, FRAME_PACKET_SIZE);
  800. if (written == -1) {
  801. 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);
  802. connect_destination(r);
  803. }
  804. }
  805. LOGf("DEBUG: fdread timeout restreamer srv_fd: %i | Channel: %s\n", r->sock, r->channel->name);
  806. proxy_set_status(r, "ERROR: Read timeout");
  807. RECONNECT:
  808. pthread_rwlock_wrlock(&r->lock);
  809. r->conn_ts = 0;
  810. pthread_rwlock_unlock(&r->lock);
  811. LOGf("DEBUG: reconnect srv_fd: %i | Channel: %s\n", r->sock, r->channel->name);
  812. proxy_set_status(r, "Reconnecting");
  813. shutdown_fd(&(r->sock));
  814. next_channel_source(r->channel);
  815. continue;
  816. QUIT:
  817. LOGf("DEBUG: quit srv_fd: %i | Channel: %s\n", r->sock, r->channel->name);
  818. break;
  819. }
  820. proxy_close(r);
  821. return 0;
  822. }
  823. static int copyright_shown = 0;
  824. void show_usage(int ident_only) {
  825. if (!copyright_shown) {
  826. printf("%s %s\n", server_sig, server_ver);
  827. puts(copyright);
  828. puts("");
  829. copyright_shown = 1;
  830. }
  831. if (ident_only)
  832. return;
  833. puts("Usage: tomcast [opts] -c config_file");
  834. puts("");
  835. puts(" Options:");
  836. puts("\t-c file\t\tChannels configuration file");
  837. puts("\t-i ident\tServer ident. Must be formated as PROVIDER/SERVER");
  838. puts("\t-d pidfile\tDaemonize and write daemon pid into pidfile");
  839. puts("\t-t ttl\t\tSet multicast ttl (default: 1)");
  840. puts("\t-o ip\t\tOutput interface address (default: 0.0.0.0)");
  841. puts("\t-l host\t\tSyslog host (default: disabled)");
  842. puts("\t-L port\t\tSyslog port (default: 514)");
  843. puts("\t-R\t\tSend reset packets when changing sources.");
  844. puts("");
  845. puts(" Web server options:");
  846. puts("\t-b addr\t\tLocal IP address to bind. (default: 0.0.0.0)");
  847. puts("\t-p port\t\tPort to listen. (default: disabled)");
  848. puts("");
  849. }
  850. void set_ident(char *new_ident, struct config *cfg) {
  851. cfg->ident = new_ident;
  852. cfg->logident = strdup(new_ident);
  853. char *c = cfg->logident;
  854. while (*c) {
  855. if (*c=='/')
  856. *c='-';
  857. c++;
  858. }
  859. }
  860. void parse_options(int argc, char **argv, struct config *cfg) {
  861. int j, ttl;
  862. cfg->server_socket = -1;
  863. cfg->logport = 514;
  864. pthread_mutex_init(&cfg->channels_lock, NULL);
  865. while ((j = getopt(argc, argv, "i:b:p:c:d:t:o:l:L:RHh")) != -1) {
  866. switch (j) {
  867. case 'b':
  868. cfg->server_addr = optarg;
  869. break;
  870. case 'p':
  871. cfg->server_port = atoi(optarg);
  872. break;
  873. case 'i':
  874. set_ident(optarg, cfg);
  875. break;
  876. case 'c':
  877. cfg->channels_file = optarg;
  878. break;
  879. case 'd':
  880. cfg->pidfile = optarg;
  881. break;
  882. case 'o':
  883. if (inet_aton(optarg, &output_intf) == 0) {
  884. fprintf(stderr, "Invalid interface address: %s\n", optarg);
  885. exit(1);
  886. }
  887. break;
  888. case 't':
  889. ttl = atoi(optarg);
  890. multicast_ttl = (ttl && ttl < 127) ? ttl : 1;
  891. break;
  892. case 'l':
  893. cfg->loghost = optarg;
  894. cfg->syslog_active = 1;
  895. break;
  896. case 'L':
  897. cfg->logport = atoi(optarg);
  898. break;
  899. case 'R':
  900. send_reset_opt = 1;
  901. break;
  902. case 'H':
  903. case 'h':
  904. show_usage(0);
  905. exit(0);
  906. break;
  907. }
  908. }
  909. if (!cfg->channels_file) {
  910. show_usage(0);
  911. fprintf(stderr, "ERROR: No channels file is set (use -c option).\n");
  912. exit(1);
  913. }
  914. if (!cfg->ident) {
  915. set_ident("unixsol/tomcast", cfg);
  916. }
  917. printf("Configuration:\n");
  918. printf("\tServer ident : %s\n", cfg->ident);
  919. printf("\tChannels file : %s\n", cfg->channels_file);
  920. printf("\tOutput iface addr : %s\n", inet_ntoa(output_intf));
  921. printf("\tMulticast ttl : %d\n", multicast_ttl);
  922. if (cfg->syslog_active) {
  923. printf("\tSyslog host : %s\n", cfg->loghost);
  924. printf("\tSyslog port : %d\n", cfg->logport);
  925. } else {
  926. printf("\tSyslog disabled.\n");
  927. }
  928. if (send_reset_opt)
  929. printf("\tSend reset packets.\n");
  930. if (cfg->pidfile) {
  931. printf("\tDaemonize : %s\n", cfg->pidfile);
  932. } else {
  933. printf("\tDo not daemonize.\n");
  934. }
  935. if (cfg->server_port) {
  936. init_server_socket(cfg->server_addr, cfg->server_port, &cfg->server, &cfg->server_socket);
  937. printf("\tStarting web srv : http://%s:%d/status (sock: %d)\n",
  938. cfg->server_addr ? cfg->server_addr : "*", cfg->server_port, cfg->server_socket);
  939. } else {
  940. printf("\tNo web server\n");
  941. }
  942. }
  943. void init_vars(struct config *cfg) {
  944. cfg->restreamer = list_new("restreamer");
  945. regcomp(&http_response, "^HTTP/1.[0-1] (([0-9]{3}) .*)", REG_EXTENDED);
  946. memset(&TS_NULL_FRAME, 0xff, FRAME_PACKET_SIZE);
  947. int i;
  948. for (i=0; i<FRAME_PACKET_SIZE; i=i+188) {
  949. TS_NULL_FRAME[i+0] = 0x47;
  950. TS_NULL_FRAME[i+1] = 0x1f;
  951. TS_NULL_FRAME[i+2] = 0xff;
  952. TS_NULL_FRAME[i+3] = 0x00;
  953. }
  954. }
  955. void spawn_proxy_threads(struct config *cfg) {
  956. LNODE *lc, *lctmp;
  957. LNODE *lr, *lrtmp;
  958. int spawned = 0;
  959. list_for_each(cfg->chanconf, lc, lctmp) {
  960. CHANNEL *c = lc->data;
  961. int restreamer_active = 0;
  962. list_lock(cfg->restreamer);
  963. list_for_each(cfg->restreamer, lr, lrtmp) {
  964. RESTREAMER *r = lr->data;
  965. if (strcmp(r->name, c->name)==0) {
  966. restreamer_active = 1;
  967. break;
  968. }
  969. }
  970. list_unlock(cfg->restreamer);
  971. if (!restreamer_active) {
  972. RESTREAMER *nr = new_restreamer(c->name, c);
  973. if (nr->clientsock < 0) {
  974. LOGf("Error creating proxy socket for %s\n", c->name);
  975. free_restreamer(nr);
  976. } else {
  977. list_add(cfg->restreamer, nr);
  978. if (pthread_create(&nr->thread, NULL, &proxy_ts_stream, nr) == 0) {
  979. spawned++;
  980. pthread_detach(nr->thread);
  981. } else {
  982. LOGf("Error creating proxy for %s\n", c->name);
  983. }
  984. }
  985. }
  986. }
  987. LOGf("INFO : %d proxy threads spawned\n", spawned);
  988. }
  989. void kill_proxy_threads(struct config *cfg) {
  990. LNODE *l, *tmp;
  991. int killed = 0;
  992. list_lock(cfg->restreamer);
  993. list_for_each(cfg->restreamer, l, tmp) {
  994. RESTREAMER *r = l->data;
  995. r->dienow = 1;
  996. killed++;
  997. }
  998. list_unlock(cfg->restreamer);
  999. LOGf("INFO : %d proxy threads killed\n", killed);
  1000. }
  1001. int keep_going = 1;
  1002. void signal_quit(int sig) {
  1003. keep_going = 0;
  1004. kill_proxy_threads(&config);
  1005. usleep(500000);
  1006. LOGf("KILL : Signal %i | %s %s (%s)\n", sig, server_sig, server_ver, config.ident);
  1007. usleep(100000);
  1008. log_close();
  1009. if (config.pidfile && strlen(config.pidfile))
  1010. unlink(config.pidfile);
  1011. signal(sig, SIG_DFL);
  1012. raise(sig);
  1013. }
  1014. struct config *get_config(void) {
  1015. return &config;
  1016. }
  1017. void do_reconnect(int sig) {
  1018. (void)sig;
  1019. LNODE *l, *tmp;
  1020. list_lock(config.restreamer);
  1021. list_for_each(config.restreamer, l, tmp) {
  1022. RESTREAMER *r = l->data;
  1023. r->reconnect = 1;
  1024. }
  1025. list_unlock(config.restreamer);
  1026. }
  1027. void do_reconf(int sig) {
  1028. (void)sig;
  1029. load_channels_config(&config);
  1030. spawn_proxy_threads(&config);
  1031. }
  1032. void init_signals(void) {
  1033. signal(SIGCHLD, SIG_IGN);
  1034. signal(SIGPIPE, SIG_IGN);
  1035. signal(SIGHUP , do_reconf);
  1036. signal(SIGUSR1, do_reconnect);
  1037. signal(SIGINT , signal_quit);
  1038. signal(SIGTERM, signal_quit);
  1039. }
  1040. void do_daemonize(struct config *cfg) {
  1041. if (!cfg->pidfile)
  1042. return;
  1043. fprintf(stderr, "Daemonizing.\n");
  1044. pid_t pid = fork();
  1045. if (pid > 0) {
  1046. FILE *F = fopen(cfg->pidfile,"w");
  1047. if (F) {
  1048. fprintf(F,"%i\n",pid);
  1049. fclose(F);
  1050. }
  1051. exit(0);
  1052. }
  1053. // Child process continues...
  1054. setsid(); // request a new session (job control)
  1055. freopen("/dev/null", "r", stdin);
  1056. freopen("/dev/null", "w", stdout);
  1057. freopen("/dev/null", "w", stderr);
  1058. }
  1059. /* Must be called after daemonize! */
  1060. void init_logger(struct config *cfg) {
  1061. if (cfg->syslog_active)
  1062. fprintf(stderr, "Logging to %s:%d\n", cfg->loghost, cfg->logport);
  1063. log_init(cfg->logident, cfg->syslog_active, cfg->pidfile == NULL, cfg->loghost, cfg->logport);
  1064. }
  1065. int main(int argc, char **argv) {
  1066. set_http_response_server_ident(server_sig, server_ver);
  1067. show_usage(1); // Show copyright and version
  1068. init_vars(&config);
  1069. parse_options(argc, argv, &config);
  1070. do_daemonize(&config);
  1071. init_logger(&config);
  1072. init_signals();
  1073. LOGf("INIT : %s %s (%s)\n" , server_sig, server_ver, config.ident);
  1074. load_channels_config(&config);
  1075. spawn_proxy_threads(&config);
  1076. web_server_start(&config);
  1077. do {
  1078. sleep(60);
  1079. } while(1);
  1080. signal_quit(15);
  1081. exit(0);
  1082. }