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) */
19 #include <sys/types.h>
20 #include <sys/socket.h>
22 #include <netinet/in.h>
23 #include <arpa/inet.h>
35 #include <xmms/util.h>
36 #include <xmms/plugin.h>
42 #include "configure.h"
43 #include "plugin_common/locale_hack.h"
44 #include "FLAC/format.h"
47 #ifndef HAVE_SOCKLEN_T
48 typedef unsigned int socklen_t;
51 #define min(x,y) ((x)<(y)?(x):(y))
52 #define min3(x,y,z) (min(x,y)<(z)?min(x,y):(z))
53 #define min4(x,y,z,w) (min3(x,y,z)<(w)?min3(x,y,z):(w))
55 static gchar *icy_name = NULL;
56 static gint icy_metaint = 0;
58 extern InputPlugin flac_ip;
62 /* Static udp channel functions */
63 static int udp_establish_listener (gint *sock);
64 static int udp_check_for_data(gint sock);
66 static char *flac_http_get_title(char *url);
68 static gboolean prebuffering, going, eof = FALSE;
69 static gint sock, rd_index, wr_index, buffer_length, prebuffer_length;
70 static guint64 buffer_read = 0;
72 static guint64 offset;
73 static pthread_t thread;
74 static GtkWidget *error_dialog = NULL;
76 static FILE *output_file = NULL;
78 #define BASE64_LENGTH(len) (4 * (((len) + 2) / 3))
80 /* Encode the string S of length LENGTH to base64 format and place it
81 to STORE. STORE will be 0-terminated, and must point to a writable
82 buffer of at least 1+BASE64_LENGTH(length) bytes. */
83 static void base64_encode (const gchar *s, gchar *store, gint length)
85 /* Conversion table. */
86 static gchar tbl[64] = {
87 'A','B','C','D','E','F','G','H',
88 'I','J','K','L','M','N','O','P',
89 'Q','R','S','T','U','V','W','X',
90 'Y','Z','a','b','c','d','e','f',
91 'g','h','i','j','k','l','m','n',
92 'o','p','q','r','s','t','u','v',
93 'w','x','y','z','0','1','2','3',
94 '4','5','6','7','8','9','+','/'
97 guchar *p = (guchar *)store;
99 /* Transform the 3x8 bits to 4x6 bits, as required by base64. */
100 for (i = 0; i < length; i += 3)
102 *p++ = tbl[s[0] >> 2];
103 *p++ = tbl[((s[0] & 3) << 4) + (s[1] >> 4)];
104 *p++ = tbl[((s[1] & 0xf) << 2) + (s[2] >> 6)];
105 *p++ = tbl[s[2] & 0x3f];
108 /* Pad the result if necessary... */
111 else if (i == length + 2)
112 *(p - 1) = *(p - 2) = '=';
113 /* ...and zero-terminate it. */
117 /* Create the authentication header contents for the `Basic' scheme.
118 This is done by encoding the string `USER:PASS' in base64 and
119 prepending `HEADER: Basic ' to it. */
120 static gchar *basic_authentication_encode (const gchar *user, const gchar *passwd, const gchar *header)
122 gchar *t1, *t2, *res;
123 gint len1 = strlen (user) + 1 + strlen (passwd);
124 gint len2 = BASE64_LENGTH (len1);
126 t1 = g_strdup_printf("%s:%s", user, passwd);
127 t2 = g_malloc0(len2 + 1);
128 base64_encode (t1, t2, len1);
129 res = g_strdup_printf("%s: Basic %s\r\n", header, t2);
136 static void parse_url(const gchar * url, gchar ** user, gchar ** pass, gchar ** host, int *port, gchar ** filename)
138 gchar *h, *p, *pt, *f, *temp, *ptr;
140 temp = g_strdup(url);
143 if (!strncasecmp("http://", ptr, 7))
145 h = strchr(ptr, '@');
146 f = strchr(ptr, '/');
147 if (h != NULL && (!f || h < f))
150 p = strchr(ptr, ':');
151 if (p != NULL && p < h)
159 *user = g_strdup(ptr);
169 pt = strchr(ptr, ':');
170 if (pt != NULL && (f == NULL || pt < f))
173 *port = atoi(pt + 1);
184 *filename = g_strdup(f + 1);
190 void flac_http_close(void)
194 pthread_join(thread, NULL);
200 static gint http_used(void)
202 if (wr_index >= rd_index)
203 return wr_index - rd_index;
204 return buffer_length - (rd_index - wr_index);
207 static gint http_free(void)
209 if (rd_index > wr_index)
210 return (rd_index - wr_index) - 1;
211 return (buffer_length - (wr_index - rd_index)) - 1;
214 static void http_wait_for_data(gint bytes)
216 while ((prebuffering || http_used() < bytes) && !eof && going)
220 static void show_error_message(gchar *error)
225 error_dialog = xmms_show_message(_("Error"), error, _("Ok"), FALSE,
227 gtk_signal_connect(GTK_OBJECT(error_dialog),
229 GTK_SIGNAL_FUNC(gtk_widget_destroyed),
235 int flac_http_read(gpointer data, gint length)
237 gint len, cnt, off = 0, meta_len, meta_off = 0, i;
238 gchar *meta_data, **tags, *temp, *title;
239 if (length > buffer_length) {
240 length = buffer_length;
243 http_wait_for_data(length);
247 len = min(http_used(), length);
249 while (len && http_used())
251 if ((flac_cfg.stream.cast_title_streaming) && (icy_metaint > 0) && (buffer_read % icy_metaint) == 0 && (buffer_read > 0))
253 meta_len = *((guchar *) buffer + rd_index) * 16;
254 rd_index = (rd_index + 1) % buffer_length;
257 http_wait_for_data(meta_len);
258 meta_data = g_malloc0(meta_len);
259 if (http_used() >= meta_len)
263 cnt = min(meta_len, buffer_length - rd_index);
264 memcpy(meta_data + meta_off, buffer + rd_index, cnt);
265 rd_index = (rd_index + cnt) % buffer_length;
269 tags = g_strsplit(meta_data, "';", 0);
271 for (i = 0; tags[i]; i++)
273 if (!strncasecmp(tags[i], "StreamTitle=", 12))
275 temp = g_strdup(tags[i] + 13);
276 title = g_strdup_printf("%s (%s)", temp, icy_name);
277 set_track_info(title, -1);
289 http_wait_for_data(length - off);
290 cnt = min3(len, buffer_length - rd_index, http_used());
292 else if ((icy_metaint > 0) && (flac_cfg.stream.cast_title_streaming))
293 cnt = min4(len, buffer_length - rd_index, http_used(), icy_metaint - (gint) (buffer_read % icy_metaint));
295 cnt = min3(len, buffer_length - rd_index, http_used());
297 fwrite(buffer + rd_index, 1, cnt, output_file);
299 memcpy((gchar *)data + off, buffer + rd_index, cnt);
300 rd_index = (rd_index + cnt) % buffer_length;
306 fprintf(stderr, "returning zero\n");
311 static gboolean http_check_for_data(void)
322 ret = select(sock + 1, &set, NULL, NULL, &tv);
328 gint flac_http_read_line(gchar * buf, gint size)
332 while (going && i < size - 1)
334 if (http_check_for_data())
336 if (read(sock, buf + i, 1) <= 0)
350 /* returns the file descriptor of the socket, or -1 on error */
351 static int http_connect (gchar *url_, gboolean head, guint64 offset)
353 gchar line[1024], *user, *pass, *host, *filename,
354 *status, *url, *temp, *file;
356 gint cnt, error, err_len, port, cport;
361 struct sockaddr_in address;
364 url = g_strdup (url_);
372 parse_url(url, &user, &pass, &host, &port, &filename);
374 if ((!filename || !*filename) && url[strlen(url) - 1] != '/')
375 temp = g_strconcat(url, "/", NULL);
377 temp = g_strdup(url);
381 chost = flac_cfg.stream.use_proxy ? flac_cfg.stream.proxy_host : host;
382 cport = flac_cfg.stream.use_proxy ? flac_cfg.stream.proxy_port : port;
384 sock = socket(AF_INET, SOCK_STREAM, 0);
385 fcntl(sock, F_SETFL, O_NONBLOCK);
386 address.sin_family = AF_INET;
388 status = g_strdup_printf(_("LOOKING UP %s"), chost);
389 flac_ip.set_info_text(status);
392 if (!(hp = gethostbyname(chost)))
394 status = g_strdup_printf(_("Couldn't look up host %s"), chost);
395 show_error_message(status);
398 flac_ip.set_info_text(NULL);
404 memcpy(&address.sin_addr.s_addr, *(hp->h_addr_list), sizeof (address.sin_addr.s_addr));
405 address.sin_port = (gint) g_htons(cport);
407 status = g_strdup_printf(_("CONNECTING TO %s:%d"), chost, cport);
408 flac_ip.set_info_text(status);
410 if (connect(sock, (struct sockaddr *) &address, sizeof (struct sockaddr_in)) == -1)
412 if (errno != EINPROGRESS)
414 status = g_strdup_printf(_("Couldn't connect to host %s"), chost);
415 show_error_message(status);
418 flac_ip.set_info_text(NULL);
428 if (select(sock + 1, NULL, &set, NULL, &tv) > 0)
430 err_len = sizeof (error);
431 getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &err_len);
434 status = g_strdup_printf(_("Couldn't connect to host %s"),
436 show_error_message(status);
439 flac_ip.set_info_text(NULL);
448 gchar *auth = NULL, *proxy_auth = NULL;
452 if (flac_cfg.stream.use_udp_channel)
454 udp_port = udp_establish_listener (&udp_sock);
456 sprintf (udpspace, "x-audiocast-udpport: %d\r\n", udp_port);
462 auth = basic_authentication_encode(user, pass, "Authorization");
464 if (flac_cfg.stream.use_proxy)
466 file = g_strdup(url);
467 if(flac_cfg.stream.proxy_use_auth && flac_cfg.stream.proxy_user && flac_cfg.stream.proxy_pass)
469 proxy_auth = basic_authentication_encode(flac_cfg.stream.proxy_user,
470 flac_cfg.stream.proxy_pass,
471 "Proxy-Authorization");
475 file = g_strconcat("/", filename, NULL);
477 temp = g_strdup_printf("GET %s HTTP/1.0\r\n"
479 "User-Agent: %s/%s\r\n"
481 file, host, "Reference FLAC Player", FLAC__VERSION_STRING,
482 proxy_auth ? proxy_auth : "", auth ? auth : "",
483 flac_cfg.stream.cast_title_streaming ? "Icy-MetaData:1\r\n" : "",
484 flac_cfg.stream.use_udp_channel ? udpspace : "");
485 if (offset && !head) {
486 gchar *temp_dead = temp;
487 temp = g_strdup_printf ("%sRange: %llu-\r\n", temp, offset);
488 fprintf (stderr, "%s", temp);
497 write(sock, temp, strlen(temp));
498 write(sock, "\r\n", 2);
500 flac_ip.set_info_text(_("CONNECTED: WAITING FOR REPLY"));
501 while (going && !eof)
503 if (http_check_for_data())
505 if (flac_http_read_line(line, 1024))
507 status = strchr(line, ' ');
510 if (status[1] == '2')
512 else if(status[1] == '3' && status[2] == '0' && status[3] == '2')
516 if(http_check_for_data())
518 if((cnt = flac_http_read_line(line, 1024)) != -1)
522 if(!strncmp(line, "Location:", 9))
525 url = g_strdup(line+10);
531 flac_ip.set_info_text(NULL);
541 status = g_strdup_printf(_("Couldn't connect to host %s\nServer reported: %s"), chost, status);
542 show_error_message(status);
551 flac_ip.set_info_text(NULL);
556 while (going && !redirect)
558 if (http_check_for_data())
560 if ((cnt = flac_http_read_line(line, 1024)) != -1)
564 if (!strncmp(line, "icy-name:", 9))
565 icy_name = g_strdup(line + 9);
566 else if (!strncmp(line, "x-audiocast-name:", 17))
567 icy_name = g_strdup(line + 17);
568 if (!strncmp(line, "icy-metaint:", 12))
569 icy_metaint = atoi(line + 12);
570 if (!strncmp(line, "x-audiocast-udpport:", 20)) {
572 fprintf (stderr, "Server wants udp messages on port %d\n", atoi (line + 20));
574 /*udp_serverport = atoi (line + 20);*/
581 flac_ip.set_info_text(NULL);
606 return eof ? -1 : sock;
609 static void *http_buffer_loop(void *arg)
611 gchar *status, *url, *temp, *file;
616 sock = http_connect (url, false, offset);
618 if (sock >= 0 && flac_cfg.stream.save_http_stream) {
620 file = flac_http_get_title(url);
622 if (!strncasecmp(output_name, "http://", 7))
624 temp = strrchr(output_name, '.');
625 if (temp && (!strcasecmp(temp, ".fla") || !strcasecmp(temp, ".flac")))
628 while ((temp = strchr(output_name, '/')))
630 output_name = g_strdup_printf("%s/%s.flac", flac_cfg.stream.save_http_path, output_name);
634 output_file = fopen(output_name, "wb");
641 if (!http_used() && !flac_ip.output->buffer_playing())
643 if (http_free() > 0 && !eof)
645 if (http_check_for_data())
647 cnt = min(http_free(), buffer_length - wr_index);
650 written = read(sock, buffer + wr_index, cnt);
656 prebuffering = FALSE;
658 flac_ip.set_info_text(NULL);
663 wr_index = (wr_index + written) % buffer_length;
668 if (http_used() > prebuffer_length)
670 prebuffering = FALSE;
671 flac_ip.set_info_text(NULL);
675 status = g_strdup_printf(_("PRE-BUFFERING: %dKB/%dKB"), http_used() / 1024, prebuffer_length / 1024);
676 flac_ip.set_info_text(status);
685 if (flac_cfg.stream.use_udp_channel && udp_sock != 0)
686 if (udp_check_for_data(udp_sock) < 0)
707 return NULL; /* avoid compiler warning */
710 int flac_http_open(gchar * _url, guint64 _offset)
714 url = g_strdup(_url);
718 buffer_length = flac_cfg.stream.http_buffer_size * 1024;
719 prebuffer_length = (buffer_length * flac_cfg.stream.http_prebuffer) / 100;
725 buffer = g_malloc(buffer_length);
728 pthread_create(&thread, NULL, http_buffer_loop, url);
733 char *flac_http_get_title(char *url)
736 return g_strdup(icy_name);
737 if (g_basename(url) && strlen(g_basename(url)) > 0)
738 return g_strdup(g_basename(url));
739 return g_strdup(url);
742 /* Start UDP Channel specific stuff */
744 /* Find a good local udp port and bind udp_sock to it, return the port */
745 static int udp_establish_listener(int *sock)
747 struct sockaddr_in sin;
748 socklen_t sinlen = sizeof (struct sockaddr_in);
751 fprintf (stderr,"Establishing udp listener\n");
754 if ((*sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
756 g_log(NULL, G_LOG_LEVEL_CRITICAL,
757 "udp_establish_listener(): unable to create socket");
761 memset(&sin, 0, sinlen);
762 sin.sin_family = AF_INET;
763 sin.sin_addr.s_addr = g_htonl(INADDR_ANY);
765 if (bind(*sock, (struct sockaddr *)&sin, sinlen) < 0)
767 g_log(NULL, G_LOG_LEVEL_CRITICAL,
768 "udp_establish_listener(): Failed to bind socket to localhost: %s", strerror(errno));
772 if (fcntl(*sock, F_SETFL, O_NONBLOCK) < 0)
774 g_log(NULL, G_LOG_LEVEL_CRITICAL,
775 "udp_establish_listener(): Failed to set flags: %s", strerror(errno));
780 memset(&sin, 0, sinlen);
781 if (getsockname(*sock, (struct sockaddr *)&sin, &sinlen) < 0)
783 g_log(NULL, G_LOG_LEVEL_CRITICAL,
784 "udp_establish_listener(): Failed to retrieve socket info: %s", strerror(errno));
790 fprintf (stderr,"Listening on local %s:%d\n", inet_ntoa(sin.sin_addr), g_ntohs(sin.sin_port));
793 return g_ntohs(sin.sin_port);
796 static int udp_check_for_data(int sock)
798 char buf[1025], **lines;
802 struct sockaddr_in from;
805 fromlen = sizeof(struct sockaddr_in);
807 if ((len = recvfrom(sock, buf, 1024, 0, (struct sockaddr *)&from, &fromlen)) < 0)
811 g_log(NULL, G_LOG_LEVEL_CRITICAL,
812 "udp_read_data(): Error reading from socket: %s", strerror(errno));
819 fprintf (stderr,"Received: [%s]\n", buf);
821 lines = g_strsplit(buf, "\n", 0);
825 for (i = 0; lines[i]; i++)
827 while ((lines[i][strlen(lines[i]) - 1] == '\n') ||
828 (lines[i][strlen(lines[i]) - 1] == '\r'))
829 lines[i][strlen(lines[i]) - 1] = '\0';
831 valptr = strchr(lines[i], ':');
842 if (strstr(lines[i], "x-audiocast-streamtitle") != NULL)
844 title = g_strdup_printf ("%s (%s)", valptr, icy_name);
846 set_track_info(title, -1);
851 else if (strstr(lines[i], "x-audiocast-streamlength") != NULL)
853 if (atoi(valptr) != -1)
854 set_track_info(NULL, atoi(valptr));
858 else if (strstr(lines[i], "x-audiocast-streammsg") != NULL)
860 /* set_track_info(title, -1); */
861 /* xmms_show_message(_("Message"), valptr, _("Ok"), */
862 /* FALSE, NULL, NULL); */
863 g_message("Stream_message: %s", valptr);
867 /* Use this to direct your webbrowser.. yeah right.. */
868 else if (strstr(lines[i], "x-audiocast-streamurl") != NULL)
870 if (lasturl && g_strcmp (valptr, lasturl))
872 c_message (stderr, "Song URL: %s\n", valptr);
874 lasturl = g_strdup (valptr);
878 else if (strstr(lines[i], "x-audiocast-udpseqnr:") != NULL)
881 sprintf(obuf, "x-audiocast-ack: %ld \r\n", atol(valptr));
882 if (sendto(sock, obuf, strlen(obuf), 0, (struct sockaddr *) &from, fromlen) < 0)
884 g_log(NULL, G_LOG_LEVEL_WARNING,
885 "udp_check_for_data(): Unable to send ack to server: %s", strerror(errno));
889 fprintf(stderr,"Sent ack: %s", obuf);
890 fprintf (stderr,"Remote: %s:%d\n", inet_ntoa(from.sin_addr), g_ntohs(from.sin_port));