stream.c 13 KB

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