2
0

stream.c 13 KB

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