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