stream.c 19 KB

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