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