stream.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  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. u32_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 u32_t memfind(const u8_t* haystack, u32_t n, const char* needle, u32_t len, u32_t *offset) {
  159. int 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. int 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. LOG_INFO("OggS not at expected position");
  189. return;
  190. }
  191. break;
  192. }
  193. case OGG_HEADER:
  194. if (!memcmp(ogg.header.pattern, "OggS", 4)) {
  195. ogg.miss = ogg.want = ogg.header.count;
  196. ogg.data = ogg.segments;
  197. ogg.state = OGG_SEGMENTS;
  198. } else {
  199. ogg.state = OGG_SYNC;
  200. ogg.data = NULL;
  201. }
  202. break;
  203. case OGG_SEGMENTS:
  204. // calculate size of page using lacing values
  205. for (int i = 0; i < ogg.want; i++) ogg.miss += ogg.data[i];
  206. ogg.want = ogg.miss;
  207. if (ogg.header.granule == 0 || (ogg.header.granule == -1 && ogg.granule == 0)) {
  208. // granule 0 means a new stream, so let's look into it
  209. ogg.state = OGG_PAGE;
  210. ogg.data = malloc(ogg.want);
  211. } else {
  212. // otherwise, jump over data
  213. ogg.state = OGG_SYNC;
  214. ogg.data = NULL;
  215. ogg.granule = ogg.header.granule;
  216. }
  217. break;
  218. case OGG_PAGE: {
  219. u32_t offset = 0;
  220. // try to find one of valid Ogg pattern (vorbis, opus)
  221. for (char** tag = (char*[]) { "\x3vorbis", "OpusTags", NULL }; *tag; tag++, offset = 0) {
  222. u32_t pos = memfind(ogg.data, ogg.want, *tag, strlen(*tag), &offset);
  223. if (offset != strlen(*tag)) continue;
  224. // u32:len,char[]:vendorId, u32:N, N x (u32:len,char[]:comment)
  225. char* p = (char*) ogg.data + pos;
  226. p += *p + 4;
  227. u32_t count = *p;
  228. p += 4;
  229. // LMS metadata format for Ogg is "Ogg", N x (u16:len,char[]:comment)
  230. memcpy(stream.header, "Ogg", 3);
  231. stream.header_len = 3;
  232. for (u32_t len; count--; p += len) {
  233. len = *p;
  234. p += 4;
  235. // only report what we use and don't overflow (network byte order)
  236. if (!strncasecmp(p, "TITLE=", 6) || !strncasecmp(p, "ARTIST=", 7) || !strncasecmp(p, "ALBUM=", 6)) {
  237. if (stream.header_len + len > MAX_HEADER) break;
  238. stream.header[stream.header_len++] = len >> 8;
  239. stream.header[stream.header_len++] = len;
  240. memcpy(stream.header + stream.header_len, p, len);
  241. stream.header_len += len;
  242. LOG_INFO("metadata: %.*s", len, p);
  243. }
  244. }
  245. stream.meta_send = true;
  246. wake_controller();
  247. LOG_INFO("Ogg metadata length: %u", stream.header_len - 3);
  248. break;
  249. }
  250. free(ogg.data);
  251. ogg.data = NULL;
  252. ogg.state = OGG_SYNC;
  253. break;
  254. }
  255. default:
  256. break;
  257. }
  258. p += consumed;
  259. n -= consumed;
  260. }
  261. }
  262. static void *stream_thread() {
  263. while (running) {
  264. struct pollfd pollinfo;
  265. size_t space;
  266. LOCK;
  267. space = min(_buf_space(streambuf), _buf_cont_write(streambuf));
  268. if (fd < 0 || !space || stream.state <= STREAMING_WAIT) {
  269. UNLOCK;
  270. usleep(space ? 100000 : 25000);
  271. continue;
  272. }
  273. if (stream.state == STREAMING_FILE) {
  274. int n = read(fd, streambuf->writep, space);
  275. if (n == 0) {
  276. LOG_INFO("end of stream");
  277. _disconnect(DISCONNECT, DISCONNECT_OK);
  278. }
  279. if (n > 0) {
  280. _buf_inc_writep(streambuf, n);
  281. stream.bytes += n;
  282. LOG_SDEBUG("streambuf read %d bytes", n);
  283. }
  284. if (n < 0) {
  285. LOG_WARN("error reading: %s", strerror(last_error()));
  286. _disconnect(DISCONNECT, REMOTE_DISCONNECT);
  287. }
  288. UNLOCK;
  289. continue;
  290. } else {
  291. pollinfo.fd = fd;
  292. pollinfo.events = POLLIN;
  293. if (stream.state == SEND_HEADERS) {
  294. pollinfo.events |= POLLOUT;
  295. }
  296. }
  297. UNLOCK;
  298. // no mutex needed - we just want to know if we are inside poll()
  299. polling = true;
  300. if (_poll(ssl, &pollinfo, 100)) {
  301. polling = false;
  302. LOCK;
  303. // check socket has not been closed while in poll
  304. if (fd < 0) {
  305. UNLOCK;
  306. continue;
  307. }
  308. if ((pollinfo.revents & POLLOUT) && stream.state == SEND_HEADERS) {
  309. if (send_header()) stream.state = RECV_HEADERS;
  310. stream.header_len = 0;
  311. UNLOCK;
  312. continue;
  313. }
  314. if (pollinfo.revents & (POLLIN | POLLHUP)) {
  315. // get response headers
  316. if (stream.state == RECV_HEADERS) {
  317. // read one byte at a time to catch end of header
  318. char c;
  319. static int endtok;
  320. int n = _recv(ssl, fd, &c, 1, 0);
  321. if (n <= 0) {
  322. if (n < 0 && _last_error() == ERROR_WOULDBLOCK) {
  323. UNLOCK;
  324. continue;
  325. }
  326. LOG_INFO("error reading headers: %s", n ? strerror(last_error()) : "closed");
  327. _disconnect(STOPPED, LOCAL_DISCONNECT);
  328. UNLOCK;
  329. continue;
  330. }
  331. *(stream.header + stream.header_len) = c;
  332. stream.header_len++;
  333. if (stream.header_len > MAX_HEADER - 1) {
  334. LOG_ERROR("received headers too long: %u", stream.header_len);
  335. _disconnect(DISCONNECT, LOCAL_DISCONNECT);
  336. }
  337. if (stream.header_len > 1 && (c == '\r' || c == '\n')) {
  338. endtok++;
  339. if (endtok == 4) {
  340. *(stream.header + stream.header_len) = '\0';
  341. LOG_INFO("headers: len: %d\n%s", stream.header_len, stream.header);
  342. stream.state = stream.cont_wait ? STREAMING_WAIT : STREAMING_BUFFERING;
  343. wake_controller();
  344. }
  345. } else {
  346. endtok = 0;
  347. }
  348. UNLOCK;
  349. continue;
  350. }
  351. // receive icy meta data
  352. if (stream.meta_interval && stream.meta_next == 0) {
  353. if (stream.meta_left == 0) {
  354. // read meta length
  355. u8_t c;
  356. int n = _recv(ssl, fd, &c, 1, 0);
  357. if (n <= 0) {
  358. if (n < 0 && _last_error() == ERROR_WOULDBLOCK) {
  359. UNLOCK;
  360. continue;
  361. }
  362. LOG_INFO("error reading icy meta: %s", n ? strerror(last_error()) : "closed");
  363. _disconnect(STOPPED, LOCAL_DISCONNECT);
  364. UNLOCK;
  365. continue;
  366. }
  367. stream.meta_left = 16 * c;
  368. stream.header_len = 0; // amount of received meta data
  369. // MAX_HEADER must be more than meta max of 16 * 255
  370. }
  371. if (stream.meta_left) {
  372. int n = _recv(ssl, fd, stream.header + stream.header_len, stream.meta_left, 0);
  373. if (n <= 0) {
  374. if (n < 0 && _last_error() == ERROR_WOULDBLOCK) {
  375. UNLOCK;
  376. continue;
  377. }
  378. LOG_INFO("error reading icy meta: %s", n ? strerror(last_error()) : "closed");
  379. _disconnect(STOPPED, LOCAL_DISCONNECT);
  380. UNLOCK;
  381. continue;
  382. }
  383. stream.meta_left -= n;
  384. stream.header_len += n;
  385. }
  386. if (stream.meta_left == 0) {
  387. if (stream.header_len) {
  388. *(stream.header + stream.header_len) = '\0';
  389. LOG_INFO("icy meta: len: %u\n%s", stream.header_len, stream.header);
  390. stream.meta_send = true;
  391. wake_controller();
  392. }
  393. stream.meta_next = stream.meta_interval;
  394. UNLOCK;
  395. continue;
  396. }
  397. // stream body into streambuf
  398. } else {
  399. int n;
  400. space = min(_buf_space(streambuf), _buf_cont_write(streambuf));
  401. if (stream.meta_interval) {
  402. space = min(space, stream.meta_next);
  403. }
  404. n = _recv(ssl, fd, streambuf->writep, space, 0);
  405. if (n == 0) {
  406. LOG_INFO("end of stream (%u bytes)", stream.bytes);
  407. _disconnect(DISCONNECT, DISCONNECT_OK);
  408. }
  409. if (n < 0 && _last_error() != ERROR_WOULDBLOCK) {
  410. LOG_INFO("error reading: %s", strerror(last_error()));
  411. _disconnect(DISCONNECT, REMOTE_DISCONNECT);
  412. }
  413. if (n > 0) {
  414. stream_ogg(n);
  415. _buf_inc_writep(streambuf, n);
  416. stream.bytes += n;
  417. if (stream.meta_interval) {
  418. stream.meta_next -= n;
  419. }
  420. } else {
  421. UNLOCK;
  422. continue;
  423. }
  424. if (stream.state == STREAMING_BUFFERING && stream.bytes > stream.threshold) {
  425. stream.state = STREAMING_HTTP;
  426. wake_controller();
  427. }
  428. LOG_SDEBUG("streambuf read %d bytes", n);
  429. }
  430. }
  431. UNLOCK;
  432. } else {
  433. polling = false;
  434. LOG_SDEBUG("poll timeout");
  435. }
  436. }
  437. #if USE_SSL
  438. if (SSLctx) {
  439. SSL_CTX_free(SSLctx);
  440. }
  441. #endif
  442. return 0;
  443. }
  444. static thread_type thread;
  445. void stream_init(log_level level, unsigned stream_buf_size) {
  446. loglevel = level;
  447. LOG_INFO("init stream");
  448. LOG_DEBUG("streambuf size: %u", stream_buf_size);
  449. buf_init(streambuf, stream_buf_size);
  450. if (streambuf->buf == NULL) {
  451. LOG_ERROR("unable to malloc buffer");
  452. exit(2);
  453. }
  454. #if USE_SSL
  455. #if !LINKALL && !NO_SSLSYM
  456. if (ssl_loaded) {
  457. #endif
  458. SSL_library_init();
  459. SSLctx = SSL_CTX_new(SSLv23_client_method());
  460. if (SSLctx == NULL) {
  461. LOG_ERROR("unable to allocate SSL context");
  462. exit(3);
  463. }
  464. SSL_CTX_set_options(SSLctx, SSL_OP_NO_SSLv2);
  465. #if !LINKALL && !NO_SSLSYM
  466. }
  467. #endif
  468. ssl = NULL;
  469. #endif
  470. #if SUN
  471. signal(SIGPIPE, SIG_IGN); /* Force sockets to return -1 with EPIPE on pipe signal */
  472. #endif
  473. stream.state = STOPPED;
  474. stream.header = malloc(MAX_HEADER);
  475. *stream.header = '\0';
  476. fd = -1;
  477. #if LINUX || FREEBSD
  478. touch_memory(streambuf->buf, streambuf->size);
  479. #endif
  480. #if LINUX || OSX || FREEBSD || EMBEDDED
  481. pthread_attr_t attr;
  482. pthread_attr_init(&attr);
  483. #ifdef PTHREAD_STACK_MIN
  484. pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN + STREAM_THREAD_STACK_SIZE);
  485. #endif
  486. pthread_create_name(&thread, &attr, stream_thread, NULL, "stream");
  487. pthread_attr_destroy(&attr);
  488. #endif
  489. #if WIN
  490. thread = CreateThread(NULL, STREAM_THREAD_STACK_SIZE, (LPTHREAD_START_ROUTINE)&stream_thread, NULL, 0, NULL);
  491. #endif
  492. }
  493. void stream_close(void) {
  494. LOG_INFO("close stream");
  495. LOCK;
  496. running = false;
  497. UNLOCK;
  498. #if LINUX || OSX || FREEBSD || EMBEDDED
  499. pthread_join(thread, NULL);
  500. #endif
  501. free(stream.header);
  502. buf_destroy(streambuf);
  503. }
  504. void stream_file(const char *header, size_t header_len, unsigned threshold) {
  505. buf_flush(streambuf);
  506. LOCK;
  507. stream.header_len = header_len;
  508. memcpy(stream.header, header, header_len);
  509. *(stream.header+header_len) = '\0';
  510. LOG_INFO("opening local file: %s", stream.header);
  511. #if WIN
  512. fd = open(stream.header, O_RDONLY | O_BINARY);
  513. #else
  514. fd = open(stream.header, O_RDONLY);
  515. #endif
  516. stream.state = STREAMING_FILE;
  517. if (fd < 0) {
  518. LOG_INFO("can't open file: %s", stream.header);
  519. stream.state = DISCONNECT;
  520. }
  521. wake_controller();
  522. stream.cont_wait = false;
  523. stream.meta_interval = 0;
  524. stream.meta_next = 0;
  525. stream.meta_left = 0;
  526. stream.meta_send = false;
  527. stream.sent_headers = false;
  528. stream.bytes = 0;
  529. stream.threshold = threshold;
  530. UNLOCK;
  531. }
  532. void stream_sock(u32_t ip, u16_t port, char codec, const char *header, size_t header_len, unsigned threshold, bool cont_wait) {
  533. struct sockaddr_in addr;
  534. #if EMBEDDED
  535. // wait till we are not polling anymore
  536. while (polling && running) { usleep(10000); }
  537. #endif
  538. int sock = socket(AF_INET, SOCK_STREAM, 0);
  539. if (sock < 0) {
  540. LOG_ERROR("failed to create socket");
  541. return;
  542. }
  543. memset(&addr, 0, sizeof(addr));
  544. addr.sin_family = AF_INET;
  545. addr.sin_addr.s_addr = ip;
  546. addr.sin_port = port;
  547. LOG_INFO("connecting to %s:%d", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
  548. set_nonblock(sock);
  549. set_nosigpipe(sock);
  550. if (connect_timeout(sock, (struct sockaddr *) &addr, sizeof(addr), 10) < 0) {
  551. LOG_INFO("unable to connect to server");
  552. LOCK;
  553. stream.state = DISCONNECT;
  554. stream.disconnect = UNREACHABLE;
  555. UNLOCK;
  556. return;
  557. }
  558. #if USE_SSL
  559. if (ntohs(port) == 443) {
  560. char server[256], *p;
  561. ssl = SSL_new(SSLctx);
  562. SSL_set_fd(ssl, sock);
  563. // add SNI
  564. sscanf(header, "Host:%255s", server);
  565. if (server) {
  566. if ((p = strchr(server, ':')) != NULL) *p = '\0';
  567. SSL_set_tlsext_host_name(ssl, server);
  568. }
  569. while (1) {
  570. int status, err = 0;
  571. ERR_clear_error();
  572. status = SSL_connect(ssl);
  573. // successful negotiation
  574. if (status == 1) break;
  575. // error or non-blocking requires more time
  576. if (status < 0) {
  577. err = SSL_get_error(ssl, status);
  578. if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) continue;
  579. }
  580. LOG_WARN("unable to open SSL socket %d (%d)", status, err);
  581. closesocket(sock);
  582. SSL_free(ssl);
  583. ssl = NULL;
  584. LOCK;
  585. stream.state = DISCONNECT;
  586. stream.disconnect = UNREACHABLE;
  587. UNLOCK;
  588. return;
  589. }
  590. } else {
  591. ssl = NULL;
  592. }
  593. #endif
  594. buf_flush(streambuf);
  595. LOCK;
  596. fd = sock;
  597. stream.state = SEND_HEADERS;
  598. stream.cont_wait = cont_wait;
  599. stream.meta_interval = 0;
  600. stream.meta_next = 0;
  601. stream.meta_left = 0;
  602. stream.meta_send = false;
  603. stream.header_len = header_len;
  604. memcpy(stream.header, header, header_len);
  605. *(stream.header+header_len) = '\0';
  606. LOG_INFO("header: %s", stream.header);
  607. stream.sent_headers = false;
  608. stream.bytes = 0;
  609. stream.threshold = threshold;
  610. ogg.miss = ogg.match = 0;
  611. ogg.state = (codec == 'o' || codec == 'p') ? OGG_SYNC : OGG_OFF;
  612. UNLOCK;
  613. }
  614. bool stream_disconnect(void) {
  615. bool disc = false;
  616. LOCK;
  617. #if USE_SSL
  618. if (ssl) {
  619. SSL_shutdown(ssl);
  620. SSL_free(ssl);
  621. ssl = NULL;
  622. }
  623. #endif
  624. if (fd != -1) {
  625. closesocket(fd);
  626. fd = -1;
  627. disc = true;
  628. }
  629. stream.state = STOPPED;
  630. if (ogg.state == OGG_PAGE && ogg.data) free(ogg.data);
  631. ogg.data = NULL;
  632. UNLOCK;
  633. return disc;
  634. }