stream.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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. pollinfo.fd = fd;
  171. pollinfo.events = POLLIN;
  172. if (stream.state == SEND_HEADERS) {
  173. pollinfo.events |= POLLOUT;
  174. }
  175. }
  176. UNLOCK;
  177. // no mutex needed - we just want to know if we are inside poll()
  178. polling = true;
  179. if (_poll(ssl, &pollinfo, 100)) {
  180. polling = false;
  181. LOCK;
  182. // check socket has not been closed while in poll
  183. if (fd < 0) {
  184. UNLOCK;
  185. continue;
  186. }
  187. if ((pollinfo.revents & POLLOUT) && stream.state == SEND_HEADERS) {
  188. if (send_header()) stream.state = RECV_HEADERS;
  189. stream.header_len = 0;
  190. UNLOCK;
  191. continue;
  192. }
  193. if (pollinfo.revents & (POLLIN | POLLHUP)) {
  194. // get response headers
  195. if (stream.state == RECV_HEADERS) {
  196. // read one byte at a time to catch end of header
  197. char c;
  198. static int endtok;
  199. int n = _recv(ssl, fd, &c, 1, 0);
  200. if (n <= 0) {
  201. if (n < 0 && _last_error() == ERROR_WOULDBLOCK) {
  202. UNLOCK;
  203. continue;
  204. }
  205. LOG_INFO("error reading headers: %s", n ? strerror(last_error()) : "closed");
  206. _disconnect(STOPPED, LOCAL_DISCONNECT);
  207. UNLOCK;
  208. continue;
  209. }
  210. *(stream.header + stream.header_len) = c;
  211. stream.header_len++;
  212. if (stream.header_len > MAX_HEADER - 1) {
  213. LOG_ERROR("received headers too long: %u", stream.header_len);
  214. _disconnect(DISCONNECT, LOCAL_DISCONNECT);
  215. }
  216. if (stream.header_len > 1 && (c == '\r' || c == '\n')) {
  217. endtok++;
  218. if (endtok == 4) {
  219. *(stream.header + stream.header_len) = '\0';
  220. LOG_INFO("headers: len: %d\n%s", stream.header_len, stream.header);
  221. stream.state = stream.cont_wait ? STREAMING_WAIT : STREAMING_BUFFERING;
  222. wake_controller();
  223. }
  224. } else {
  225. endtok = 0;
  226. }
  227. UNLOCK;
  228. continue;
  229. }
  230. // receive icy meta data
  231. if (stream.meta_interval && stream.meta_next == 0) {
  232. if (stream.meta_left == 0) {
  233. // read meta length
  234. u8_t c;
  235. int n = _recv(ssl, fd, &c, 1, 0);
  236. if (n <= 0) {
  237. if (n < 0 && _last_error() == ERROR_WOULDBLOCK) {
  238. UNLOCK;
  239. continue;
  240. }
  241. LOG_INFO("error reading icy meta: %s", n ? strerror(last_error()) : "closed");
  242. _disconnect(STOPPED, LOCAL_DISCONNECT);
  243. UNLOCK;
  244. continue;
  245. }
  246. stream.meta_left = 16 * c;
  247. stream.header_len = 0; // amount of received meta data
  248. // MAX_HEADER must be more than meta max of 16 * 255
  249. }
  250. if (stream.meta_left) {
  251. int n = _recv(ssl, fd, stream.header + stream.header_len, stream.meta_left, 0);
  252. if (n <= 0) {
  253. if (n < 0 && _last_error() == ERROR_WOULDBLOCK) {
  254. UNLOCK;
  255. continue;
  256. }
  257. LOG_INFO("error reading icy meta: %s", n ? strerror(last_error()) : "closed");
  258. _disconnect(STOPPED, LOCAL_DISCONNECT);
  259. UNLOCK;
  260. continue;
  261. }
  262. stream.meta_left -= n;
  263. stream.header_len += n;
  264. }
  265. if (stream.meta_left == 0) {
  266. if (stream.header_len) {
  267. *(stream.header + stream.header_len) = '\0';
  268. LOG_INFO("icy meta: len: %u\n%s", stream.header_len, stream.header);
  269. stream.meta_send = true;
  270. wake_controller();
  271. }
  272. stream.meta_next = stream.meta_interval;
  273. UNLOCK;
  274. continue;
  275. }
  276. // stream body into streambuf
  277. } else {
  278. int n;
  279. space = min(_buf_space(streambuf), _buf_cont_write(streambuf));
  280. if (stream.meta_interval) {
  281. space = min(space, stream.meta_next);
  282. }
  283. n = _recv(ssl, fd, streambuf->writep, space, 0);
  284. if (n == 0) {
  285. LOG_INFO("end of stream (%u bytes)", stream.bytes);
  286. _disconnect(DISCONNECT, DISCONNECT_OK);
  287. }
  288. if (n < 0 && _last_error() != ERROR_WOULDBLOCK) {
  289. LOG_INFO("error reading: %s", strerror(last_error()));
  290. _disconnect(DISCONNECT, REMOTE_DISCONNECT);
  291. }
  292. if (n > 0) {
  293. _buf_inc_writep(streambuf, n);
  294. stream.bytes += n;
  295. if (stream.meta_interval) {
  296. stream.meta_next -= n;
  297. }
  298. } else {
  299. UNLOCK;
  300. continue;
  301. }
  302. if (stream.state == STREAMING_BUFFERING && stream.bytes > stream.threshold) {
  303. stream.state = STREAMING_HTTP;
  304. wake_controller();
  305. }
  306. LOG_SDEBUG("streambuf read %d bytes", n);
  307. }
  308. }
  309. UNLOCK;
  310. } else {
  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. while (polling && running) { usleep(10000); }
  415. #endif
  416. int sock = socket(AF_INET, SOCK_STREAM, 0);
  417. if (sock < 0) {
  418. LOG_ERROR("failed to create socket");
  419. return;
  420. }
  421. memset(&addr, 0, sizeof(addr));
  422. addr.sin_family = AF_INET;
  423. addr.sin_addr.s_addr = ip;
  424. addr.sin_port = port;
  425. LOG_INFO("connecting to %s:%d", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
  426. set_nonblock(sock);
  427. set_nosigpipe(sock);
  428. if (connect_timeout(sock, (struct sockaddr *) &addr, sizeof(addr), 10) < 0) {
  429. LOG_INFO("unable to connect to server");
  430. LOCK;
  431. stream.state = DISCONNECT;
  432. stream.disconnect = UNREACHABLE;
  433. UNLOCK;
  434. return;
  435. }
  436. #if USE_SSL
  437. if (ntohs(port) == 443) {
  438. char server[256], *p;
  439. ssl = SSL_new(SSLctx);
  440. SSL_set_fd(ssl, sock);
  441. // add SNI
  442. sscanf(header, "Host:%255s", server);
  443. if (server) {
  444. if ((p = strchr(server, ':')) != NULL) *p = '\0';
  445. SSL_set_tlsext_host_name(ssl, server);
  446. }
  447. while (1) {
  448. int status, err = 0;
  449. ERR_clear_error();
  450. status = SSL_connect(ssl);
  451. // successful negotiation
  452. if (status == 1) break;
  453. // error or non-blocking requires more time
  454. if (status < 0) {
  455. err = SSL_get_error(ssl, status);
  456. if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) continue;
  457. }
  458. LOG_WARN("unable to open SSL socket %d (%d)", status, err);
  459. closesocket(sock);
  460. SSL_free(ssl);
  461. ssl = NULL;
  462. LOCK;
  463. stream.state = DISCONNECT;
  464. stream.disconnect = UNREACHABLE;
  465. UNLOCK;
  466. return;
  467. }
  468. } else {
  469. ssl = NULL;
  470. }
  471. #endif
  472. buf_flush(streambuf);
  473. LOCK;
  474. fd = sock;
  475. stream.state = SEND_HEADERS;
  476. stream.cont_wait = cont_wait;
  477. stream.meta_interval = 0;
  478. stream.meta_next = 0;
  479. stream.meta_left = 0;
  480. stream.meta_send = false;
  481. stream.header_len = header_len;
  482. memcpy(stream.header, header, header_len);
  483. *(stream.header+header_len) = '\0';
  484. LOG_INFO("header: %s", stream.header);
  485. stream.sent_headers = false;
  486. stream.bytes = 0;
  487. stream.threshold = threshold;
  488. UNLOCK;
  489. }
  490. bool stream_disconnect(void) {
  491. bool disc = false;
  492. LOCK;
  493. #if USE_SSL
  494. if (ssl) {
  495. SSL_shutdown(ssl);
  496. SSL_free(ssl);
  497. ssl = NULL;
  498. }
  499. #endif
  500. if (fd != -1) {
  501. closesocket(fd);
  502. fd = -1;
  503. disc = true;
  504. }
  505. stream.state = STOPPED;
  506. UNLOCK;
  507. return disc;
  508. }