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