No Description
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.

proxy_common.c 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. /* tsiproxy stream proxy */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <stdarg.h>
  5. #include <unistd.h>
  6. #include <string.h>
  7. #include <signal.h>
  8. #include <netdb.h>
  9. #include <pthread.h>
  10. #include <regex.h>
  11. #include <arpa/inet.h>
  12. #include <netinet/in.h>
  13. #include <sys/utsname.h>
  14. #include <sys/socket.h>
  15. #include <sys/time.h>
  16. #include <sys/types.h>
  17. #include <sys/stat.h>
  18. #include <sys/utsname.h>
  19. #include <sys/resource.h>
  20. #include <fcntl.h>
  21. #include <errno.h>
  22. #include <poll.h>
  23. #include "libfuncs/libfuncs.h"
  24. #include "data.h"
  25. #include "conf.h"
  26. #include "proxy_common.h"
  27. extern char *server_sig;
  28. extern char *server_ver;
  29. extern regex_t http_response;
  30. extern LIST *restreamer, *chanconf;
  31. extern STATS allstats;
  32. extern CONFIG *config;
  33. extern int keep_running;
  34. extern void * proxy_ts_stream(void *channel_id);
  35. void process_client(int clientsock, CLIENT *client) {
  36. list_lock(chanconf);
  37. LNODE *l, *tmp;
  38. CHANNEL *chan = NULL;
  39. list_for_each(chanconf, l, tmp) {
  40. if (strcmp(client->chan, ((CHANNEL *)l->data)->name)==0) {
  41. chan = l->data;
  42. break;
  43. }
  44. }
  45. /* Check if requested channel exists? */
  46. if (!chan) {
  47. LOGf("ERROR: No such channel | IP: %s Path: /%s Agent: %s\n", client->IP, client->chan, client->agent);
  48. send_404_not_found(client->fno);
  49. stop_client_shutdown(client);
  50. list_unlock(chanconf);
  51. return;
  52. }
  53. /* Is there an active restreamer for the requested channel */
  54. list_lock(restreamer);
  55. RESTREAMER *r = NULL;
  56. list_for_each(restreamer, l, tmp) {
  57. if (strcmp(client->chan, ((RESTREAMER *)l->data)->name)==0) {
  58. r = l->data;
  59. break;
  60. }
  61. }
  62. if (r) {
  63. /* Active restreamer found. Add client to it's queue. Do it here while restreamer is locked otherwise there is a race! */
  64. queue_add(r->queue, client);
  65. list_unlock(restreamer);
  66. list_unlock(chanconf);
  67. return;
  68. }
  69. list_unlock(restreamer);
  70. /* No active restreamer found, start new one */
  71. RESTREAMER *nr = new_restreamer(client->chan, chan);
  72. queue_add(nr->queue, client);
  73. list_add(restreamer, nr);
  74. list_unlock(chanconf);
  75. pthread_t newthread;
  76. LOGf("SPAWN: Restreamer | Channel: %s Source: %s client_fd: %i\n", chan->name, chan->source, clientsock);
  77. if (pthread_create(&newthread, NULL, &proxy_ts_stream, nr)) {
  78. log_perror("Error TS proxy creating thread.", errno);
  79. exit(1);
  80. }
  81. pthread_detach(newthread);
  82. }
  83. static void remove_clients(RESTREAMER *r, const char *text, int error_code) {
  84. CLIENT *c;
  85. while ((c=queue_get_nowait(r->queue))) {
  86. LOGf("NOSIG: fd: %i srv_fd: %i {Op:%s} {Err:%d} | Client: %lu IP: %s Channel: %s Agent: %s\n",
  87. c->fno, r->sock, text, error_code,
  88. c->clientid, c->IP, c->chan, c->agent);
  89. // Headers are already sent or the client is using udp, just yank it
  90. if (c->headers_sent || c->client_port) {
  91. stop_client_shutdown(c);
  92. } else {
  93. char *code = "504 Gateway Timeout";
  94. char *msg = "no-signal";
  95. if (error_code >= 300) {
  96. send_http_response(c->fno, code);
  97. send_header_textplain(c->fno);
  98. fdputsf(c->fno, "X-ErrorCode: %d\nX-Error: %s\n\n%s\n", error_code, msg, msg);
  99. } else {
  100. send_http_error(c->fno, code, msg);
  101. }
  102. stop_client_shutdown(c);
  103. }
  104. }
  105. }
  106. static void remove_smart_clients(RESTREAMER *r) {
  107. CLIENT *c;
  108. LNODE *l, *tmp;
  109. list_for_each(r->clients, l, tmp) {
  110. c = l->data;
  111. if (!c->smart_client)
  112. continue;
  113. list_del(r->clients, &l);
  114. if (c->headers_sent || c->client_port) {
  115. stop_client_shutdown(c);
  116. } else {
  117. send_http_error(c->fno, "504 Gateway Timeout", "no-signal");
  118. stop_client_shutdown(c);
  119. }
  120. }
  121. }
  122. void proxy_close(RESTREAMER *r, int error_code) {
  123. LOGf("CLOSE: Restreamer | Channel: %s Source: %s IP: %s srv_fd: %i Conn: %ld Serv: %ld TrafIn: %lld TrafOut: %lld\n",
  124. r->channel->name,
  125. r->channel->source,
  126. inet_ntoa(r->sockname.sin_addr),
  127. r->sock,
  128. r->connects,
  129. r->served,
  130. r->traffic_in,
  131. r->traffic_out);
  132. // If there are no clients left, no "Timeout" messages will be logged
  133. remove_clients(r, "Timeout", error_code);
  134. list_del_entry(restreamer, r);
  135. free_restreamer(r);
  136. }
  137. void proxy_begin_reconnect(RESTREAMER *r) {
  138. shutdown_fd(&(r->sock));
  139. next_channel_source(r->channel);
  140. remove_smart_clients(r);
  141. }
  142. #define FATAL_ERROR(__no_signal_msg) do \
  143. { \
  144. remove_clients(r, __no_signal_msg, *http_code); \
  145. free_chansrc(src); \
  146. return -1; \
  147. } while (0)
  148. /*
  149. On the last try, send no-signal to clients and exit
  150. otherwise wait a little bit before trying again
  151. */
  152. #define DO_RECONNECT do \
  153. { \
  154. if (retries == 0) { \
  155. FATAL_ERROR("Connect"); \
  156. } else { \
  157. free_chansrc(src); \
  158. if (errno != EHOSTUNREACH) /* When host is unreachable there is already a delay of ~4 secs per try so no sleep is needed */ \
  159. usleep(PROXY_RETRY_TIMEOUT * 1000); \
  160. return 1; \
  161. } \
  162. } while(0)
  163. /*
  164. Returns:
  165. -1 = exit thread
  166. 1 = retry
  167. 0 = connected ok
  168. */
  169. int connect_source(RESTREAMER *r, int retries, int readbuflen, int *http_code) {
  170. CHANSRC *src = init_chansrc(r->channel->source);
  171. if (!src) {
  172. LOGf("ERROR: Can't parse channel source | Channel: %s Source: %s\n", r->channel->name, r->channel->source);
  173. FATAL_ERROR("cant-parse-channel-source");
  174. }
  175. r->connected = 0;
  176. r->reconnect = 0;
  177. int active = 1;
  178. int dret = async_resolve_host(src->host, src->port, &(r->sockname), DNS_RESOLVER_TIMEOUT, &active);
  179. if (dret != 0) {
  180. if (dret == 1)
  181. LOGf("ERROR: Can't resolve host | Channel: %s Source: %s Host: %s\n", r->channel->name, r->channel->source, src->host);
  182. if (dret == 2)
  183. LOGf("ERROR: DNS timeout | Channel: %s Source: %s Host: %s\n", r->channel->name, r->channel->source, src->host);
  184. DO_RECONNECT;
  185. }
  186. char buf[1024];
  187. *http_code = 0;
  188. if (src->sproto == tcp_sock) {
  189. r->sock = socket(PF_INET, SOCK_STREAM, 0);
  190. if (r->sock < 0) {
  191. log_perror("connect_source(): Could not create SOCK_STREAM socket.", errno);
  192. FATAL_ERROR("cant-create-sock-stream-socket");
  193. }
  194. LOGf("RCONN: Connecting | Channel: %s Source: %s IP: %s src_fd: %i TriesLeft: %i\n",
  195. r->channel->name,
  196. r->channel->source,
  197. inet_ntoa(r->sockname.sin_addr),
  198. r->sock,
  199. retries
  200. );
  201. if (do_connect(r->sock, (struct sockaddr *)&(r->sockname), sizeof(r->sockname), PROXY_CONNECT_TIMEOUT) < 0) {
  202. LOGf("ERROR: Error connecting to %s srv_fd: %i err: %s\n", r->channel->source, r->sock, strerror(errno));
  203. DO_RECONNECT;
  204. }
  205. snprintf(buf,sizeof(buf)-1, "GET /%s HTTP/1.0\nHost: %s:%u\nUser-Agent: %s %s (%s)\n\n",
  206. src->path, src->host, src->port, server_sig, server_ver, config->ident);
  207. buf[sizeof(buf)-1] = 0;
  208. allstats.traffic_out += safe_write(r->sock, buf, strlen(buf));
  209. char xresponse[128];
  210. memset(xresponse, 0, sizeof(xresponse));
  211. memset(buf, 0, sizeof(buf));
  212. regmatch_t res[4];
  213. while (fdgetline(r->sock,buf,sizeof(buf)-1)) {
  214. if (buf[0] == '\n' || buf[0] == '\r')
  215. break;
  216. if (strstr(buf,"HTTP/1.") != NULL) {
  217. if (regexec(&http_response,buf,3,res,0) != REG_NOMATCH) {
  218. char codestr[4];
  219. if ((unsigned int)res[1].rm_eo-res[1].rm_so < (unsigned)sizeof(xresponse)) {
  220. strncpy(xresponse, &buf[res[1].rm_so], res[1].rm_eo-res[1].rm_so);
  221. xresponse[res[1].rm_eo-res[1].rm_so] = '\0';
  222. chomp(xresponse);
  223. strncpy(codestr, &buf[res[2].rm_so], res[2].rm_eo-res[2].rm_so);
  224. codestr[3] = 0;
  225. *http_code = atoi(codestr);
  226. }
  227. }
  228. }
  229. if (*http_code == 504) { // Extract extra error code
  230. if (strstr(buf, "X-ErrorCode: ") != NULL) {
  231. *http_code = atoi(buf+13);
  232. break;
  233. }
  234. }
  235. }
  236. if (*http_code == 0) { // No valid HTTP response, retry
  237. LOGf("DEBUG: Server returned not valid HTTP code | srv_fd: %i\n", r->sock);
  238. DO_RECONNECT;
  239. }
  240. if (*http_code == 504) { // No signal, exit
  241. LOGf("ERROR: Get no-signal for %s from %s on srv_fd: %i\n", r->channel->name, r->channel->source, r->sock);
  242. FATAL_ERROR("no-signal");
  243. }
  244. if (*http_code > 300) { // Unhandled or error codes, exit
  245. LOGf("ERROR: Get code %i for %s from %s on srv_fd: %i exiting.\n", *http_code, r->channel->name, r->channel->source, r->sock);
  246. FATAL_ERROR("unhandled-http-code");
  247. }
  248. // connected ok, continue
  249. } else {
  250. if (!IN_MULTICAST(ntohl(r->sockname.sin_addr.s_addr))) {
  251. LOGf("ERROR: %s is not multicast address\n", r->channel->source);
  252. FATAL_ERROR("source-is-not-multicast-address");
  253. }
  254. struct ip_mreq mreq;
  255. struct sockaddr_in receiving_from;
  256. r->sock = socket(PF_INET, SOCK_DGRAM, 0);
  257. if (r->sock < 0) {
  258. log_perror("play(): Could not create SOCK_DGRAM socket.", errno);
  259. FATAL_ERROR("cant-create-sock-dgram-socket");
  260. }
  261. LOGf("RCONN: Listening on multicast socket %s srv_fd: %i retries left: %i\n", r->channel->source, r->sock, retries);
  262. int on = 1;
  263. setsockopt(r->sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
  264. // subscribe to multicast group
  265. memcpy(&mreq.imr_multiaddr, &(r->sockname.sin_addr), sizeof(struct in_addr));
  266. mreq.imr_interface.s_addr = htonl(INADDR_ANY);
  267. if (setsockopt(r->sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) {
  268. LOGf("ERROR: Failed to add IP membership on %s srv_fd: %i\n", r->channel->source, r->sock);
  269. FATAL_ERROR("failed-to-add-membership");
  270. }
  271. // bind to the socket so data can be read
  272. memset(&receiving_from, 0, sizeof(receiving_from));
  273. receiving_from.sin_family = AF_INET;
  274. receiving_from.sin_addr = r->sockname.sin_addr;
  275. receiving_from.sin_port = htons(src->port);
  276. if (bind(r->sock, (struct sockaddr *) &receiving_from, sizeof(receiving_from)) < 0) {
  277. LOGf("ERROR: Failed to bind to %s srv_fd: %i\n", r->channel->source, r->sock);
  278. FATAL_ERROR("failed-to-bind");
  279. }
  280. }
  281. if (setsockopt(r->sock, SOL_SOCKET, SO_RCVBUF, (const char *)&readbuflen, sizeof(readbuflen)) < 0)
  282. log_perror("play(): setsockopt(SO_RCVBUF)", errno);
  283. r->connects++;
  284. r->connected = 1;
  285. free_chansrc(src);
  286. return 0;
  287. }
  288. int connect_udp_client(CLIENT *c) {
  289. int newsock = -1;
  290. int client_socket = c->fno;
  291. struct sockaddr_in sockname;
  292. struct in_addr client_ip;
  293. inet_aton(c->IP, &client_ip);
  294. sockname.sin_family = AF_INET;
  295. sockname.sin_port = htons(c->client_port);
  296. sockname.sin_addr = client_ip;
  297. // Create new udp socket to the client
  298. newsock = socket(PF_INET, SOCK_DGRAM, 0);
  299. if (newsock < 0) {
  300. log_perror("process_new_clients(): Could not create SOCK_DGRAM socket.", errno);
  301. stop_client_noshutdown(c); // ??
  302. return -1;
  303. }
  304. // Connect to the client
  305. // Connect on udp socket never returns an error
  306. // The error will be returned on the first send/write
  307. do_connect(newsock, (struct sockaddr *)&sockname, sizeof(sockname), 1000);
  308. // Return pls playlist (vlc supports it)
  309. send_200_ok(c->fno);
  310. if (c->agent && strstr(c->agent,"VLC")==c->agent) { // VLC support pls playlists
  311. fdputsf(c->fno, "Content-type: application/pls+xml\n\n[playlist]\nFile1=%s://@:%u\nTitle1=LiveTV\n", "udp", c->client_port);
  312. // sleep a little bit so VLC can start listening to the udp port
  313. shutdown_fd(&client_socket);
  314. usleep(500000);
  315. } else {
  316. fdputsf(c->fno, "Content-type: text/plain\n\n%s://@:%u\n", "udp", c->client_port);
  317. shutdown_fd(&client_socket);
  318. }
  319. // Change client socket to the new udp socket
  320. c->fno = newsock;
  321. return newsock;
  322. }
  323. void process_new_clients(RESTREAMER *r, int bufsz, uint32_t start_pts, unsigned int pos) {
  324. CLIENT *c;
  325. while ((c=queue_get_nowait(r->queue))) {
  326. if (c->clientid) {
  327. int client_exists = 0;
  328. {
  329. LNODE *l, *tmp;
  330. CLIENT *n = NULL;
  331. list_lock(r->clients);
  332. list_for_each_reverse(r->clients, l, tmp) {
  333. if (c->clientid == ((CLIENT *)l->data)->clientid) {
  334. n = l->data;
  335. break;
  336. }
  337. }
  338. // if the same client is already watching the channel but from different IP
  339. // or the same client is already watching the channel on the same port
  340. if (n && (strcmp(n->IP,c->IP)!=0 || (n->client_port && n->client_port==c->client_port)))
  341. client_exists = 1;
  342. list_unlock(r->clients);
  343. }
  344. if (client_exists) {
  345. LOGf("2ND : fd: %i | Client: %lu IP: %s Channel: %s Agent: %s\n",
  346. c->fno, c->clientid, c->IP, c->chan, c->agent);
  347. send_400_bad_request(c->fno, "already-watching-the-channel");
  348. stop_client_shutdown(c);
  349. continue;
  350. }
  351. }
  352. // Connect with udp to the client, closing incomming http req socket
  353. if (c->client_port && connect_udp_client(c) == -1) {
  354. continue;
  355. }
  356. if (setsockopt(c->fno, SOL_SOCKET, SO_SNDBUF, (const char *) &bufsz,sizeof(bufsz))<0)
  357. log_perror("play(): setsockopt(SO_SNDBUF)", errno);
  358. c->pos = pos;
  359. c->start_pts = start_pts;
  360. list_add(r->clients, c);
  361. }
  362. }
  363. int shout(RESTREAMER *r, char *buf, const size_t bufsz, const size_t framelen, unsigned int pos, const char *content_type, char *header, unsigned int header_len) {
  364. CLIENT *n;
  365. int num_clients=0, nfds=0;
  366. struct timeval tv;
  367. fd_set wfds,efds,rfds;
  368. time_t now = time(NULL);
  369. if (r->clients==NULL || r->clients->items == 0)
  370. return 0;
  371. FD_ZERO(&wfds);
  372. FD_ZERO(&rfds);
  373. FD_ZERO(&efds);
  374. LNODE *l, *tmp;
  375. list_for_each_reverse(r->clients, l, tmp) {
  376. n = l->data;
  377. /* EXPR: No traffic in XX seconds. Kill the client. X seconds have passed and 0 traffic send - kill */
  378. if ((now-n->ts >= NO_TRAFFIC_SECONDS) ||
  379. (n->traffic_out == 0 && now-n->start >= NO_TRAFFIC_SECONDS))
  380. {
  381. n->start += NO_TRAFFIC_SECONDS;
  382. stop_client_shutdown_mark(n, 'x');
  383. list_del(r->clients, &l);
  384. continue;
  385. }
  386. FD_SET(n->fno,&wfds);
  387. FD_SET(n->fno,&efds);
  388. FD_SET(n->fno,&rfds);
  389. if (n->fno>nfds) nfds=n->fno;
  390. num_clients++;
  391. if (!n->logged) {
  392. client_log_connect(n);
  393. r->served++;
  394. }
  395. }
  396. tv.tv_sec = 0;
  397. tv.tv_usec= 0;
  398. if (select(nfds+1,&rfds,&wfds,&efds,&tv)>0) {
  399. list_for_each_reverse(r->clients, l, tmp) {
  400. n = l->data;
  401. if ((FD_ISSET(n->fno,&rfds)) || (FD_ISSET(n->fno,&efds)) || // closed connection
  402. ((n->expire > 0) && (now > n->expire)) || // expired session
  403. n->dienow) // Forcefully stopped client
  404. {
  405. stop_client_shutdown(n);
  406. list_del(r->clients, &l);
  407. num_clients--;
  408. continue;
  409. }
  410. // OK, send him the stream if is ready
  411. if ((buf!=NULL)&&(FD_ISSET(n->fno,&wfds))){
  412. // Sent headers to the client (http client)
  413. if (!n->client_port && !n->headers_sent) {
  414. n->headers_sent = 1;
  415. send_200_ok(n->fno); // Standart http client response
  416. fdputsf(n->fno, "%s", content_type);
  417. if (header != NULL && header_len > 0) {
  418. allstats.traffic_out += safe_write(n->fno, header, header_len);
  419. }
  420. }
  421. int i,j;
  422. // When in mpeg mode the first packet is always 1316 also the client is at current buffer position
  423. if (!n->data_send && framelen == FRAME_PACKET_SIZE) {
  424. i = framelen;
  425. n->data_send = 1;
  426. if (config->disable_burst) {
  427. if (pos >= FRAME_PACKET_SIZE)
  428. n->pos = pos - FRAME_PACKET_SIZE;
  429. else
  430. n->pos = pos;
  431. }
  432. }
  433. if (pos > n->pos) {
  434. i = pos - n->pos;
  435. } else {
  436. i = bufsz * framelen - n->pos;
  437. }
  438. // Sent it
  439. j = safe_write(n->fno, buf+n->pos, i);
  440. if (j >= 0) {
  441. /* 0 bytes written is not an error per se, but here we threat
  442. it special, because there are buggy clients that connect and
  443. start reading 0 bytes. If we do not set n->ts these clients
  444. will be disconnected when NO_TRAFFIC_SECONDS pass */
  445. if (j > 0) {
  446. allstats.traffic_out += j;
  447. r->traffic_out += j;
  448. n->traffic_out += j;
  449. n->pos += j;
  450. n->ts = time(NULL);
  451. }
  452. if (n->pos == bufsz * framelen)
  453. n->pos = 0;
  454. // Send netmsg
  455. if (framelen == FRAME_PACKET_SIZE && n->netmsg[0]) {
  456. char *netmsg = get_netmsg_packet(n->netmsg);
  457. if (netmsg) {
  458. safe_write(n->fno, netmsg, FRAME_PACKET_SIZE);
  459. n->netmsg[0] = 0;
  460. FREE(netmsg);
  461. }
  462. }
  463. } else {
  464. stop_client_shutdown(n);
  465. list_del(r->clients, &l);
  466. num_clients--;
  467. }
  468. }
  469. }
  470. }
  471. return num_clients;
  472. }
  473. int check_restreamer_state(RESTREAMER *r) {
  474. if (!keep_running)
  475. return 2;
  476. if (r->dienow) {
  477. LOGf("RESTR: Forced disconnect on srv_fd: %i | Channel: %s Source: %s\n", r->sock, r->channel->name, r->channel->source);
  478. return 2;
  479. }
  480. if (r->reconnect) {
  481. LOGf("RESTR: Forced reconnect on srv_fd: %i | Channel: %s Source: %s\n", r->sock, r->channel->name, r->channel->source);
  482. return 1;
  483. }
  484. return 0;
  485. }