stream.c 13 KB

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