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 "FLAC/format.h"
44 #include "configure.h"
45 #include "locale_hack.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, port, cport;
364 struct sockaddr_in address;
367 url = g_strdup (url_);
375 parse_url(url, &user, &pass, &host, &port, &filename);
377 if ((!filename || !*filename) && url[strlen(url) - 1] != '/')
378 temp = g_strconcat(url, "/", NULL);
380 temp = g_strdup(url);
384 chost = flac_cfg.stream.use_proxy ? flac_cfg.stream.proxy_host : host;
385 cport = flac_cfg.stream.use_proxy ? flac_cfg.stream.proxy_port : port;
387 sock = socket(AF_INET, SOCK_STREAM, 0);
388 fcntl(sock, F_SETFL, O_NONBLOCK);
389 address.sin_family = AF_INET;
391 status = g_strdup_printf(_("LOOKING UP %s"), chost);
392 flac_ip.set_info_text(status);
395 if (!(hp = gethostbyname(chost)))
397 status = g_strdup_printf(_("Couldn't look up host %s"), chost);
398 show_error_message(status);
401 flac_ip.set_info_text(NULL);
407 memcpy(&address.sin_addr.s_addr, *(hp->h_addr_list), sizeof (address.sin_addr.s_addr));
408 address.sin_port = (gint) g_htons(cport);
410 status = g_strdup_printf(_("CONNECTING TO %s:%d"), chost, cport);
411 flac_ip.set_info_text(status);
413 if (connect(sock, (struct sockaddr *) &address, sizeof (struct sockaddr_in)) == -1)
415 if (errno != EINPROGRESS)
417 status = g_strdup_printf(_("Couldn't connect to host %s"), chost);
418 show_error_message(status);
421 flac_ip.set_info_text(NULL);
431 if (select(sock + 1, NULL, &set, NULL, &tv) > 0)
433 err_len = sizeof (error);
434 getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &err_len);
437 status = g_strdup_printf(_("Couldn't connect to host %s"),
439 show_error_message(status);
442 flac_ip.set_info_text(NULL);
451 gchar *auth = NULL, *proxy_auth = NULL;
455 if (flac_cfg.stream.use_udp_channel)
457 udp_port = udp_establish_listener (&udp_sock);
459 sprintf (udpspace, "x-audiocast-udpport: %d\r\n", udp_port);
465 auth = basic_authentication_encode(user, pass, "Authorization");
467 if (flac_cfg.stream.use_proxy)
469 file = g_strdup(url);
470 if(flac_cfg.stream.proxy_use_auth && flac_cfg.stream.proxy_user && flac_cfg.stream.proxy_pass)
472 proxy_auth = basic_authentication_encode(flac_cfg.stream.proxy_user,
473 flac_cfg.stream.proxy_pass,
474 "Proxy-Authorization");
478 file = g_strconcat("/", filename, NULL);
480 temp = g_strdup_printf("GET %s HTTP/1.0\r\n"
482 "User-Agent: %s/%s\r\n"
484 file, host, "Reference FLAC Player", FLAC__VERSION_STRING,
485 proxy_auth ? proxy_auth : "", auth ? auth : "",
486 flac_cfg.stream.cast_title_streaming ? "Icy-MetaData:1\r\n" : "",
487 flac_cfg.stream.use_udp_channel ? udpspace : "");
488 if (offset && !head) {
489 gchar *temp_dead = temp;
490 temp = g_strdup_printf ("%sRange: %" PRIu64 "-\r\n", temp, offset);
491 fprintf (stderr, "%s", temp);
500 write(sock, temp, strlen(temp));
501 write(sock, "\r\n", 2);
503 flac_ip.set_info_text(_("CONNECTED: WAITING FOR REPLY"));
504 while (going && !eof)
506 if (http_check_for_data())
508 if (flac_http_read_line(line, 1024))
510 status = strchr(line, ' ');
513 if (status[1] == '2')
515 else if(status[1] == '3' && status[2] == '0' && status[3] == '2')
519 if(http_check_for_data())
521 if((cnt = flac_http_read_line(line, 1024)) != -1)
525 if(!strncmp(line, "Location:", 9))
528 url = g_strdup(line+10);
534 flac_ip.set_info_text(NULL);
544 status = g_strdup_printf(_("Couldn't connect to host %s\nServer reported: %s"), chost, status);
545 show_error_message(status);
554 flac_ip.set_info_text(NULL);
559 while (going && !redirect)
561 if (http_check_for_data())
563 if ((cnt = flac_http_read_line(line, 1024)) != -1)
567 if (!strncmp(line, "icy-name:", 9))
568 icy_name = g_strdup(line + 9);
569 else if (!strncmp(line, "x-audiocast-name:", 17))
570 icy_name = g_strdup(line + 17);
571 if (!strncmp(line, "icy-metaint:", 12))
572 icy_metaint = atoi(line + 12);
573 if (!strncmp(line, "x-audiocast-udpport:", 20)) {
575 fprintf (stderr, "Server wants udp messages on port %d\n", atoi (line + 20));
577 /*udp_serverport = atoi (line + 20);*/
584 flac_ip.set_info_text(NULL);
609 return eof ? -1 : sock;
612 static void *http_buffer_loop(void *arg)
614 gchar *status, *url, *temp, *file;
619 sock = http_connect (url, false, offset);
621 if (sock >= 0 && flac_cfg.stream.save_http_stream) {
623 file = flac_http_get_title(url);
625 if (!strncasecmp(output_name, "http://", 7))
627 temp = strrchr(output_name, '.');
628 if (temp && (!strcasecmp(temp, ".fla") || !strcasecmp(temp, ".flac")))
631 while ((temp = strchr(output_name, '/')))
633 output_name = g_strdup_printf("%s/%s.flac", flac_cfg.stream.save_http_path, output_name);
637 output_file = fopen(output_name, "wb");
644 if (!http_used() && !flac_ip.output->buffer_playing())
646 if (http_free() > 0 && !eof)
648 if (http_check_for_data())
650 cnt = min(http_free(), buffer_length - wr_index);
653 written = read(sock, buffer + wr_index, cnt);
659 prebuffering = FALSE;
661 flac_ip.set_info_text(NULL);
666 wr_index = (wr_index + written) % buffer_length;
671 if (http_used() > prebuffer_length)
673 prebuffering = FALSE;
674 flac_ip.set_info_text(NULL);
678 status = g_strdup_printf(_("PRE-BUFFERING: %dKB/%dKB"), http_used() / 1024, prebuffer_length / 1024);
679 flac_ip.set_info_text(status);
688 if (flac_cfg.stream.use_udp_channel && udp_sock != 0)
689 if (udp_check_for_data(udp_sock) < 0)
710 return NULL; /* avoid compiler warning */
713 int flac_http_open(const gchar * _url, guint64 _offset)
717 url = g_strdup(_url);
721 buffer_length = flac_cfg.stream.http_buffer_size * 1024;
722 prebuffer_length = (buffer_length * flac_cfg.stream.http_prebuffer) / 100;
728 buffer = g_malloc(buffer_length);
731 pthread_create(&thread, NULL, http_buffer_loop, url);
736 char *flac_http_get_title(char *url)
739 return g_strdup(icy_name);
740 if (g_basename(url) && strlen(g_basename(url)) > 0)
741 return g_strdup(g_basename(url));
742 return g_strdup(url);
745 /* Start UDP Channel specific stuff */
747 /* Find a good local udp port and bind udp_sock to it, return the port */
748 static int udp_establish_listener(int *sock)
750 struct sockaddr_in sin;
751 socklen_t sinlen = sizeof (struct sockaddr_in);
754 fprintf (stderr,"Establishing udp listener\n");
757 if ((*sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
759 g_log(NULL, G_LOG_LEVEL_CRITICAL,
760 "udp_establish_listener(): unable to create socket");
764 memset(&sin, 0, sinlen);
765 sin.sin_family = AF_INET;
766 sin.sin_addr.s_addr = g_htonl(INADDR_ANY);
768 if (bind(*sock, (struct sockaddr *)&sin, sinlen) < 0)
770 g_log(NULL, G_LOG_LEVEL_CRITICAL,
771 "udp_establish_listener(): Failed to bind socket to localhost: %s", strerror(errno));
775 if (fcntl(*sock, F_SETFL, O_NONBLOCK) < 0)
777 g_log(NULL, G_LOG_LEVEL_CRITICAL,
778 "udp_establish_listener(): Failed to set flags: %s", strerror(errno));
783 memset(&sin, 0, sinlen);
784 if (getsockname(*sock, (struct sockaddr *)&sin, &sinlen) < 0)
786 g_log(NULL, G_LOG_LEVEL_CRITICAL,
787 "udp_establish_listener(): Failed to retrieve socket info: %s", strerror(errno));
793 fprintf (stderr,"Listening on local %s:%d\n", inet_ntoa(sin.sin_addr), g_ntohs(sin.sin_port));
796 return g_ntohs(sin.sin_port);
799 static int udp_check_for_data(int sock)
801 char buf[1025], **lines;
805 struct sockaddr_in from;
808 fromlen = sizeof(struct sockaddr_in);
810 if ((len = recvfrom(sock, buf, 1024, 0, (struct sockaddr *)&from, &fromlen)) < 0)
814 g_log(NULL, G_LOG_LEVEL_CRITICAL,
815 "udp_read_data(): Error reading from socket: %s", strerror(errno));
822 fprintf (stderr,"Received: [%s]\n", buf);
824 lines = g_strsplit(buf, "\n", 0);
828 for (i = 0; lines[i]; i++)
830 while ((lines[i][strlen(lines[i]) - 1] == '\n') ||
831 (lines[i][strlen(lines[i]) - 1] == '\r'))
832 lines[i][strlen(lines[i]) - 1] = '\0';
834 valptr = strchr(lines[i], ':');
845 if (strstr(lines[i], "x-audiocast-streamtitle") != NULL)
847 title = g_strdup_printf ("%s (%s)", valptr, icy_name);
849 set_track_info(title, -1);
854 else if (strstr(lines[i], "x-audiocast-streamlength") != NULL)
856 if (atoi(valptr) != -1)
857 set_track_info(NULL, atoi(valptr));
861 else if (strstr(lines[i], "x-audiocast-streammsg") != NULL)
863 /* set_track_info(title, -1); */
864 /* xmms_show_message(_("Message"), valptr, _("Ok"), */
865 /* FALSE, NULL, NULL); */
866 g_message("Stream_message: %s", valptr);
870 /* Use this to direct your webbrowser.. yeah right.. */
871 else if (strstr(lines[i], "x-audiocast-streamurl") != NULL)
873 if (lasturl && g_strcmp (valptr, lasturl))
875 c_message (stderr, "Song URL: %s\n", valptr);
877 lasturl = g_strdup (valptr);
881 else if (strstr(lines[i], "x-audiocast-udpseqnr:") != NULL)
884 sprintf(obuf, "x-audiocast-ack: %ld \r\n", atol(valptr));
885 if (sendto(sock, obuf, strlen(obuf), 0, (struct sockaddr *) &from, fromlen) < 0)
887 g_log(NULL, G_LOG_LEVEL_WARNING,
888 "udp_check_for_data(): Unable to send ack to server: %s", strerror(errno));
892 fprintf(stderr,"Sent ack: %s", obuf);
893 fprintf (stderr,"Remote: %s:%d\n", inet_ntoa(from.sin_addr), g_ntohs(from.sin_port));