stream.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  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 EXT_RAM_ATTR streamstate stream;
  53. static EXT_RAM_ATTR struct {
  54. enum { OGG_OFF, OGG_SYNC, OGG_HEADER, OGG_SEGMENTS, OGG_PAGE } state;
  55. size_t want, miss, match;
  56. u64_t granule;
  57. u8_t* data, segments[255];
  58. #pragma pack(push, 1)
  59. struct {
  60. char pattern[4];
  61. u8_t version, type;
  62. u64_t granule;
  63. u32_t serial, page, checksum;
  64. u8_t count;
  65. } header;
  66. #pragma pack(pop)
  67. } ogg;
  68. #if USE_SSL
  69. static SSL_CTX *SSLctx;
  70. SSL *ssl;
  71. #endif
  72. #if !USE_SSL
  73. #define _recv(ssl, fc, buf, n, opt) recv(fd, buf, n, opt)
  74. #define _send(ssl, fd, buf, n, opt) send(fd, buf, n, opt)
  75. #define _poll(ssl, pollinfo, timeout) poll(pollinfo, 1, timeout)
  76. #define _last_error() last_error()
  77. #else
  78. #define _last_error() ERROR_WOULDBLOCK
  79. static int _recv(SSL *ssl, int fd, void *buffer, size_t bytes, int options) {
  80. int n;
  81. if (!ssl) return recv(fd, buffer, bytes, options);
  82. n = SSL_read(ssl, (u8_t*) buffer, bytes);
  83. if (n <= 0 && SSL_get_error(ssl, n) == SSL_ERROR_ZERO_RETURN) return 0;
  84. return n;
  85. }
  86. static int _send(SSL *ssl, int fd, void *buffer, size_t bytes, int options) {
  87. int n;
  88. if (!ssl) return send(fd, buffer, bytes, options);
  89. while (1) {
  90. int err;
  91. ERR_clear_error();
  92. if ((n = SSL_write(ssl, (u8_t*) buffer, bytes)) >= 0) return n;
  93. err = SSL_get_error(ssl, n);
  94. if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) continue;
  95. LOG_INFO("SSL write error %d", err );
  96. return n;
  97. }
  98. }
  99. /*
  100. can't mimic exactly poll as SSL is a real pain. Even if SSL_pending returns
  101. 0, there might be bytes to read but when select (poll) return > 0, there might
  102. be no frame available. As well select (poll) < 0 does not mean that there is
  103. no data pending
  104. */
  105. static int _poll(SSL *ssl, struct pollfd *pollinfo, int timeout) {
  106. if (!ssl) return poll(pollinfo, 1, timeout);
  107. if (pollinfo->events & POLLIN && SSL_pending(ssl)) {
  108. if (pollinfo->events & POLLOUT) poll(pollinfo, 1, 0);
  109. pollinfo->revents = POLLIN;
  110. return 1;
  111. }
  112. return poll(pollinfo, 1, timeout);
  113. }
  114. #endif
  115. static bool send_header(void) {
  116. char *ptr = stream.header;
  117. int len = stream.header_len;
  118. unsigned try = 0;
  119. ssize_t n;
  120. while (len) {
  121. n = _send(ssl, fd, ptr, len, MSG_NOSIGNAL);
  122. if (n <= 0) {
  123. if (n < 0 && _last_error() == ERROR_WOULDBLOCK && try < 10) {
  124. LOG_SDEBUG("retrying (%d) writing to socket", ++try);
  125. usleep(1000);
  126. continue;
  127. }
  128. LOG_INFO("failed writing to socket: %s", strerror(last_error()));
  129. stream.disconnect = LOCAL_DISCONNECT;
  130. stream.state = DISCONNECT;
  131. wake_controller();
  132. return false;
  133. }
  134. LOG_SDEBUG("wrote %d bytes to socket", n);
  135. ptr += n;
  136. len -= n;
  137. }
  138. LOG_SDEBUG("wrote header");
  139. return true;
  140. }
  141. static bool running = true;
  142. static void _disconnect(stream_state state, disconnect_code disconnect) {
  143. stream.state = state;
  144. stream.disconnect = disconnect;
  145. if (ogg.state == OGG_PAGE && ogg.data) free(ogg.data);
  146. ogg.data = NULL;
  147. #if USE_SSL
  148. if (ssl) {
  149. SSL_shutdown(ssl);
  150. SSL_free(ssl);
  151. ssl = NULL;
  152. }
  153. #endif
  154. closesocket(fd);
  155. fd = -1;
  156. wake_controller();
  157. }
  158. static size_t memfind(const u8_t* haystack, size_t n, const char* needle, size_t len, size_t* offset) {
  159. size_t i;
  160. for (i = 0; i < n && *offset != len; i++) *offset = (haystack[i] == needle[*offset]) ? *offset + 1 : 0;
  161. return i;
  162. }
  163. static void stream_ogg(size_t n) {
  164. if (ogg.state == OGG_OFF) return;
  165. u8_t* p = streambuf->writep;
  166. while (n) {
  167. size_t consumed = min(ogg.miss, n);
  168. // copy as many bytes as possible and come back later if we do'nt have enough
  169. if (ogg.data) {
  170. memcpy(ogg.data + ogg.want - ogg.miss, p, consumed);
  171. ogg.miss -= consumed;
  172. if (ogg.miss) return;
  173. }
  174. // we have what we want, let's parse
  175. switch (ogg.state) {
  176. case OGG_SYNC: {
  177. ogg.miss -= consumed;
  178. if (consumed) break;
  179. // we have to memorize position in case any of last 3 bytes match...
  180. size_t pos = memfind(p, n, "OggS", 4, &ogg.match);
  181. if (ogg.match == 4) {
  182. consumed = pos - ogg.match;
  183. ogg.state = OGG_HEADER;
  184. ogg.miss = ogg.want = sizeof(ogg.header);
  185. ogg.data = (u8_t*) &ogg.header;
  186. ogg.match = 0;
  187. } else {
  188. if (!ogg.match) {
  189. LOG_INFO("OggS not at expected position %zu/%zu", pos, n);
  190. }
  191. return;
  192. }
  193. break;
  194. }
  195. case OGG_HEADER:
  196. if (!memcmp(ogg.header.pattern, "OggS", 4)) {
  197. ogg.miss = ogg.want = ogg.header.count;
  198. ogg.data = ogg.segments;
  199. ogg.state = OGG_SEGMENTS;
  200. } else {
  201. ogg.state = OGG_SYNC;
  202. ogg.data = NULL;
  203. }
  204. break;
  205. case OGG_SEGMENTS:
  206. // calculate size of page using lacing values
  207. for (size_t i = 0; i < ogg.want; i++) ogg.miss += ogg.data[i];
  208. ogg.want = ogg.miss;
  209. if (ogg.header.granule == 0 || (ogg.header.granule == -1 && ogg.granule == 0)) {
  210. // granule 0 means a new stream, so let's look into it
  211. ogg.state = OGG_PAGE;
  212. ogg.data = malloc(ogg.want);
  213. } else {
  214. // otherwise, jump over data
  215. ogg.state = OGG_SYNC;
  216. ogg.data = NULL;
  217. }
  218. // memorize granule for next page
  219. if (ogg.header.granule != -1) ogg.granule = ogg.header.granule;
  220. break;
  221. case OGG_PAGE: {
  222. size_t offset = 0;
  223. // try to find one of valid Ogg pattern (vorbis, opus)
  224. for (char** tag = (char*[]) { "\x3vorbis", "OpusTags", NULL }; *tag; tag++, offset = 0) {
  225. size_t pos = memfind(ogg.data, ogg.want, *tag, strlen(*tag), &offset);
  226. if (offset != strlen(*tag)) continue;
  227. // u32:len,char[]:vendorId, u32:N, N x (u32:len,char[]:comment)
  228. char* p = (char*) ogg.data + pos;
  229. p += *p + 4;
  230. u32_t count = *p;
  231. p += 4;
  232. // LMS metadata format for Ogg is "Ogg", N x (u16:len,char[]:comment)
  233. memcpy(stream.header, "Ogg", 3);
  234. stream.header_len = 3;
  235. for (u32_t len; count--; p += len) {
  236. len = *p;
  237. p += 4;
  238. // only report what we use and don't overflow (network byte order)
  239. if (!strncasecmp(p, "TITLE=", 6) || !strncasecmp(p, "ARTIST=", 7) || !strncasecmp(p, "ALBUM=", 6)) {
  240. if (stream.header_len + len > MAX_HEADER) break;
  241. stream.header[stream.header_len++] = len >> 8;
  242. stream.header[stream.header_len++] = len;
  243. memcpy(stream.header + stream.header_len, p, len);
  244. stream.header_len += len;
  245. LOG_INFO("metadata: %.*s", len, p);
  246. }
  247. }
  248. stream.meta_send = true;
  249. wake_controller();
  250. LOG_INFO("Ogg metadata length: %u", stream.header_len - 3);
  251. break;
  252. }
  253. free(ogg.data);
  254. ogg.data = NULL;
  255. ogg.state = OGG_SYNC;
  256. break;
  257. }
  258. default:
  259. break;
  260. }
  261. p += consumed;
  262. n -= consumed;
  263. }
  264. }
  265. static void *stream_thread() {
  266. while (running) {
  267. struct pollfd pollinfo;
  268. size_t space;
  269. LOCK;
  270. space = min(_buf_space(streambuf), _buf_cont_write(streambuf));
  271. if (fd < 0 || !space || stream.state <= STREAMING_WAIT) {
  272. UNLOCK;
  273. usleep(space ? 100000 : 25000);
  274. continue;
  275. }
  276. if (stream.state == STREAMING_FILE) {
  277. int n = read(fd, streambuf->writep, space);
  278. if (n == 0) {
  279. LOG_INFO("end of stream");
  280. _disconnect(DISCONNECT, DISCONNECT_OK);
  281. }
  282. if (n > 0) {
  283. _buf_inc_writep(streambuf, n);
  284. stream.bytes += n;
  285. LOG_SDEBUG("streambuf read %d bytes", n);
  286. }
  287. if (n < 0) {
  288. LOG_WARN("error reading: %s", strerror(last_error()));
  289. _disconnect(DISCONNECT, REMOTE_DISCONNECT);
  290. }
  291. UNLOCK;
  292. continue;
  293. } else {
  294. pollinfo.fd = fd;
  295. pollinfo.events = POLLIN;
  296. if (stream.state == SEND_HEADERS) {
  297. pollinfo.events |= POLLOUT;
  298. }
  299. }
  300. UNLOCK;
  301. // no mutex needed - we just want to know if we are inside poll()
  302. polling = true;
  303. if (_poll(ssl, &pollinfo, 100)) {
  304. polling = false;
  305. LOCK;
  306. // check socket has not been closed while in poll
  307. if (fd < 0) {
  308. UNLOCK;
  309. continue;
  310. }
  311. if ((pollinfo.revents & POLLOUT) && stream.state == SEND_HEADERS) {
  312. if (send_header()) stream.state = RECV_HEADERS;
  313. stream.header_len = 0;
  314. UNLOCK;
  315. continue;
  316. }
  317. if (pollinfo.revents & (POLLIN | POLLHUP)) {
  318. // get response headers
  319. if (stream.state == RECV_HEADERS) {
  320. // read one byte at a time to catch end of header
  321. char c;
  322. static int endtok;
  323. int n = _recv(ssl, fd, &c, 1, 0);
  324. if (n <= 0) {
  325. if (n < 0 && _last_error() == ERROR_WOULDBLOCK) {
  326. UNLOCK;
  327. continue;
  328. }
  329. LOG_INFO("error reading headers: %s", n ? strerror(last_error()) : "closed");
  330. _disconnect(STOPPED, LOCAL_DISCONNECT);
  331. UNLOCK;
  332. continue;
  333. }
  334. *(stream.header + stream.header_len) = c;
  335. stream.header_len++;
  336. if (stream.header_len > MAX_HEADER - 1) {
  337. LOG_ERROR("received headers too long: %u", stream.header_len);
  338. _disconnect(DISCONNECT, LOCAL_DISCONNECT);
  339. }
  340. if (stream.header_len > 1 && (c == '\r' || c == '\n')) {
  341. endtok++;
  342. if (endtok == 4) {
  343. *(stream.header + stream.header_len) = '\0';
  344. LOG_INFO("headers: len: %d\n%s", stream.header_len, stream.header);
  345. stream.state = stream.cont_wait ? STREAMING_WAIT : STREAMING_BUFFERING;
  346. wake_controller();
  347. }
  348. } else {
  349. endtok = 0;
  350. }
  351. UNLOCK;
  352. continue;
  353. }
  354. // receive icy meta data
  355. if (stream.meta_interval && stream.meta_next == 0) {
  356. if (stream.meta_left == 0) {
  357. // read meta length
  358. u8_t c;
  359. int n = _recv(ssl, fd, &c, 1, 0);
  360. if (n <= 0) {
  361. if (n < 0 && _last_error() == ERROR_WOULDBLOCK) {
  362. UNLOCK;
  363. continue;
  364. }
  365. LOG_INFO("error reading icy meta: %s", n ? strerror(last_error()) : "closed");
  366. _disconnect(STOPPED, LOCAL_DISCONNECT);
  367. UNLOCK;
  368. continue;
  369. }
  370. stream.meta_left = 16 * c;
  371. stream.header_len = 0; // amount of received meta data
  372. // MAX_HEADER must be more than meta max of 16 * 255
  373. }
  374. if (stream.meta_left) {
  375. int n = _recv(ssl, fd, stream.header + stream.header_len, stream.meta_left, 0);
  376. if (n <= 0) {
  377. if (n < 0 && _last_error() == ERROR_WOULDBLOCK) {
  378. UNLOCK;
  379. continue;
  380. }
  381. LOG_INFO("error reading icy meta: %s", n ? strerror(last_error()) : "closed");
  382. _disconnect(STOPPED, LOCAL_DISCONNECT);
  383. UNLOCK;
  384. continue;
  385. }
  386. stream.meta_left -= n;
  387. stream.header_len += n;
  388. }
  389. if (stream.meta_left == 0) {
  390. if (stream.header_len) {
  391. *(stream.header + stream.header_len) = '\0';
  392. LOG_INFO("icy meta: len: %u\n%s", stream.header_len, stream.header);
  393. stream.meta_send = true;
  394. wake_controller();
  395. }
  396. stream.meta_next = stream.meta_interval;
  397. UNLOCK;
  398. continue;
  399. }
  400. // stream body into streambuf
  401. } else {
  402. int n;
  403. space = min(_buf_space(streambuf), _buf_cont_write(streambuf));
  404. if (stream.meta_interval) {
  405. space = min(space, stream.meta_next);
  406. }
  407. n = _recv(ssl, fd, streambuf->writep, space, 0);
  408. if (n == 0) {
  409. LOG_INFO("end of stream (%u bytes)", stream.bytes);
  410. _disconnect(DISCONNECT, DISCONNECT_OK);
  411. }
  412. if (n < 0 && _last_error() != ERROR_WOULDBLOCK) {
  413. LOG_INFO("error reading: %s", strerror(last_error()));
  414. _disconnect(DISCONNECT, REMOTE_DISCONNECT);
  415. }
  416. if (n > 0) {
  417. stream_ogg(n);
  418. _buf_inc_writep(streambuf, n);
  419. stream.bytes += n;
  420. if (stream.meta_interval) {
  421. stream.meta_next -= n;
  422. }
  423. } else {
  424. UNLOCK;
  425. continue;
  426. }
  427. if (stream.state == STREAMING_BUFFERING && stream.bytes > stream.threshold) {
  428. stream.state = STREAMING_HTTP;
  429. wake_controller();
  430. }
  431. LOG_SDEBUG("streambuf read %d bytes", n);
  432. }
  433. }
  434. UNLOCK;
  435. } else {
  436. polling = false;
  437. LOG_SDEBUG("poll timeout");
  438. }
  439. }
  440. #if USE_SSL
  441. if (SSLctx) {
  442. SSL_CTX_free(SSLctx);
  443. }
  444. #endif
  445. return 0;
  446. }
  447. static thread_type thread;
  448. void stream_init(log_level level, unsigned stream_buf_size) {
  449. loglevel = level;
  450. LOG_INFO("init stream");
  451. LOG_DEBUG("streambuf size: %u", stream_buf_size);
  452. buf_init(streambuf, stream_buf_size);
  453. if (streambuf->buf == NULL) {
  454. LOG_ERROR("unable to malloc buffer");
  455. exit(2);
  456. }
  457. #if USE_SSL
  458. #if !LINKALL && !NO_SSLSYM
  459. if (ssl_loaded) {
  460. #endif
  461. SSL_library_init();
  462. SSLctx = SSL_CTX_new(SSLv23_client_method());
  463. if (SSLctx == NULL) {
  464. LOG_ERROR("unable to allocate SSL context");
  465. exit(3);
  466. }
  467. SSL_CTX_set_options(SSLctx, SSL_OP_NO_SSLv2);
  468. #if !LINKALL && !NO_SSLSYM
  469. }
  470. #endif
  471. ssl = NULL;
  472. #endif
  473. #if SUN
  474. signal(SIGPIPE, SIG_IGN); /* Force sockets to return -1 with EPIPE on pipe signal */
  475. #endif
  476. stream.state = STOPPED;
  477. stream.header = malloc(MAX_HEADER);
  478. *stream.header = '\0';
  479. fd = -1;
  480. #if LINUX || FREEBSD
  481. touch_memory(streambuf->buf, streambuf->size);
  482. #endif
  483. #if LINUX || OSX || FREEBSD || EMBEDDED
  484. pthread_attr_t attr;
  485. pthread_attr_init(&attr);
  486. #ifdef PTHREAD_STACK_MIN
  487. pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN + STREAM_THREAD_STACK_SIZE);
  488. #endif
  489. pthread_create_name(&thread, &attr, stream_thread, NULL, "stream");
  490. pthread_attr_destroy(&attr);
  491. #endif
  492. #if WIN
  493. thread = CreateThread(NULL, STREAM_THREAD_STACK_SIZE, (LPTHREAD_START_ROUTINE)&stream_thread, NULL, 0, NULL);
  494. #endif
  495. }
  496. void stream_close(void) {
  497. LOG_INFO("close stream");
  498. LOCK;
  499. running = false;
  500. UNLOCK;
  501. #if LINUX || OSX || FREEBSD || EMBEDDED
  502. pthread_join(thread, NULL);
  503. #endif
  504. free(stream.header);
  505. buf_destroy(streambuf);
  506. }
  507. void stream_file(const char *header, size_t header_len, unsigned threshold) {
  508. buf_flush(streambuf);
  509. LOCK;
  510. stream.header_len = header_len;
  511. memcpy(stream.header, header, header_len);
  512. *(stream.header+header_len) = '\0';
  513. LOG_INFO("opening local file: %s", stream.header);
  514. #if WIN
  515. fd = open(stream.header, O_RDONLY | O_BINARY);
  516. #else
  517. fd = open(stream.header, O_RDONLY);
  518. #endif
  519. stream.state = STREAMING_FILE;
  520. if (fd < 0) {
  521. LOG_INFO("can't open file: %s", stream.header);
  522. stream.state = DISCONNECT;
  523. }
  524. wake_controller();
  525. stream.cont_wait = false;
  526. stream.meta_interval = 0;
  527. stream.meta_next = 0;
  528. stream.meta_left = 0;
  529. stream.meta_send = false;
  530. stream.sent_headers = false;
  531. stream.bytes = 0;
  532. stream.threshold = threshold;
  533. UNLOCK;
  534. }
  535. void stream_sock(u32_t ip, u16_t port, char codec, const char *header, size_t header_len, unsigned threshold, bool cont_wait) {
  536. struct sockaddr_in addr;
  537. #if EMBEDDED
  538. // wait till we are not polling anymore
  539. while (polling && running) { usleep(10000); }
  540. #endif
  541. int sock = socket(AF_INET, SOCK_STREAM, 0);
  542. if (sock < 0) {
  543. LOG_ERROR("failed to create socket");
  544. return;
  545. }
  546. memset(&addr, 0, sizeof(addr));
  547. addr.sin_family = AF_INET;
  548. addr.sin_addr.s_addr = ip;
  549. addr.sin_port = port;
  550. LOG_INFO("connecting to %s:%d", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
  551. set_nonblock(sock);
  552. set_nosigpipe(sock);
  553. if (connect_timeout(sock, (struct sockaddr *) &addr, sizeof(addr), 10) < 0) {
  554. LOG_INFO("unable to connect to server");
  555. LOCK;
  556. stream.state = DISCONNECT;
  557. stream.disconnect = UNREACHABLE;
  558. UNLOCK;
  559. return;
  560. }
  561. #if USE_SSL
  562. if (ntohs(port) == 443) {
  563. char server[256], *p;
  564. ssl = SSL_new(SSLctx);
  565. SSL_set_fd(ssl, sock);
  566. // add SNI
  567. sscanf(header, "Host:%255s", server);
  568. if (server) {
  569. if ((p = strchr(server, ':')) != NULL) *p = '\0';
  570. SSL_set_tlsext_host_name(ssl, server);
  571. }
  572. while (1) {
  573. int status, err = 0;
  574. ERR_clear_error();
  575. status = SSL_connect(ssl);
  576. // successful negotiation
  577. if (status == 1) break;
  578. // error or non-blocking requires more time
  579. if (status < 0) {
  580. err = SSL_get_error(ssl, status);
  581. if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) continue;
  582. }
  583. LOG_WARN("unable to open SSL socket %d (%d)", status, err);
  584. closesocket(sock);
  585. SSL_free(ssl);
  586. ssl = NULL;
  587. LOCK;
  588. stream.state = DISCONNECT;
  589. stream.disconnect = UNREACHABLE;
  590. UNLOCK;
  591. return;
  592. }
  593. } else {
  594. ssl = NULL;
  595. }
  596. #endif
  597. buf_flush(streambuf);
  598. LOCK;
  599. fd = sock;
  600. stream.state = SEND_HEADERS;
  601. stream.cont_wait = cont_wait;
  602. stream.meta_interval = 0;
  603. stream.meta_next = 0;
  604. stream.meta_left = 0;
  605. stream.meta_send = false;
  606. stream.header_len = header_len;
  607. memcpy(stream.header, header, header_len);
  608. *(stream.header+header_len) = '\0';
  609. LOG_INFO("header: %s", stream.header);
  610. stream.sent_headers = false;
  611. stream.bytes = 0;
  612. stream.threshold = threshold;
  613. ogg.miss = ogg.match = 0;
  614. ogg.state = (codec == 'o' || codec == 'p') ? OGG_SYNC : OGG_OFF;
  615. UNLOCK;
  616. }
  617. bool stream_disconnect(void) {
  618. bool disc = false;
  619. LOCK;
  620. #if USE_SSL
  621. if (ssl) {
  622. SSL_shutdown(ssl);
  623. SSL_free(ssl);
  624. ssl = NULL;
  625. }
  626. #endif
  627. if (fd != -1) {
  628. closesocket(fd);
  629. fd = -1;
  630. disc = true;
  631. }
  632. stream.state = STOPPED;
  633. if (ogg.state == OGG_PAGE && ogg.data) free(ogg.data);
  634. ogg.data = NULL;
  635. UNLOCK;
  636. return disc;
  637. }