stream.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. /*
  2. * Squeezelite - lightweight headless squeezebox emulator
  3. *
  4. * (c) Adrian Smith 2012-2015, triode1@btinternet.com
  5. * Ralph Irving 2015-2017, ralph_irving@hotmail.com
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. *
  20. */
  21. // stream thread
  22. #ifndef _GNU_SOURCE
  23. #define _GNU_SOURCE
  24. #endif
  25. #include "squeezelite.h"
  26. #include <fcntl.h>
  27. #if USE_SSL
  28. #include "openssl/ssl.h"
  29. #include "openssl/err.h"
  30. #endif
  31. #if SUN
  32. #include <signal.h>
  33. #endif
  34. static log_level loglevel;
  35. static struct buffer buf;
  36. struct buffer *streambuf = &buf;
  37. #define LOCK mutex_lock(streambuf->mutex)
  38. #define UNLOCK mutex_unlock(streambuf->mutex)
  39. /*
  40. When LMS sends a close/open sequence very quickly, the stream thread might
  41. still be waiting in the poll() on the closed socket. It is never recommended
  42. to have a thread closing a socket used by another thread but it works, as
  43. opposed to an infinite select().
  44. In stream_sock() a new socket is created and full OS will allocate a different
  45. one but on RTOS and simple IP stack, the same might be re-used and that causes
  46. an exception as a thread is already waiting on a newly allocated socket
  47. A simple variable that forces stream_sock() to wait until we are out of poll()
  48. is enough and much faster than a mutex
  49. */
  50. static bool polling;
  51. static sockfd fd;
  52. struct streamstate stream;
  53. #if USE_SSL
  54. static SSL_CTX *SSLctx;
  55. SSL *ssl;
  56. #endif
  57. #if !USE_SSL
  58. #define _recv(ssl, fc, buf, n, opt) recv(fd, buf, n, opt)
  59. #define _send(ssl, fd, buf, n, opt) send(fd, buf, n, opt)
  60. #define _poll(ssl, pollinfo, timeout) poll(pollinfo, 1, timeout)
  61. #define _last_error() last_error()
  62. #else
  63. #define _last_error() ERROR_WOULDBLOCK
  64. static int _recv(SSL *ssl, int fd, void *buffer, size_t bytes, int options) {
  65. int n;
  66. if (!ssl) return recv(fd, buffer, bytes, options);
  67. n = SSL_read(ssl, (u8_t*) buffer, bytes);
  68. if (n <= 0 && SSL_get_error(ssl, n) == SSL_ERROR_ZERO_RETURN) return 0;
  69. return n;
  70. }
  71. static int _send(SSL *ssl, int fd, void *buffer, size_t bytes, int options) {
  72. int n;
  73. if (!ssl) return send(fd, buffer, bytes, options);
  74. while (1) {
  75. int err;
  76. ERR_clear_error();
  77. if ((n = SSL_write(ssl, (u8_t*) buffer, bytes)) >= 0) return n;
  78. err = SSL_get_error(ssl, n);
  79. if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) continue;
  80. LOG_INFO("SSL write error %d", err );
  81. return n;
  82. }
  83. }
  84. /*
  85. can't mimic exactly poll as SSL is a real pain. Even if SSL_pending returns
  86. 0, there might be bytes to read but when select (poll) return > 0, there might
  87. be no frame available. As well select (poll) < 0 does not mean that there is
  88. no data pending
  89. */
  90. static int _poll(SSL *ssl, struct pollfd *pollinfo, int timeout) {
  91. if (!ssl) return poll(pollinfo, 1, timeout);
  92. if (pollinfo->events & POLLIN && SSL_pending(ssl)) {
  93. if (pollinfo->events & POLLOUT) poll(pollinfo, 1, 0);
  94. pollinfo->revents = POLLIN;
  95. return 1;
  96. }
  97. return poll(pollinfo, 1, timeout);
  98. }
  99. #endif
  100. static bool send_header(void) {
  101. char *ptr = stream.header;
  102. int len = stream.header_len;
  103. unsigned try = 0;
  104. ssize_t n;
  105. while (len) {
  106. n = _send(ssl, fd, ptr, len, MSG_NOSIGNAL);
  107. if (n <= 0) {
  108. if (n < 0 && _last_error() == ERROR_WOULDBLOCK && try < 10) {
  109. LOG_SDEBUG("retrying (%d) writing to socket", ++try);
  110. usleep(1000);
  111. continue;
  112. }
  113. LOG_INFO("failed writing to socket: %s", strerror(last_error()));
  114. stream.disconnect = LOCAL_DISCONNECT;
  115. stream.state = DISCONNECT;
  116. wake_controller();
  117. return false;
  118. }
  119. LOG_SDEBUG("wrote %d bytes to socket", n);
  120. ptr += n;
  121. len -= n;
  122. }
  123. LOG_SDEBUG("wrote header");
  124. return true;
  125. }
  126. static bool running = true;
  127. static void _disconnect(stream_state state, disconnect_code disconnect) {
  128. stream.state = state;
  129. stream.disconnect = disconnect;
  130. #if USE_SSL
  131. if (ssl) {
  132. SSL_shutdown(ssl);
  133. SSL_free(ssl);
  134. ssl = NULL;
  135. }
  136. #endif
  137. closesocket(fd);
  138. fd = -1;
  139. wake_controller();
  140. }
  141. static void *stream_thread() {
  142. while (running) {
  143. struct pollfd pollinfo;
  144. size_t space;
  145. LOCK;
  146. space = min(_buf_space(streambuf), _buf_cont_write(streambuf));
  147. if (fd < 0 || !space || stream.state <= STREAMING_WAIT) {
  148. UNLOCK;
  149. usleep(space ? 100000 : 25000);
  150. continue;
  151. }
  152. if (stream.state == STREAMING_FILE) {
  153. int n = read(fd, streambuf->writep, space);
  154. if (n == 0) {
  155. LOG_INFO("end of stream");
  156. _disconnect(DISCONNECT, DISCONNECT_OK);
  157. }
  158. if (n > 0) {
  159. _buf_inc_writep(streambuf, n);
  160. stream.bytes += n;
  161. LOG_SDEBUG("streambuf read %d bytes", n);
  162. }
  163. if (n < 0) {
  164. LOG_WARN("error reading: %s", strerror(last_error()));
  165. _disconnect(DISCONNECT, REMOTE_DISCONNECT);
  166. }
  167. UNLOCK;
  168. continue;
  169. } else {
  170. polling = true;
  171. pollinfo.fd = fd;
  172. pollinfo.events = POLLIN;
  173. if (stream.state == SEND_HEADERS) {
  174. pollinfo.events |= POLLOUT;
  175. }
  176. }
  177. UNLOCK;
  178. if (_poll(ssl, &pollinfo, 100)) {
  179. polling = false;
  180. LOCK;
  181. // check socket has not been closed while in poll
  182. if (fd < 0) {
  183. UNLOCK;
  184. continue;
  185. }
  186. if ((pollinfo.revents & POLLOUT) && stream.state == SEND_HEADERS) {
  187. if (send_header()) stream.state = RECV_HEADERS;
  188. stream.header_len = 0;
  189. UNLOCK;
  190. continue;
  191. }
  192. if (pollinfo.revents & (POLLIN | POLLHUP)) {
  193. // get response headers
  194. if (stream.state == RECV_HEADERS) {
  195. // read one byte at a time to catch end of header
  196. char c;
  197. static int endtok;
  198. int n = _recv(ssl, fd, &c, 1, 0);
  199. if (n <= 0) {
  200. if (n < 0 && _last_error() == ERROR_WOULDBLOCK) {
  201. UNLOCK;
  202. continue;
  203. }
  204. LOG_INFO("error reading headers: %s", n ? strerror(last_error()) : "closed");
  205. _disconnect(STOPPED, LOCAL_DISCONNECT);
  206. UNLOCK;
  207. continue;
  208. }
  209. *(stream.header + stream.header_len) = c;
  210. stream.header_len++;
  211. if (stream.header_len > MAX_HEADER - 1) {
  212. LOG_ERROR("received headers too long: %u", stream.header_len);
  213. _disconnect(DISCONNECT, LOCAL_DISCONNECT);
  214. }
  215. if (stream.header_len > 1 && (c == '\r' || c == '\n')) {
  216. endtok++;
  217. if (endtok == 4) {
  218. *(stream.header + stream.header_len) = '\0';
  219. LOG_INFO("headers: len: %d\n%s", stream.header_len, stream.header);
  220. stream.state = stream.cont_wait ? STREAMING_WAIT : STREAMING_BUFFERING;
  221. wake_controller();
  222. }
  223. } else {
  224. endtok = 0;
  225. }
  226. UNLOCK;
  227. continue;
  228. }
  229. // receive icy meta data
  230. if (stream.meta_interval && stream.meta_next == 0) {
  231. if (stream.meta_left == 0) {
  232. // read meta length
  233. u8_t c;
  234. int n = _recv(ssl, fd, &c, 1, 0);
  235. if (n <= 0) {
  236. if (n < 0 && _last_error() == ERROR_WOULDBLOCK) {
  237. UNLOCK;
  238. continue;
  239. }
  240. LOG_INFO("error reading icy meta: %s", n ? strerror(last_error()) : "closed");
  241. _disconnect(STOPPED, LOCAL_DISCONNECT);
  242. UNLOCK;
  243. continue;
  244. }
  245. stream.meta_left = 16 * c;
  246. stream.header_len = 0; // amount of received meta data
  247. // MAX_HEADER must be more than meta max of 16 * 255
  248. }
  249. if (stream.meta_left) {
  250. int n = _recv(ssl, fd, stream.header + stream.header_len, stream.meta_left, 0);
  251. if (n <= 0) {
  252. if (n < 0 && _last_error() == ERROR_WOULDBLOCK) {
  253. UNLOCK;
  254. continue;
  255. }
  256. LOG_INFO("error reading icy meta: %s", n ? strerror(last_error()) : "closed");
  257. _disconnect(STOPPED, LOCAL_DISCONNECT);
  258. UNLOCK;
  259. continue;
  260. }
  261. stream.meta_left -= n;
  262. stream.header_len += n;
  263. }
  264. if (stream.meta_left == 0) {
  265. if (stream.header_len) {
  266. *(stream.header + stream.header_len) = '\0';
  267. LOG_INFO("icy meta: len: %u\n%s", stream.header_len, stream.header);
  268. stream.meta_send = true;
  269. wake_controller();
  270. }
  271. stream.meta_next = stream.meta_interval;
  272. UNLOCK;
  273. continue;
  274. }
  275. // stream body into streambuf
  276. } else {
  277. int n;
  278. space = min(_buf_space(streambuf), _buf_cont_write(streambuf));
  279. if (stream.meta_interval) {
  280. space = min(space, stream.meta_next);
  281. }
  282. n = _recv(ssl, fd, streambuf->writep, space, 0);
  283. if (n == 0) {
  284. LOG_INFO("end of stream");
  285. _disconnect(DISCONNECT, DISCONNECT_OK);
  286. }
  287. if (n < 0 && _last_error() != ERROR_WOULDBLOCK) {
  288. LOG_INFO("error reading: %s", strerror(last_error()));
  289. _disconnect(DISCONNECT, REMOTE_DISCONNECT);
  290. }
  291. if (n > 0) {
  292. _buf_inc_writep(streambuf, n);
  293. stream.bytes += n;
  294. if (stream.meta_interval) {
  295. stream.meta_next -= n;
  296. }
  297. } else {
  298. UNLOCK;
  299. continue;
  300. }
  301. if (stream.state == STREAMING_BUFFERING && stream.bytes > stream.threshold) {
  302. stream.state = STREAMING_HTTP;
  303. wake_controller();
  304. }
  305. LOG_SDEBUG("streambuf read %d bytes", n);
  306. }
  307. }
  308. UNLOCK;
  309. } else {
  310. // it is safe to set it unlocked
  311. polling = false;
  312. LOG_SDEBUG("poll timeout");
  313. }
  314. }
  315. #if USE_SSL
  316. if (SSLctx) {
  317. SSL_CTX_free(SSLctx);
  318. }
  319. #endif
  320. return 0;
  321. }
  322. static thread_type thread;
  323. void stream_init(log_level level, unsigned stream_buf_size) {
  324. loglevel = level;
  325. LOG_INFO("init stream");
  326. LOG_DEBUG("streambuf size: %u", stream_buf_size);
  327. buf_init(streambuf, stream_buf_size);
  328. if (streambuf->buf == NULL) {
  329. LOG_ERROR("unable to malloc buffer");
  330. exit(0);
  331. }
  332. #if USE_SSL
  333. #if !LINKALL && !NO_SSLSYM
  334. if (ssl_loaded) {
  335. #endif
  336. SSL_library_init();
  337. SSLctx = SSL_CTX_new(SSLv23_client_method());
  338. if (SSLctx == NULL) {
  339. LOG_ERROR("unable to allocate SSL context");
  340. exit(0);
  341. }
  342. SSL_CTX_set_options(SSLctx, SSL_OP_NO_SSLv2);
  343. #if !LINKALL && !NO_SSLSYM
  344. }
  345. #endif
  346. ssl = NULL;
  347. #endif
  348. #if SUN
  349. signal(SIGPIPE, SIG_IGN); /* Force sockets to return -1 with EPIPE on pipe signal */
  350. #endif
  351. stream.state = STOPPED;
  352. stream.header = malloc(MAX_HEADER);
  353. *stream.header = '\0';
  354. fd = -1;
  355. #if LINUX || FREEBSD
  356. touch_memory(streambuf->buf, streambuf->size);
  357. #endif
  358. #if LINUX || OSX || FREEBSD || EMBEDDED
  359. pthread_attr_t attr;
  360. pthread_attr_init(&attr);
  361. #ifdef PTHREAD_STACK_MIN
  362. pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN + STREAM_THREAD_STACK_SIZE);
  363. #endif
  364. pthread_create_name(&thread, &attr, stream_thread, NULL, "stream");
  365. pthread_attr_destroy(&attr);
  366. #endif
  367. #if WIN
  368. thread = CreateThread(NULL, STREAM_THREAD_STACK_SIZE, (LPTHREAD_START_ROUTINE)&stream_thread, NULL, 0, NULL);
  369. #endif
  370. }
  371. void stream_close(void) {
  372. LOG_INFO("close stream");
  373. LOCK;
  374. running = false;
  375. UNLOCK;
  376. #if LINUX || OSX || FREEBSD || EMBEDDED
  377. pthread_join(thread, NULL);
  378. #endif
  379. free(stream.header);
  380. buf_destroy(streambuf);
  381. }
  382. void stream_file(const char *header, size_t header_len, unsigned threshold) {
  383. buf_flush(streambuf);
  384. LOCK;
  385. stream.header_len = header_len;
  386. memcpy(stream.header, header, header_len);
  387. *(stream.header+header_len) = '\0';
  388. LOG_INFO("opening local file: %s", stream.header);
  389. #if WIN
  390. fd = open(stream.header, O_RDONLY | O_BINARY);
  391. #else
  392. fd = open(stream.header, O_RDONLY);
  393. #endif
  394. stream.state = STREAMING_FILE;
  395. if (fd < 0) {
  396. LOG_INFO("can't open file: %s", stream.header);
  397. stream.state = DISCONNECT;
  398. }
  399. wake_controller();
  400. stream.cont_wait = false;
  401. stream.meta_interval = 0;
  402. stream.meta_next = 0;
  403. stream.meta_left = 0;
  404. stream.meta_send = false;
  405. stream.sent_headers = false;
  406. stream.bytes = 0;
  407. stream.threshold = threshold;
  408. UNLOCK;
  409. }
  410. void stream_sock(u32_t ip, u16_t port, const char *header, size_t header_len, unsigned threshold, bool cont_wait) {
  411. struct sockaddr_in addr;
  412. #if EMBEDDED
  413. // wait till we are not polling anymore
  414. for (LOCK; running && polling; UNLOCK, usleep(10000), LOCK);
  415. UNLOCK;
  416. #endif
  417. int sock = socket(AF_INET, SOCK_STREAM, 0);
  418. if (sock < 0) {
  419. LOG_ERROR("failed to create socket");
  420. return;
  421. }
  422. memset(&addr, 0, sizeof(addr));
  423. addr.sin_family = AF_INET;
  424. addr.sin_addr.s_addr = ip;
  425. addr.sin_port = port;
  426. LOG_INFO("connecting to %s:%d", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
  427. set_nonblock(sock);
  428. set_nosigpipe(sock);
  429. if (connect_timeout(sock, (struct sockaddr *) &addr, sizeof(addr), 10) < 0) {
  430. LOG_INFO("unable to connect to server");
  431. LOCK;
  432. stream.state = DISCONNECT;
  433. stream.disconnect = UNREACHABLE;
  434. UNLOCK;
  435. return;
  436. }
  437. #if USE_SSL
  438. if (ntohs(port) == 443) {
  439. char *server = strcasestr(header, "Host:");
  440. ssl = SSL_new(SSLctx);
  441. SSL_set_fd(ssl, sock);
  442. // add SNI
  443. if (server) {
  444. char *p, *servername = malloc(1024);
  445. sscanf(server, "Host:%255[^:]s", servername);
  446. for (p = servername; *p == ' '; p++);
  447. SSL_set_tlsext_host_name(ssl, p);
  448. free(servername);
  449. }
  450. while (1) {
  451. int status, err = 0;
  452. ERR_clear_error();
  453. status = SSL_connect(ssl);
  454. // successful negotiation
  455. if (status == 1) break;
  456. // error or non-blocking requires more time
  457. if (status < 0) {
  458. err = SSL_get_error(ssl, status);
  459. if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) continue;
  460. }
  461. LOG_WARN("unable to open SSL socket %d (%d)", status, err);
  462. closesocket(sock);
  463. SSL_free(ssl);
  464. ssl = NULL;
  465. LOCK;
  466. stream.state = DISCONNECT;
  467. stream.disconnect = UNREACHABLE;
  468. UNLOCK;
  469. return;
  470. }
  471. } else {
  472. ssl = NULL;
  473. }
  474. #endif
  475. buf_flush(streambuf);
  476. LOCK;
  477. fd = sock;
  478. stream.state = SEND_HEADERS;
  479. stream.cont_wait = cont_wait;
  480. stream.meta_interval = 0;
  481. stream.meta_next = 0;
  482. stream.meta_left = 0;
  483. stream.meta_send = false;
  484. stream.header_len = header_len;
  485. memcpy(stream.header, header, header_len);
  486. *(stream.header+header_len) = '\0';
  487. LOG_INFO("header: %s", stream.header);
  488. stream.sent_headers = false;
  489. stream.bytes = 0;
  490. stream.threshold = threshold;
  491. UNLOCK;
  492. }
  493. bool stream_disconnect(void) {
  494. bool disc = false;
  495. LOCK;
  496. #if USE_SSL
  497. if (ssl) {
  498. SSL_shutdown(ssl);
  499. SSL_free(ssl);
  500. ssl = NULL;
  501. }
  502. #endif
  503. if (fd != -1) {
  504. closesocket(fd);
  505. fd = -1;
  506. disc = true;
  507. }
  508. stream.state = STOPPED;
  509. UNLOCK;
  510. return disc;
  511. }