2
0

stream.c 13 KB

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