stream.c 19 KB

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