complete largefile support
[platform/upstream/flac.git] / src / plugin_xmms / http.c
1 /*  XMMS - Cross-platform multimedia player
2  *  Copyright (C) 1998-2000  Peter Alm, Mikael Alm, Olle Hallnas, Thomas Nilsson and 4Front Technologies
3  *
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.
8  *
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.
13  *
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.
17  */
18 /* modified for FLAC support by Steven Richman (2003) */
19
20 #if HAVE_CONFIG_H
21 #  include <config.h>
22 #endif
23
24 #include <sys/types.h>
25 #include <sys/socket.h>
26 #include <sys/time.h>
27 #include <netinet/in.h>
28 #include <arpa/inet.h>
29 #include <netdb.h>
30 #include <glib.h>
31 #include <string.h>
32 #include <fcntl.h>
33 #include <unistd.h>
34 #include <errno.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37
38 #include <pthread.h>
39
40 #include <xmms/util.h>
41 #include <xmms/plugin.h>
42
43 #include "configure.h"
44 #include "plugin_common/locale_hack.h"
45 #include "FLAC/format.h"
46 #include "plugin.h"
47
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;
51 #endif
52
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))
56
57 static gchar *icy_name = NULL;
58 static gint icy_metaint = 0;
59
60 extern InputPlugin flac_ip;
61
62 #undef DEBUG_UDP
63
64 /* Static udp channel functions */
65 static int udp_establish_listener (gint *sock);
66 static int udp_check_for_data(gint sock);
67
68 static char *flac_http_get_title(char *url);
69
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;
73 static gchar *buffer;
74 static guint64 offset;
75 static pthread_t thread;
76 static GtkWidget *error_dialog = NULL;
77
78 static FILE *output_file = NULL;
79
80 #define BASE64_LENGTH(len) (4 * (((len) + 2) / 3))
81
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)
86 {
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','+','/'
97         };
98         gint i;
99         guchar *p = (guchar *)store;
100
101         /* Transform the 3x8 bits to 4x6 bits, as required by base64.  */
102         for (i = 0; i < length; i += 3)
103         {
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];
108                 s += 3;
109         }
110         /* Pad the result if necessary...  */
111         if (i == length + 1)
112                 *(p - 1) = '=';
113         else if (i == length + 2)
114                 *(p - 1) = *(p - 2) = '=';
115         /* ...and zero-terminate it.  */
116         *p = '\0';
117 }
118
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)
123 {
124         gchar *t1, *t2, *res;
125         gint len1 = strlen (user) + 1 + strlen (passwd);
126         gint len2 = BASE64_LENGTH (len1);
127
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);
132         g_free(t2);
133         g_free(t1);
134         
135         return res;
136 }
137
138 static void parse_url(const gchar * url, gchar ** user, gchar ** pass, gchar ** host, int *port, gchar ** filename)
139 {
140         gchar *h, *p, *pt, *f, *temp, *ptr;
141
142         temp = g_strdup(url);
143         ptr = temp;
144
145         if (!strncasecmp("http://", ptr, 7))
146                 ptr += 7;
147         h = strchr(ptr, '@');
148         f = strchr(ptr, '/');
149         if (h != NULL && (!f || h < f))
150         {
151                 *h = '\0';
152                 p = strchr(ptr, ':');
153                 if (p != NULL && p < h)
154                 {
155                         *p = '\0';
156                         p++;
157                         *pass = g_strdup(p);
158                 }
159                 else
160                         *pass = NULL;
161                 *user = g_strdup(ptr);
162                 h++;
163                 ptr = h;
164         }
165         else
166         {
167                 *user = NULL;
168                 *pass = NULL;
169                 h = ptr;
170         }
171         pt = strchr(ptr, ':');
172         if (pt != NULL && (f == NULL || pt < f))
173         {
174                 *pt = '\0';
175                 *port = atoi(pt + 1);
176         }
177         else
178         {
179                 if (f)
180                         *f = '\0';
181                 *port = 80;
182         }
183         *host = g_strdup(h);
184         
185         if (f)
186                 *filename = g_strdup(f + 1);
187         else
188                 *filename = NULL;
189         g_free(temp);
190 }
191
192 void flac_http_close(void)
193 {
194         going = FALSE;
195
196         pthread_join(thread, NULL);
197         g_free(icy_name);
198         icy_name = NULL;
199 }
200
201
202 static gint http_used(void)
203 {
204         if (wr_index >= rd_index)
205                 return wr_index - rd_index;
206         return buffer_length - (rd_index - wr_index);
207 }
208
209 static gint http_free(void)
210 {
211         if (rd_index > wr_index)
212                 return (rd_index - wr_index) - 1;
213         return (buffer_length - (wr_index - rd_index)) - 1;
214 }
215
216 static void http_wait_for_data(gint bytes)
217 {
218         while ((prebuffering || http_used() < bytes) && !eof && going)
219                 xmms_usleep(10000);
220 }
221
222 static void show_error_message(gchar *error)
223 {
224         if(!error_dialog)
225         {
226                 GDK_THREADS_ENTER();
227                 error_dialog = xmms_show_message(_("Error"), error, _("Ok"), FALSE,
228                                                  NULL, NULL);
229                 gtk_signal_connect(GTK_OBJECT(error_dialog),
230                                    "destroy",
231                                    GTK_SIGNAL_FUNC(gtk_widget_destroyed),
232                                    &error_dialog);
233                 GDK_THREADS_LEAVE();
234         }
235 }
236
237 int flac_http_read(gpointer data, gint length)
238 {
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;
243         }
244
245         http_wait_for_data(length);
246
247         if (!going)
248                 return 0;
249         len = min(http_used(), length);
250
251         while (len && http_used())
252         {
253                 if ((flac_cfg.stream.cast_title_streaming) && (icy_metaint > 0) && (buffer_read % icy_metaint) == 0 && (buffer_read > 0))
254                 {
255                         meta_len = *((guchar *) buffer + rd_index) * 16;
256                         rd_index = (rd_index + 1) % buffer_length;
257                         if (meta_len > 0)
258                         {
259                                 http_wait_for_data(meta_len);
260                                 meta_data = g_malloc0(meta_len);
261                                 if (http_used() >= meta_len)
262                                 {
263                                         while (meta_len)
264                                         {
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;
268                                                 meta_len -= cnt;
269                                                 meta_off += cnt;
270                                         }
271                                         tags = g_strsplit(meta_data, "';", 0);
272
273                                         for (i = 0; tags[i]; i++)
274                                         {
275                                                 if (!strncasecmp(tags[i], "StreamTitle=", 12))
276                                                 {
277                                                         temp = g_strdup(tags[i] + 13);
278                                                         title = g_strdup_printf("%s (%s)", temp, icy_name);
279                                                         set_track_info(title, -1);
280                                                         g_free(title);
281                                                         g_free(temp);
282                                                 }
283
284                                         }
285                                         g_strfreev(tags);
286
287                                 }
288                                 g_free(meta_data);
289                         }
290                         if (!http_used())
291                                 http_wait_for_data(length - off);
292                         cnt = min3(len, buffer_length - rd_index, http_used());
293                 }
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));
296                 else
297                         cnt = min3(len, buffer_length - rd_index, http_used());
298                 if (output_file)
299                         fwrite(buffer + rd_index, 1, cnt, output_file);
300
301                 memcpy((gchar *)data + off, buffer + rd_index, cnt);
302                 rd_index = (rd_index + cnt) % buffer_length;
303                 buffer_read += cnt;
304                 len -= cnt;
305                 off += cnt;
306         }
307         if (!off) {
308                 fprintf(stderr, "returning zero\n");
309         }
310         return off;
311 }
312
313 static gboolean http_check_for_data(void)
314 {
315
316         fd_set set;
317         struct timeval tv;
318         gint ret;
319
320         tv.tv_sec = 0;
321         tv.tv_usec = 20000;
322         FD_ZERO(&set);
323         FD_SET(sock, &set);
324         ret = select(sock + 1, &set, NULL, NULL, &tv);
325         if (ret > 0)
326                 return TRUE;
327         return FALSE;
328 }
329
330 gint flac_http_read_line(gchar * buf, gint size)
331 {
332         gint i = 0;
333
334         while (going && i < size - 1)
335         {
336                 if (http_check_for_data())
337                 {
338                         if (read(sock, buf + i, 1) <= 0)
339                                 return -1;
340                         if (buf[i] == '\n')
341                                 break;
342                         if (buf[i] != '\r')
343                                 i++;
344                 }
345         }
346         if (!going)
347                 return -1;
348         buf[i] = '\0';
349         return i;
350 }
351
352 /* returns the file descriptor of the socket, or -1 on error */
353 static int http_connect (gchar *url_, gboolean head, guint64 offset)
354 {
355         gchar line[1024], *user, *pass, *host, *filename,
356              *status, *url, *temp, *file;
357         gchar *chost;
358         gint cnt, error, err_len, port, cport;
359         gboolean redirect;
360         int udp_sock = 0;
361         fd_set set;
362         struct hostent *hp;
363         struct sockaddr_in address;
364         struct timeval tv;
365
366         url = g_strdup (url_);
367
368         do
369         {
370                 redirect=FALSE;
371         
372                 g_strstrip(url);
373
374                 parse_url(url, &user, &pass, &host, &port, &filename);
375
376                 if ((!filename || !*filename) && url[strlen(url) - 1] != '/')
377                         temp = g_strconcat(url, "/", NULL);
378                 else
379                         temp = g_strdup(url);
380                 g_free(url);
381                 url = temp;
382
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;
385
386                 sock = socket(AF_INET, SOCK_STREAM, 0);
387                 fcntl(sock, F_SETFL, O_NONBLOCK);
388                 address.sin_family = AF_INET;
389
390                 status = g_strdup_printf(_("LOOKING UP %s"), chost);
391                 flac_ip.set_info_text(status);
392                 g_free(status);
393
394                 if (!(hp = gethostbyname(chost)))
395                 {
396                         status = g_strdup_printf(_("Couldn't look up host %s"), chost);
397                         show_error_message(status);
398                         g_free(status);
399
400                         flac_ip.set_info_text(NULL);
401                         eof = TRUE;
402                 }
403
404                 if (!eof)
405                 {
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);
408
409                         status = g_strdup_printf(_("CONNECTING TO %s:%d"), chost, cport);
410                         flac_ip.set_info_text(status);
411                         g_free(status);
412                         if (connect(sock, (struct sockaddr *) &address, sizeof (struct sockaddr_in)) == -1)
413                         {
414                                 if (errno != EINPROGRESS)
415                                 {
416                                         status = g_strdup_printf(_("Couldn't connect to host %s"), chost);
417                                         show_error_message(status);
418                                         g_free(status);
419
420                                         flac_ip.set_info_text(NULL);
421                                         eof = TRUE;
422                                 }
423                         }
424                         while (going)
425                         {
426                                 tv.tv_sec = 0;
427                                 tv.tv_usec = 10000;
428                                 FD_ZERO(&set);
429                                 FD_SET(sock, &set);
430                                 if (select(sock + 1, NULL, &set, NULL, &tv) > 0)
431                                 {
432                                         err_len = sizeof (error);
433                                         getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &err_len);
434                                         if (error)
435                                         {
436                                                 status = g_strdup_printf(_("Couldn't connect to host %s"),
437                                                                          chost);
438                                                 show_error_message(status);
439                                                 g_free(status);
440
441                                                 flac_ip.set_info_text(NULL);
442                                                 eof = TRUE;
443                                                 
444                                         }
445                                         break;
446                                 }
447                         }
448                         if (!eof)
449                         {
450                                 gchar *auth = NULL, *proxy_auth = NULL;
451                                 gchar udpspace[30];
452                                 int udp_port;
453
454                                 if (flac_cfg.stream.use_udp_channel)
455                                 {
456                                         udp_port = udp_establish_listener (&udp_sock);
457                                         if (udp_port > 0) 
458                                                 sprintf (udpspace, "x-audiocast-udpport: %d\r\n", udp_port);
459                                         else
460                                                 udp_sock = 0;
461                                 }
462                                         
463                                 if(user && pass)
464                                         auth = basic_authentication_encode(user, pass, "Authorization");
465
466                                 if (flac_cfg.stream.use_proxy)
467                                 {
468                                         file = g_strdup(url);
469                                         if(flac_cfg.stream.proxy_use_auth && flac_cfg.stream.proxy_user && flac_cfg.stream.proxy_pass)
470                                         {
471                                                 proxy_auth = basic_authentication_encode(flac_cfg.stream.proxy_user,
472                                                                                          flac_cfg.stream.proxy_pass,
473                                                                                          "Proxy-Authorization");
474                                         }
475                                 }
476                                 else
477                                         file = g_strconcat("/", filename, NULL);
478
479                                 temp = g_strdup_printf("GET %s HTTP/1.0\r\n"
480                                                        "Host: %s\r\n"
481                                                        "User-Agent: %s/%s\r\n"
482                                                        "%s%s%s%s",
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);
491                                         g_free (temp_dead);
492                                 }
493                                 
494                                 g_free(file);
495                                 if(proxy_auth)
496                                         g_free(proxy_auth);
497                                 if(auth)
498                                         g_free(auth);
499                                 write(sock, temp, strlen(temp));
500                                 write(sock, "\r\n", 2);
501                                 g_free(temp);
502                                 flac_ip.set_info_text(_("CONNECTED: WAITING FOR REPLY"));
503                                 while (going && !eof)
504                                   {
505                                         if (http_check_for_data())
506                                         {
507                                                 if (flac_http_read_line(line, 1024))
508                                                 {
509                                                         status = strchr(line, ' ');
510                                                         if (status)
511                                                         {
512                                                                 if (status[1] == '2')
513                                                                         break;
514                                                                 else if(status[1] == '3' && status[2] == '0' && status[3] == '2')
515                                                                 {
516                                                                         while(going)
517                                                                         {
518                                                                                 if(http_check_for_data())
519                                                                                 {
520                                                                                         if((cnt = flac_http_read_line(line, 1024)) != -1)
521                                                                                         {
522                                                                                                 if(!cnt)
523                                                                                                         break;
524                                                                                                 if(!strncmp(line, "Location:", 9))
525                                                                                                 {
526                                                                                                         g_free(url);
527                                                                                                         url = g_strdup(line+10);
528                                                                                                 }
529                                                                                         }
530                                                                                         else
531                                                                                         {
532                                                                                                 eof=TRUE;
533                                                                                                 flac_ip.set_info_text(NULL);
534                                                                                                 break;
535                                                                                         }
536                                                                                 }
537                                                                         }                       
538                                                                         redirect=TRUE;
539                                                                         break;
540                                                                 }
541                                                                 else
542                                                                 {
543                                                                         status = g_strdup_printf(_("Couldn't connect to host %s\nServer reported: %s"), chost, status);
544                                                                         show_error_message(status);
545                                                                         g_free(status);
546                                                                         break;
547                                                                 }
548                                                         }
549                                                 }
550                                                 else
551                                                 {
552                                                         eof = TRUE;
553                                                         flac_ip.set_info_text(NULL);
554                                                 }
555                                         }
556                                 }
557
558                                 while (going && !redirect)
559                                 {
560                                         if (http_check_for_data())
561                                         {
562                                                 if ((cnt = flac_http_read_line(line, 1024)) != -1)
563                                                 {
564                                                         if (!cnt)
565                                                                 break;
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)) {
573 #ifdef DEBUG_UDP
574                                                                 fprintf (stderr, "Server wants udp messages on port %d\n", atoi (line + 20));
575 #endif
576                                                                 /*udp_serverport = atoi (line + 20);*/
577                                                         }
578                                                         
579                                                 }
580                                                 else
581                                                 {
582                                                         eof = TRUE;
583                                                         flac_ip.set_info_text(NULL);
584                                                         break;
585                                                 }
586                                         }
587                                 }
588                         }
589                 }
590         
591                 if(redirect)
592                 {
593                         if (output_file)
594                         {
595                                 fclose(output_file);
596                                 output_file = NULL;
597                         }
598                         close(sock);
599                 }
600
601                 g_free(user);
602                 g_free(pass);
603                 g_free(host);
604                 g_free(filename);
605         } while(redirect);
606
607         g_free(url);
608         return eof ? -1 : sock;
609 }
610
611 static void *http_buffer_loop(void *arg)
612 {
613         gchar *status, *url, *temp, *file;
614         gint cnt, written;
615         int udp_sock = 0;
616
617         url = (gchar *) arg;
618         sock = http_connect (url, false, offset);
619         
620         if (sock >= 0 && flac_cfg.stream.save_http_stream) {
621                 gchar *output_name;
622                 file = flac_http_get_title(url);
623                 output_name = file;
624                 if (!strncasecmp(output_name, "http://", 7))
625                         output_name += 7;
626                 temp = strrchr(output_name, '.');
627                 if (temp && (!strcasecmp(temp, ".fla") || !strcasecmp(temp, ".flac")))
628                         *temp = '\0';
629
630                 while ((temp = strchr(output_name, '/')))
631                         *temp = '_';
632                 output_name = g_strdup_printf("%s/%s.flac", flac_cfg.stream.save_http_path, output_name);
633
634                 g_free(file);
635
636                 output_file = fopen(output_name, "wb");
637                 g_free(output_name);
638         }
639
640         while (going)
641         {
642
643                 if (!http_used() && !flac_ip.output->buffer_playing())
644                         prebuffering = TRUE;
645                 if (http_free() > 0 && !eof)
646                 {
647                         if (http_check_for_data())
648                         {
649                                 cnt = min(http_free(), buffer_length - wr_index);
650                                 if (cnt > 1024)
651                                         cnt = 1024;
652                                 written = read(sock, buffer + wr_index, cnt);
653                                 if (written <= 0)
654                                 {
655                                         eof = TRUE;
656                                         if (prebuffering)
657                                         {
658                                                 prebuffering = FALSE;
659
660                                                 flac_ip.set_info_text(NULL);
661                                         }
662
663                                 }
664                                 else
665                                         wr_index = (wr_index + written) % buffer_length;
666                         }
667
668                         if (prebuffering)
669                         {
670                                 if (http_used() > prebuffer_length)
671                                 {
672                                         prebuffering = FALSE;
673                                         flac_ip.set_info_text(NULL);
674                                 }
675                                 else
676                                 {
677                                         status = g_strdup_printf(_("PRE-BUFFERING: %dKB/%dKB"), http_used() / 1024, prebuffer_length / 1024);
678                                         flac_ip.set_info_text(status);
679                                         g_free(status);
680                                 }
681
682                         }
683                 }
684                 else
685                         xmms_usleep(10000);
686
687                 if (flac_cfg.stream.use_udp_channel && udp_sock != 0)
688                         if (udp_check_for_data(udp_sock) < 0)
689                         {
690                                 close(udp_sock);
691                                 udp_sock = 0;
692                         }
693         }
694         if (output_file)
695         {
696                 fclose(output_file);
697                 output_file = NULL;
698         }
699         if (sock >= 0) {
700                 close(sock);
701         }
702         if (udp_sock != 0)
703                 close(udp_sock);
704
705         g_free(buffer);
706         g_free(url);
707         
708         pthread_exit(NULL);
709         return NULL; /* avoid compiler warning */
710 }
711
712 int flac_http_open(gchar * _url, guint64 _offset)
713 {
714         gchar *url;
715
716         url = g_strdup(_url);
717
718         rd_index = 0;
719         wr_index = 0;
720         buffer_length = flac_cfg.stream.http_buffer_size * 1024;
721         prebuffer_length = (buffer_length * flac_cfg.stream.http_prebuffer) / 100;
722         buffer_read = 0;
723         icy_metaint = 0;
724         prebuffering = TRUE;
725         going = TRUE;
726         eof = FALSE;
727         buffer = g_malloc(buffer_length);
728         offset = _offset;
729
730         pthread_create(&thread, NULL, http_buffer_loop, url);
731
732         return 0;
733 }
734
735 char *flac_http_get_title(char *url)
736 {
737         if (icy_name)
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);
742 }
743
744 /* Start UDP Channel specific stuff */
745
746 /* Find a good local udp port and bind udp_sock to it, return the port */
747 static int udp_establish_listener(int *sock)
748 {
749         struct sockaddr_in sin;
750         socklen_t sinlen = sizeof (struct sockaddr_in);
751         
752 #ifdef DEBUG_UDP
753         fprintf (stderr,"Establishing udp listener\n");
754 #endif
755         
756         if ((*sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
757         {
758                 g_log(NULL, G_LOG_LEVEL_CRITICAL,
759                       "udp_establish_listener(): unable to create socket");
760                 return -1;
761         }
762
763         memset(&sin, 0, sinlen);
764         sin.sin_family = AF_INET;
765         sin.sin_addr.s_addr = g_htonl(INADDR_ANY);
766                         
767         if (bind(*sock, (struct sockaddr *)&sin, sinlen) < 0)
768         {
769                 g_log(NULL, G_LOG_LEVEL_CRITICAL,
770                       "udp_establish_listener():  Failed to bind socket to localhost: %s", strerror(errno));
771                 close(*sock);
772                 return -1;
773         }
774         if (fcntl(*sock, F_SETFL, O_NONBLOCK) < 0)
775         {
776                 g_log(NULL, G_LOG_LEVEL_CRITICAL,
777                       "udp_establish_listener():  Failed to set flags: %s", strerror(errno));
778                 close(*sock);
779                 return -1;
780         }
781
782         memset(&sin, 0, sinlen);
783         if (getsockname(*sock, (struct sockaddr *)&sin, &sinlen) < 0)
784         {
785                 g_log(NULL, G_LOG_LEVEL_CRITICAL,
786                       "udp_establish_listener():  Failed to retrieve socket info: %s", strerror(errno));
787                 close(*sock);
788                 return -1;
789         }
790
791 #ifdef DEBUG_UDP
792         fprintf (stderr,"Listening on local %s:%d\n", inet_ntoa(sin.sin_addr), g_ntohs(sin.sin_port));
793 #endif
794         
795         return g_ntohs(sin.sin_port);
796 }
797
798 static int udp_check_for_data(int sock)
799 {
800         char buf[1025], **lines;
801         char *valptr;
802         gchar *title;
803         gint len, i;
804         struct sockaddr_in from;
805         socklen_t fromlen;
806
807         fromlen = sizeof(struct sockaddr_in);
808         
809         if ((len = recvfrom(sock, buf, 1024, 0, (struct sockaddr *)&from, &fromlen)) < 0)
810         {
811                 if (errno != EAGAIN)
812                 {
813                         g_log(NULL, G_LOG_LEVEL_CRITICAL,
814                               "udp_read_data(): Error reading from socket: %s", strerror(errno));
815                         return -1;
816                 }
817                 return 0;
818         }
819         buf[len] = '\0';
820 #ifdef DEBUG_UDP
821         fprintf (stderr,"Received: [%s]\n", buf);
822 #endif
823         lines = g_strsplit(buf, "\n", 0);
824         if (!lines)
825                 return 0;
826         
827         for (i = 0; lines[i]; i++)
828         {
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';
832                 
833                 valptr = strchr(lines[i], ':');
834                 
835                 if (!valptr)
836                         continue;
837                 else
838                         valptr++;
839                 
840                 g_strstrip(valptr);
841                 if (!strlen(valptr))
842                         continue;
843                 
844                 if (strstr(lines[i], "x-audiocast-streamtitle") != NULL)
845                 {
846                         title = g_strdup_printf ("%s (%s)", valptr, icy_name);
847                         if (going)
848                                 set_track_info(title, -1);
849                         g_free (title);
850                 }
851
852 #if 0
853                 else if (strstr(lines[i], "x-audiocast-streamlength") != NULL)
854                 {
855                         if (atoi(valptr) != -1)
856                                 set_track_info(NULL, atoi(valptr));
857                 }
858 #endif
859                                 
860                 else if (strstr(lines[i], "x-audiocast-streammsg") != NULL)
861                 {
862                         /* set_track_info(title, -1); */
863 /*                      xmms_show_message(_("Message"), valptr, _("Ok"), */
864 /*                                        FALSE, NULL, NULL); */
865                         g_message("Stream_message: %s", valptr);
866                 }
867
868 #if 0
869                 /* Use this to direct your webbrowser.. yeah right.. */
870                 else if (strstr(lines[i], "x-audiocast-streamurl") != NULL)
871                 {
872                         if (lasturl && g_strcmp (valptr, lasturl))
873                         {
874                                 c_message (stderr, "Song URL: %s\n", valptr);
875                                 g_free (lasturl);
876                                 lasturl = g_strdup (valptr);
877                         }
878                 }
879 #endif
880                 else if (strstr(lines[i], "x-audiocast-udpseqnr:") != NULL)
881                 {
882                         gchar obuf[60];
883                         sprintf(obuf, "x-audiocast-ack: %ld \r\n", atol(valptr));
884                         if (sendto(sock, obuf, strlen(obuf), 0, (struct sockaddr *) &from, fromlen) < 0)
885                         {
886                                 g_log(NULL, G_LOG_LEVEL_WARNING,
887                                       "udp_check_for_data(): Unable to send ack to server: %s", strerror(errno));
888                         }
889 #ifdef DEBUG_UDP
890                         else
891                                 fprintf(stderr,"Sent ack: %s", obuf);
892                         fprintf (stderr,"Remote: %s:%d\n", inet_ntoa(from.sin_addr), g_ntohs(from.sin_port));
893 #endif
894                 }
895         }
896         g_strfreev(lines);
897         return 0;
898 }