1 /* XMMS - Cross-platform multimedia player
2 * Copyright (C) 1998-2000 Peter Alm, Mikael Alm, Olle Hallnas, Thomas Nilsson and 4Front Technologies
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18 /* modified for FLAC support by Steven Richman (2003) */
24 #include <sys/types.h>
25 #include <sys/socket.h>
27 #include <netinet/in.h>
28 #include <arpa/inet.h>
40 #include <xmms/util.h>
41 #include <xmms/plugin.h>
43 #include "configure.h"
44 #include "plugin_common/locale_hack.h"
45 #include "FLAC/format.h"
48 /* on FreeBSD we get socklen_t from <sys/socket.h> */
49 #if (!defined HAVE_SOCKLEN_T) && !defined(__FreeBSD__)
50 typedef unsigned int socklen_t;
53 #define min(x,y) ((x)<(y)?(x):(y))
54 #define min3(x,y,z) (min(x,y)<(z)?min(x,y):(z))
55 #define min4(x,y,z,w) (min3(x,y,z)<(w)?min3(x,y,z):(w))
57 static gchar *icy_name = NULL;
58 static gint icy_metaint = 0;
60 extern InputPlugin flac_ip;
64 /* Static udp channel functions */
65 static int udp_establish_listener (gint *sock);
66 static int udp_check_for_data(gint sock);
68 static char *flac_http_get_title(char *url);
70 static gboolean prebuffering, going, eof = FALSE;
71 static gint sock, rd_index, wr_index, buffer_length, prebuffer_length;
72 static guint64 buffer_read = 0;
74 static guint64 offset;
75 static pthread_t thread;
76 static GtkWidget *error_dialog = NULL;
78 static FILE *output_file = NULL;
80 #define BASE64_LENGTH(len) (4 * (((len) + 2) / 3))
82 /* Encode the string S of length LENGTH to base64 format and place it
83 to STORE. STORE will be 0-terminated, and must point to a writable
84 buffer of at least 1+BASE64_LENGTH(length) bytes. */
85 static void base64_encode (const gchar *s, gchar *store, gint length)
87 /* Conversion table. */
88 static gchar tbl[64] = {
89 'A','B','C','D','E','F','G','H',
90 'I','J','K','L','M','N','O','P',
91 'Q','R','S','T','U','V','W','X',
92 'Y','Z','a','b','c','d','e','f',
93 'g','h','i','j','k','l','m','n',
94 'o','p','q','r','s','t','u','v',
95 'w','x','y','z','0','1','2','3',
96 '4','5','6','7','8','9','+','/'
99 guchar *p = (guchar *)store;
101 /* Transform the 3x8 bits to 4x6 bits, as required by base64. */
102 for (i = 0; i < length; i += 3)
104 *p++ = tbl[s[0] >> 2];
105 *p++ = tbl[((s[0] & 3) << 4) + (s[1] >> 4)];
106 *p++ = tbl[((s[1] & 0xf) << 2) + (s[2] >> 6)];
107 *p++ = tbl[s[2] & 0x3f];
110 /* Pad the result if necessary... */
113 else if (i == length + 2)
114 *(p - 1) = *(p - 2) = '=';
115 /* ...and zero-terminate it. */
119 /* Create the authentication header contents for the `Basic' scheme.
120 This is done by encoding the string `USER:PASS' in base64 and
121 prepending `HEADER: Basic ' to it. */
122 static gchar *basic_authentication_encode (const gchar *user, const gchar *passwd, const gchar *header)
124 gchar *t1, *t2, *res;
125 gint len1 = strlen (user) + 1 + strlen (passwd);
126 gint len2 = BASE64_LENGTH (len1);
128 t1 = g_strdup_printf("%s:%s", user, passwd);
129 t2 = g_malloc0(len2 + 1);
130 base64_encode (t1, t2, len1);
131 res = g_strdup_printf("%s: Basic %s\r\n", header, t2);
138 static void parse_url(const gchar * url, gchar ** user, gchar ** pass, gchar ** host, int *port, gchar ** filename)
140 gchar *h, *p, *pt, *f, *temp, *ptr;
142 temp = g_strdup(url);
145 if (!strncasecmp("http://", ptr, 7))
147 h = strchr(ptr, '@');
148 f = strchr(ptr, '/');
149 if (h != NULL && (!f || h < f))
152 p = strchr(ptr, ':');
153 if (p != NULL && p < h)
161 *user = g_strdup(ptr);
171 pt = strchr(ptr, ':');
172 if (pt != NULL && (f == NULL || pt < f))
175 *port = atoi(pt + 1);
186 *filename = g_strdup(f + 1);
192 void flac_http_close(void)
196 pthread_join(thread, NULL);
202 static gint http_used(void)
204 if (wr_index >= rd_index)
205 return wr_index - rd_index;
206 return buffer_length - (rd_index - wr_index);
209 static gint http_free(void)
211 if (rd_index > wr_index)
212 return (rd_index - wr_index) - 1;
213 return (buffer_length - (wr_index - rd_index)) - 1;
216 static void http_wait_for_data(gint bytes)
218 while ((prebuffering || http_used() < bytes) && !eof && going)
222 static void show_error_message(gchar *error)
227 error_dialog = xmms_show_message(_("Error"), error, _("Ok"), FALSE,
229 gtk_signal_connect(GTK_OBJECT(error_dialog),
231 GTK_SIGNAL_FUNC(gtk_widget_destroyed),
237 int flac_http_read(gpointer data, gint length)
239 gint len, cnt, off = 0, meta_len, meta_off = 0, i;
240 gchar *meta_data, **tags, *temp, *title;
241 if (length > buffer_length) {
242 length = buffer_length;
245 http_wait_for_data(length);
249 len = min(http_used(), length);
251 while (len && http_used())
253 if ((flac_cfg.stream.cast_title_streaming) && (icy_metaint > 0) && (buffer_read % icy_metaint) == 0 && (buffer_read > 0))
255 meta_len = *((guchar *) buffer + rd_index) * 16;
256 rd_index = (rd_index + 1) % buffer_length;
259 http_wait_for_data(meta_len);
260 meta_data = g_malloc0(meta_len);
261 if (http_used() >= meta_len)
265 cnt = min(meta_len, buffer_length - rd_index);
266 memcpy(meta_data + meta_off, buffer + rd_index, cnt);
267 rd_index = (rd_index + cnt) % buffer_length;
271 tags = g_strsplit(meta_data, "';", 0);
273 for (i = 0; tags[i]; i++)
275 if (!strncasecmp(tags[i], "StreamTitle=", 12))
277 temp = g_strdup(tags[i] + 13);
278 title = g_strdup_printf("%s (%s)", temp, icy_name);
279 set_track_info(title, -1);
291 http_wait_for_data(length - off);
292 cnt = min3(len, buffer_length - rd_index, http_used());
294 else if ((icy_metaint > 0) && (flac_cfg.stream.cast_title_streaming))
295 cnt = min4(len, buffer_length - rd_index, http_used(), icy_metaint - (gint) (buffer_read % icy_metaint));
297 cnt = min3(len, buffer_length - rd_index, http_used());
299 fwrite(buffer + rd_index, 1, cnt, output_file);
301 memcpy((gchar *)data + off, buffer + rd_index, cnt);
302 rd_index = (rd_index + cnt) % buffer_length;
308 fprintf(stderr, "returning zero\n");
313 static gboolean http_check_for_data(void)
324 ret = select(sock + 1, &set, NULL, NULL, &tv);
330 gint flac_http_read_line(gchar * buf, gint size)
334 while (going && i < size - 1)
336 if (http_check_for_data())
338 if (read(sock, buf + i, 1) <= 0)
352 /* returns the file descriptor of the socket, or -1 on error */
353 static int http_connect (gchar *url_, gboolean head, guint64 offset)
355 gchar line[1024], *user, *pass, *host, *filename,
356 *status, *url, *temp, *file;
358 gint cnt, error, err_len, port, cport;
363 struct sockaddr_in address;
366 url = g_strdup (url_);
374 parse_url(url, &user, &pass, &host, &port, &filename);
376 if ((!filename || !*filename) && url[strlen(url) - 1] != '/')
377 temp = g_strconcat(url, "/", NULL);
379 temp = g_strdup(url);
383 chost = flac_cfg.stream.use_proxy ? flac_cfg.stream.proxy_host : host;
384 cport = flac_cfg.stream.use_proxy ? flac_cfg.stream.proxy_port : port;
386 sock = socket(AF_INET, SOCK_STREAM, 0);
387 fcntl(sock, F_SETFL, O_NONBLOCK);
388 address.sin_family = AF_INET;
390 status = g_strdup_printf(_("LOOKING UP %s"), chost);
391 flac_ip.set_info_text(status);
394 if (!(hp = gethostbyname(chost)))
396 status = g_strdup_printf(_("Couldn't look up host %s"), chost);
397 show_error_message(status);
400 flac_ip.set_info_text(NULL);
406 memcpy(&address.sin_addr.s_addr, *(hp->h_addr_list), sizeof (address.sin_addr.s_addr));
407 address.sin_port = (gint) g_htons(cport);
409 status = g_strdup_printf(_("CONNECTING TO %s:%d"), chost, cport);
410 flac_ip.set_info_text(status);
412 if (connect(sock, (struct sockaddr *) &address, sizeof (struct sockaddr_in)) == -1)
414 if (errno != EINPROGRESS)
416 status = g_strdup_printf(_("Couldn't connect to host %s"), chost);
417 show_error_message(status);
420 flac_ip.set_info_text(NULL);
430 if (select(sock + 1, NULL, &set, NULL, &tv) > 0)
432 err_len = sizeof (error);
433 getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &err_len);
436 status = g_strdup_printf(_("Couldn't connect to host %s"),
438 show_error_message(status);
441 flac_ip.set_info_text(NULL);
450 gchar *auth = NULL, *proxy_auth = NULL;
454 if (flac_cfg.stream.use_udp_channel)
456 udp_port = udp_establish_listener (&udp_sock);
458 sprintf (udpspace, "x-audiocast-udpport: %d\r\n", udp_port);
464 auth = basic_authentication_encode(user, pass, "Authorization");
466 if (flac_cfg.stream.use_proxy)
468 file = g_strdup(url);
469 if(flac_cfg.stream.proxy_use_auth && flac_cfg.stream.proxy_user && flac_cfg.stream.proxy_pass)
471 proxy_auth = basic_authentication_encode(flac_cfg.stream.proxy_user,
472 flac_cfg.stream.proxy_pass,
473 "Proxy-Authorization");
477 file = g_strconcat("/", filename, NULL);
479 temp = g_strdup_printf("GET %s HTTP/1.0\r\n"
481 "User-Agent: %s/%s\r\n"
483 file, host, "Reference FLAC Player", FLAC__VERSION_STRING,
484 proxy_auth ? proxy_auth : "", auth ? auth : "",
485 flac_cfg.stream.cast_title_streaming ? "Icy-MetaData:1\r\n" : "",
486 flac_cfg.stream.use_udp_channel ? udpspace : "");
487 if (offset && !head) {
488 gchar *temp_dead = temp;
489 temp = g_strdup_printf ("%sRange: %llu-\r\n", temp, offset);
490 fprintf (stderr, "%s", temp);
499 write(sock, temp, strlen(temp));
500 write(sock, "\r\n", 2);
502 flac_ip.set_info_text(_("CONNECTED: WAITING FOR REPLY"));
503 while (going && !eof)
505 if (http_check_for_data())
507 if (flac_http_read_line(line, 1024))
509 status = strchr(line, ' ');
512 if (status[1] == '2')
514 else if(status[1] == '3' && status[2] == '0' && status[3] == '2')
518 if(http_check_for_data())
520 if((cnt = flac_http_read_line(line, 1024)) != -1)
524 if(!strncmp(line, "Location:", 9))
527 url = g_strdup(line+10);
533 flac_ip.set_info_text(NULL);
543 status = g_strdup_printf(_("Couldn't connect to host %s\nServer reported: %s"), chost, status);
544 show_error_message(status);
553 flac_ip.set_info_text(NULL);
558 while (going && !redirect)
560 if (http_check_for_data())
562 if ((cnt = flac_http_read_line(line, 1024)) != -1)
566 if (!strncmp(line, "icy-name:", 9))
567 icy_name = g_strdup(line + 9);
568 else if (!strncmp(line, "x-audiocast-name:", 17))
569 icy_name = g_strdup(line + 17);
570 if (!strncmp(line, "icy-metaint:", 12))
571 icy_metaint = atoi(line + 12);
572 if (!strncmp(line, "x-audiocast-udpport:", 20)) {
574 fprintf (stderr, "Server wants udp messages on port %d\n", atoi (line + 20));
576 /*udp_serverport = atoi (line + 20);*/
583 flac_ip.set_info_text(NULL);
608 return eof ? -1 : sock;
611 static void *http_buffer_loop(void *arg)
613 gchar *status, *url, *temp, *file;
618 sock = http_connect (url, false, offset);
620 if (sock >= 0 && flac_cfg.stream.save_http_stream) {
622 file = flac_http_get_title(url);
624 if (!strncasecmp(output_name, "http://", 7))
626 temp = strrchr(output_name, '.');
627 if (temp && (!strcasecmp(temp, ".fla") || !strcasecmp(temp, ".flac")))
630 while ((temp = strchr(output_name, '/')))
632 output_name = g_strdup_printf("%s/%s.flac", flac_cfg.stream.save_http_path, output_name);
636 output_file = fopen(output_name, "wb");
643 if (!http_used() && !flac_ip.output->buffer_playing())
645 if (http_free() > 0 && !eof)
647 if (http_check_for_data())
649 cnt = min(http_free(), buffer_length - wr_index);
652 written = read(sock, buffer + wr_index, cnt);
658 prebuffering = FALSE;
660 flac_ip.set_info_text(NULL);
665 wr_index = (wr_index + written) % buffer_length;
670 if (http_used() > prebuffer_length)
672 prebuffering = FALSE;
673 flac_ip.set_info_text(NULL);
677 status = g_strdup_printf(_("PRE-BUFFERING: %dKB/%dKB"), http_used() / 1024, prebuffer_length / 1024);
678 flac_ip.set_info_text(status);
687 if (flac_cfg.stream.use_udp_channel && udp_sock != 0)
688 if (udp_check_for_data(udp_sock) < 0)
709 return NULL; /* avoid compiler warning */
712 int flac_http_open(gchar * _url, guint64 _offset)
716 url = g_strdup(_url);
720 buffer_length = flac_cfg.stream.http_buffer_size * 1024;
721 prebuffer_length = (buffer_length * flac_cfg.stream.http_prebuffer) / 100;
727 buffer = g_malloc(buffer_length);
730 pthread_create(&thread, NULL, http_buffer_loop, url);
735 char *flac_http_get_title(char *url)
738 return g_strdup(icy_name);
739 if (g_basename(url) && strlen(g_basename(url)) > 0)
740 return g_strdup(g_basename(url));
741 return g_strdup(url);
744 /* Start UDP Channel specific stuff */
746 /* Find a good local udp port and bind udp_sock to it, return the port */
747 static int udp_establish_listener(int *sock)
749 struct sockaddr_in sin;
750 socklen_t sinlen = sizeof (struct sockaddr_in);
753 fprintf (stderr,"Establishing udp listener\n");
756 if ((*sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
758 g_log(NULL, G_LOG_LEVEL_CRITICAL,
759 "udp_establish_listener(): unable to create socket");
763 memset(&sin, 0, sinlen);
764 sin.sin_family = AF_INET;
765 sin.sin_addr.s_addr = g_htonl(INADDR_ANY);
767 if (bind(*sock, (struct sockaddr *)&sin, sinlen) < 0)
769 g_log(NULL, G_LOG_LEVEL_CRITICAL,
770 "udp_establish_listener(): Failed to bind socket to localhost: %s", strerror(errno));
774 if (fcntl(*sock, F_SETFL, O_NONBLOCK) < 0)
776 g_log(NULL, G_LOG_LEVEL_CRITICAL,
777 "udp_establish_listener(): Failed to set flags: %s", strerror(errno));
782 memset(&sin, 0, sinlen);
783 if (getsockname(*sock, (struct sockaddr *)&sin, &sinlen) < 0)
785 g_log(NULL, G_LOG_LEVEL_CRITICAL,
786 "udp_establish_listener(): Failed to retrieve socket info: %s", strerror(errno));
792 fprintf (stderr,"Listening on local %s:%d\n", inet_ntoa(sin.sin_addr), g_ntohs(sin.sin_port));
795 return g_ntohs(sin.sin_port);
798 static int udp_check_for_data(int sock)
800 char buf[1025], **lines;
804 struct sockaddr_in from;
807 fromlen = sizeof(struct sockaddr_in);
809 if ((len = recvfrom(sock, buf, 1024, 0, (struct sockaddr *)&from, &fromlen)) < 0)
813 g_log(NULL, G_LOG_LEVEL_CRITICAL,
814 "udp_read_data(): Error reading from socket: %s", strerror(errno));
821 fprintf (stderr,"Received: [%s]\n", buf);
823 lines = g_strsplit(buf, "\n", 0);
827 for (i = 0; lines[i]; i++)
829 while ((lines[i][strlen(lines[i]) - 1] == '\n') ||
830 (lines[i][strlen(lines[i]) - 1] == '\r'))
831 lines[i][strlen(lines[i]) - 1] = '\0';
833 valptr = strchr(lines[i], ':');
844 if (strstr(lines[i], "x-audiocast-streamtitle") != NULL)
846 title = g_strdup_printf ("%s (%s)", valptr, icy_name);
848 set_track_info(title, -1);
853 else if (strstr(lines[i], "x-audiocast-streamlength") != NULL)
855 if (atoi(valptr) != -1)
856 set_track_info(NULL, atoi(valptr));
860 else if (strstr(lines[i], "x-audiocast-streammsg") != NULL)
862 /* set_track_info(title, -1); */
863 /* xmms_show_message(_("Message"), valptr, _("Ok"), */
864 /* FALSE, NULL, NULL); */
865 g_message("Stream_message: %s", valptr);
869 /* Use this to direct your webbrowser.. yeah right.. */
870 else if (strstr(lines[i], "x-audiocast-streamurl") != NULL)
872 if (lasturl && g_strcmp (valptr, lasturl))
874 c_message (stderr, "Song URL: %s\n", valptr);
876 lasturl = g_strdup (valptr);
880 else if (strstr(lines[i], "x-audiocast-udpseqnr:") != NULL)
883 sprintf(obuf, "x-audiocast-ack: %ld \r\n", atol(valptr));
884 if (sendto(sock, obuf, strlen(obuf), 0, (struct sockaddr *) &from, fromlen) < 0)
886 g_log(NULL, G_LOG_LEVEL_WARNING,
887 "udp_check_for_data(): Unable to send ack to server: %s", strerror(errno));
891 fprintf(stderr,"Sent ack: %s", obuf);
892 fprintf (stderr,"Remote: %s:%d\n", inet_ntoa(from.sin_addr), g_ntohs(from.sin_port));