a0bf63118d27fcf6dc596af07146b3c8d681d335
[platform/upstream/gstreamer.git] / ext / neon / gstneonhttpsrc.c
1 /* GStreamer
2  * Copyright (C) <2005> Edgard Lima <edgard.lima@gmail.com>
3  * Copyright (C) <2006> Rosfran Borges <rosfran.borges@indt.org.br>
4  * Copyright (C) <2006> Andre Moreira Magalhaes <andre.magalhaes@indt.org.br>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more 
15  */
16
17 #ifdef HAVE_CONFIG_H
18 #include "config.h"
19 #endif
20
21 #include "gstneonhttpsrc.h"
22 #include <stdlib.h>
23 #include <string.h>
24 #ifdef _HAVE_UNISTD_H
25 #include <unistd.h>
26 #endif /* _HAVE_UNISTD_H */
27
28 #include <ne_redirect.h>
29
30 #define STATUS_IS_REDIRECTION(status)     ((status) >= 300 && (status) < 400)
31
32 GST_DEBUG_CATEGORY_STATIC (neonhttpsrc_debug);
33 #define GST_CAT_DEFAULT neonhttpsrc_debug
34
35 #define MAX_READ_SIZE (4 * 1024)
36
37 /* max number of HTTP redirects, when iterating over a sequence of HTTP 3xx status code */
38 #define MAX_HTTP_REDIRECTS_NUMBER 5
39
40 static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src",
41     GST_PAD_SRC,
42     GST_PAD_ALWAYS,
43     GST_STATIC_CAPS_ANY);
44
45 #define HTTP_SOCKET_ERROR        -2
46 #define HTTP_REQUEST_WRONG_PROXY -1
47 #define HTTP_DEFAULT_PORT        80
48 #define HTTPS_DEFAULT_PORT       443
49 #define HTTP_DEFAULT_HOST        "localhost"
50
51 /* default properties */
52 #define DEFAULT_LOCATION             "http://" HTTP_DEFAULT_HOST ":" G_STRINGIFY(HTTP_DEFAULT_PORT)
53 #define DEFAULT_PROXY                ""
54 #define DEFAULT_USER_AGENT           "GStreamer neonhttpsrc"
55 #define DEFAULT_AUTOMATIC_REDIRECT   TRUE
56 #define DEFAULT_ACCEPT_SELF_SIGNED   FALSE
57 #define DEFAULT_NEON_HTTP_DEBUG      FALSE
58 #define DEFAULT_CONNECT_TIMEOUT      0
59 #define DEFAULT_READ_TIMEOUT         0
60 #define DEFAULT_IRADIO_MODE          TRUE
61
62 enum
63 {
64   PROP_0,
65   PROP_LOCATION,
66   PROP_PROXY,
67   PROP_USER_AGENT,
68   PROP_COOKIES,
69   PROP_AUTOMATIC_REDIRECT,
70   PROP_ACCEPT_SELF_SIGNED,
71   PROP_CONNECT_TIMEOUT,
72   PROP_READ_TIMEOUT,
73 #ifndef GST_DISABLE_GST_DEBUG
74   PROP_NEON_HTTP_DEBUG,
75 #endif
76   PROP_IRADIO_MODE
77 };
78
79 static void gst_neonhttp_src_uri_handler_init (gpointer g_iface,
80     gpointer iface_data);
81 static void gst_neonhttp_src_dispose (GObject * gobject);
82 static void gst_neonhttp_src_set_property (GObject * object, guint prop_id,
83     const GValue * value, GParamSpec * pspec);
84 static void gst_neonhttp_src_get_property (GObject * object, guint prop_id,
85     GValue * value, GParamSpec * pspec);
86
87 static GstFlowReturn gst_neonhttp_src_fill (GstPushSrc * psrc,
88     GstBuffer * outbuf);
89 static gboolean gst_neonhttp_src_start (GstBaseSrc * bsrc);
90 static gboolean gst_neonhttp_src_stop (GstBaseSrc * bsrc);
91 static gboolean gst_neonhttp_src_get_size (GstBaseSrc * bsrc, guint64 * size);
92 static gboolean gst_neonhttp_src_is_seekable (GstBaseSrc * bsrc);
93 static gboolean gst_neonhttp_src_do_seek (GstBaseSrc * bsrc,
94     GstSegment * segment);
95 static gboolean gst_neonhttp_src_query (GstBaseSrc * bsrc, GstQuery * query);
96
97 static gboolean gst_neonhttp_src_set_proxy (GstNeonhttpSrc * src,
98     const gchar * uri);
99 static gboolean gst_neonhttp_src_set_location (GstNeonhttpSrc * src,
100     const gchar * uri, GError ** err);
101 static gint gst_neonhttp_src_send_request_and_redirect (GstNeonhttpSrc * src,
102     ne_session ** ses, ne_request ** req, gint64 offset, gboolean do_redir);
103 static gint gst_neonhttp_src_request_dispatch (GstNeonhttpSrc * src,
104     GstBuffer * outbuf);
105 static void gst_neonhttp_src_close_session (GstNeonhttpSrc * src);
106 static gchar *gst_neonhttp_src_unicodify (const gchar * str);
107 static void oom_callback (void);
108
109 #define parent_class gst_neonhttp_src_parent_class
110 G_DEFINE_TYPE_WITH_CODE (GstNeonhttpSrc, gst_neonhttp_src, GST_TYPE_PUSH_SRC,
111     G_IMPLEMENT_INTERFACE (GST_TYPE_URI_HANDLER,
112         gst_neonhttp_src_uri_handler_init));
113
114 static void
115 gst_neonhttp_src_class_init (GstNeonhttpSrcClass * klass)
116 {
117   GObjectClass *gobject_class;
118   GstElementClass *element_class;
119   GstBaseSrcClass *gstbasesrc_class;
120   GstPushSrcClass *gstpushsrc_class;
121
122   gobject_class = (GObjectClass *) klass;
123   element_class = (GstElementClass *) klass;
124   gstbasesrc_class = (GstBaseSrcClass *) klass;
125   gstpushsrc_class = (GstPushSrcClass *) klass;
126
127   gobject_class->set_property = gst_neonhttp_src_set_property;
128   gobject_class->get_property = gst_neonhttp_src_get_property;
129   gobject_class->dispose = gst_neonhttp_src_dispose;
130
131   g_object_class_install_property
132       (gobject_class, PROP_LOCATION,
133       g_param_spec_string ("location", "Location",
134           "Location to read from", "",
135           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
136
137   g_object_class_install_property
138       (gobject_class, PROP_PROXY,
139       g_param_spec_string ("proxy", "Proxy",
140           "Proxy server to use, in the form HOSTNAME:PORT. "
141           "Defaults to the http_proxy environment variable",
142           "", G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
143
144   g_object_class_install_property
145       (gobject_class, PROP_USER_AGENT,
146       g_param_spec_string ("user-agent", "User-Agent",
147           "Value of the User-Agent HTTP request header field",
148           "GStreamer neonhttpsrc", G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
149
150   g_object_class_install_property (gobject_class, PROP_COOKIES,
151       g_param_spec_boxed ("cookies", "Cookies", "HTTP request cookies",
152           G_TYPE_STRV, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
153
154   g_object_class_install_property
155       (gobject_class, PROP_AUTOMATIC_REDIRECT,
156       g_param_spec_boolean ("automatic-redirect", "automatic-redirect",
157           "Automatically follow HTTP redirects (HTTP Status Code 3xx)",
158           TRUE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
159
160   g_object_class_install_property
161       (gobject_class, PROP_ACCEPT_SELF_SIGNED,
162       g_param_spec_boolean ("accept-self-signed", "accept-self-signed",
163           "Accept self-signed SSL/TLS certificates",
164           DEFAULT_ACCEPT_SELF_SIGNED,
165           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
166
167   g_object_class_install_property (gobject_class, PROP_CONNECT_TIMEOUT,
168       g_param_spec_uint ("connect-timeout", "connect-timeout",
169           "Value in seconds to timeout a blocking connection (0 = default).", 0,
170           3600, DEFAULT_CONNECT_TIMEOUT,
171           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
172
173   g_object_class_install_property (gobject_class, PROP_READ_TIMEOUT,
174       g_param_spec_uint ("read-timeout", "read-timeout",
175           "Value in seconds to timeout a blocking read (0 = default).", 0,
176           3600, DEFAULT_READ_TIMEOUT,
177           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
178
179 #ifndef GST_DISABLE_GST_DEBUG
180   g_object_class_install_property
181       (gobject_class, PROP_NEON_HTTP_DEBUG,
182       g_param_spec_boolean ("neon-http-debug", "neon-http-debug",
183           "Enable Neon HTTP debug messages",
184           DEFAULT_NEON_HTTP_DEBUG, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
185 #endif
186
187   g_object_class_install_property (gobject_class, PROP_IRADIO_MODE,
188       g_param_spec_boolean ("iradio-mode", "iradio-mode",
189           "Enable internet radio mode (ask server to send shoutcast/icecast "
190           "metadata interleaved with the actual stream data)",
191           DEFAULT_IRADIO_MODE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
192
193   gstbasesrc_class->start = GST_DEBUG_FUNCPTR (gst_neonhttp_src_start);
194   gstbasesrc_class->stop = GST_DEBUG_FUNCPTR (gst_neonhttp_src_stop);
195   gstbasesrc_class->get_size = GST_DEBUG_FUNCPTR (gst_neonhttp_src_get_size);
196   gstbasesrc_class->is_seekable =
197       GST_DEBUG_FUNCPTR (gst_neonhttp_src_is_seekable);
198   gstbasesrc_class->do_seek = GST_DEBUG_FUNCPTR (gst_neonhttp_src_do_seek);
199   gstbasesrc_class->query = GST_DEBUG_FUNCPTR (gst_neonhttp_src_query);
200
201   gstpushsrc_class->fill = GST_DEBUG_FUNCPTR (gst_neonhttp_src_fill);
202
203   GST_DEBUG_CATEGORY_INIT (neonhttpsrc_debug, "neonhttpsrc", 0,
204       "NEON HTTP Client Source");
205
206   gst_element_class_add_static_pad_template (element_class, &srctemplate);
207
208   gst_element_class_set_static_metadata (element_class, "HTTP client source",
209       "Source/Network",
210       "Receive data as a client over the network via HTTP using NEON",
211       "Edgard Lima <edgard.lima@gmail.com>, "
212       "Rosfran Borges <rosfran.borges@indt.org.br>, "
213       "Andre Moreira Magalhaes <andre.magalhaes@indt.org.br>");
214 }
215
216 static void
217 gst_neonhttp_src_init (GstNeonhttpSrc * src)
218 {
219   const gchar *str;
220
221   src->neon_http_debug = DEFAULT_NEON_HTTP_DEBUG;
222   src->user_agent = g_strdup (DEFAULT_USER_AGENT);
223   src->automatic_redirect = DEFAULT_AUTOMATIC_REDIRECT;
224   src->accept_self_signed = DEFAULT_ACCEPT_SELF_SIGNED;
225   src->connect_timeout = DEFAULT_CONNECT_TIMEOUT;
226   src->read_timeout = DEFAULT_READ_TIMEOUT;
227   src->iradio_mode = DEFAULT_IRADIO_MODE;
228
229   src->cookies = NULL;
230   src->session = NULL;
231   src->request = NULL;
232   memset (&src->uri, 0, sizeof (src->uri));
233   memset (&src->proxy, 0, sizeof (src->proxy));
234   src->content_size = -1;
235   src->seekable = TRUE;
236
237   gst_neonhttp_src_set_location (src, DEFAULT_LOCATION, NULL);
238
239   /* configure proxy */
240   str = g_getenv ("http_proxy");
241   if (str && !gst_neonhttp_src_set_proxy (src, str)) {
242     GST_WARNING_OBJECT (src,
243         "The proxy set on http_proxy env var ('%s') cannot be parsed.", str);
244   }
245 }
246
247 static void
248 gst_neonhttp_src_dispose (GObject * gobject)
249 {
250   GstNeonhttpSrc *src = GST_NEONHTTP_SRC (gobject);
251
252   ne_uri_free (&src->uri);
253   ne_uri_free (&src->proxy);
254
255   g_free (src->user_agent);
256
257   if (src->cookies) {
258     g_strfreev (src->cookies);
259     src->cookies = NULL;
260   }
261
262   if (src->request) {
263     ne_request_destroy (src->request);
264     src->request = NULL;
265   }
266
267   if (src->session) {
268     ne_close_connection (src->session);
269     ne_session_destroy (src->session);
270     src->session = NULL;
271   }
272
273   if (src->location) {
274     ne_free (src->location);
275   }
276   if (src->query_string) {
277     ne_free (src->query_string);
278   }
279
280   G_OBJECT_CLASS (parent_class)->dispose (gobject);
281 }
282
283 static void
284 gst_neonhttp_src_set_property (GObject * object, guint prop_id,
285     const GValue * value, GParamSpec * pspec)
286 {
287   GstNeonhttpSrc *src = GST_NEONHTTP_SRC (object);
288
289   switch (prop_id) {
290     case PROP_PROXY:
291     {
292       const gchar *proxy;
293
294       proxy = g_value_get_string (value);
295
296       if (proxy == NULL) {
297         GST_WARNING ("proxy property cannot be NULL");
298         goto done;
299       }
300       if (!gst_neonhttp_src_set_proxy (src, proxy)) {
301         GST_WARNING ("badly formated proxy");
302         goto done;
303       }
304       break;
305     }
306     case PROP_LOCATION:
307     {
308       const gchar *location;
309
310       location = g_value_get_string (value);
311
312       if (location == NULL) {
313         GST_WARNING ("location property cannot be NULL");
314         goto done;
315       }
316       if (!gst_neonhttp_src_set_location (src, location, NULL)) {
317         GST_WARNING ("badly formated location");
318         goto done;
319       }
320       break;
321     }
322     case PROP_USER_AGENT:
323       g_free (src->user_agent);
324       src->user_agent = g_strdup (g_value_get_string (value));
325       break;
326     case PROP_COOKIES:
327       if (src->cookies)
328         g_strfreev (src->cookies);
329       src->cookies = (gchar **) g_value_dup_boxed (value);
330       break;
331     case PROP_AUTOMATIC_REDIRECT:
332       src->automatic_redirect = g_value_get_boolean (value);
333       break;
334     case PROP_ACCEPT_SELF_SIGNED:
335       src->accept_self_signed = g_value_get_boolean (value);
336       break;
337     case PROP_CONNECT_TIMEOUT:
338       src->connect_timeout = g_value_get_uint (value);
339       break;
340     case PROP_READ_TIMEOUT:
341       src->read_timeout = g_value_get_uint (value);
342       break;
343 #ifndef GST_DISABLE_GST_DEBUG
344     case PROP_NEON_HTTP_DEBUG:
345       src->neon_http_debug = g_value_get_boolean (value);
346       break;
347 #endif
348     case PROP_IRADIO_MODE:
349       src->iradio_mode = g_value_get_boolean (value);
350       break;
351     default:
352       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
353       break;
354   }
355 done:
356   return;
357 }
358
359 static void
360 gst_neonhttp_src_get_property (GObject * object, guint prop_id,
361     GValue * value, GParamSpec * pspec)
362 {
363   GstNeonhttpSrc *neonhttpsrc = GST_NEONHTTP_SRC (object);
364
365   switch (prop_id) {
366     case PROP_PROXY:
367     {
368       gchar *str;
369
370       if (neonhttpsrc->proxy.host) {
371         str = ne_uri_unparse (&neonhttpsrc->proxy);
372         if (!str)
373           break;
374         g_value_set_string (value, str);
375         ne_free (str);
376       } else {
377         g_value_set_static_string (value, "");
378       }
379       break;
380     }
381     case PROP_LOCATION:
382     {
383       gchar *str;
384
385       if (neonhttpsrc->uri.host) {
386         str = ne_uri_unparse (&neonhttpsrc->uri);
387         if (!str)
388           break;
389         g_value_set_string (value, str);
390         ne_free (str);
391       } else {
392         g_value_set_static_string (value, "");
393       }
394       break;
395     }
396     case PROP_USER_AGENT:
397       g_value_set_string (value, neonhttpsrc->user_agent);
398       break;
399     case PROP_COOKIES:
400       g_value_set_boxed (value, neonhttpsrc->cookies);
401       break;
402     case PROP_AUTOMATIC_REDIRECT:
403       g_value_set_boolean (value, neonhttpsrc->automatic_redirect);
404       break;
405     case PROP_ACCEPT_SELF_SIGNED:
406       g_value_set_boolean (value, neonhttpsrc->accept_self_signed);
407       break;
408     case PROP_CONNECT_TIMEOUT:
409       g_value_set_uint (value, neonhttpsrc->connect_timeout);
410       break;
411     case PROP_READ_TIMEOUT:
412       g_value_set_uint (value, neonhttpsrc->read_timeout);
413       break;
414 #ifndef GST_DISABLE_GST_DEBUG
415     case PROP_NEON_HTTP_DEBUG:
416       g_value_set_boolean (value, neonhttpsrc->neon_http_debug);
417       break;
418 #endif
419     case PROP_IRADIO_MODE:
420       g_value_set_boolean (value, neonhttpsrc->iradio_mode);
421       break;
422     default:
423       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
424       break;
425   }
426 }
427
428 /* NEON CALLBACK */
429 static void
430 oom_callback (void)
431 {
432   GST_ERROR ("memory exeception in neon");
433 }
434
435 static GstFlowReturn
436 gst_neonhttp_src_fill (GstPushSrc * psrc, GstBuffer * outbuf)
437 {
438   GstNeonhttpSrc *src;
439   gint read;
440
441   src = GST_NEONHTTP_SRC (psrc);
442
443   /* The caller should know the number of bytes and not read beyond EOS. */
444   if (G_UNLIKELY (src->eos))
445     goto eos;
446
447   read = gst_neonhttp_src_request_dispatch (src, outbuf);
448   if (G_UNLIKELY (read < 0))
449     goto read_error;
450
451   GST_LOG_OBJECT (src, "returning %" G_GSIZE_FORMAT " bytes, "
452       "offset %" G_GUINT64_FORMAT, gst_buffer_get_size (outbuf),
453       GST_BUFFER_OFFSET (outbuf));
454
455   return GST_FLOW_OK;
456
457   /* ERRORS */
458 eos:
459   {
460     GST_DEBUG_OBJECT (src, "EOS reached");
461     return GST_FLOW_EOS;
462   }
463 read_error:
464   {
465     GST_ELEMENT_ERROR (src, RESOURCE, READ,
466         (NULL), ("Could not read any bytes (%i, %s)", read,
467             ne_get_error (src->session)));
468     return GST_FLOW_ERROR;
469   }
470 }
471
472 /* create a socket for connecting to remote server */
473 static gboolean
474 gst_neonhttp_src_start (GstBaseSrc * bsrc)
475 {
476   GstNeonhttpSrc *src = GST_NEONHTTP_SRC (bsrc);
477   const gchar *content_length;
478   gint res;
479
480 #ifndef GST_DISABLE_GST_DEBUG
481   if (src->neon_http_debug)
482     ne_debug_init (stderr, NE_DBG_HTTP);
483 #endif
484
485   ne_oom_callback (oom_callback);
486
487   res = ne_sock_init ();
488   if (res != 0)
489     goto init_failed;
490
491   res = gst_neonhttp_src_send_request_and_redirect (src,
492       &src->session, &src->request, 0, src->automatic_redirect);
493
494   if (res != NE_OK || !src->session) {
495     if (res == HTTP_SOCKET_ERROR) {
496       goto socket_error;
497     } else if (res == HTTP_REQUEST_WRONG_PROXY) {
498       goto wrong_proxy;
499     } else {
500       goto begin_req_failed;
501     }
502   }
503
504   content_length = ne_get_response_header (src->request, "Content-Length");
505
506   if (content_length)
507     src->content_size = g_ascii_strtoull (content_length, NULL, 10);
508   else
509     src->content_size = -1;
510
511   if (TRUE) {
512     /* Icecast stuff */
513     const gchar *str_value;
514     GstTagList *tags;
515     gchar *iradio_name;
516     gchar *iradio_url;
517     gchar *iradio_genre;
518     gint icy_metaint;
519
520     tags = gst_tag_list_new_empty ();
521
522     str_value = ne_get_response_header (src->request, "icy-metaint");
523     if (str_value) {
524       if (sscanf (str_value, "%d", &icy_metaint) == 1) {
525         GstCaps *icy_caps;
526
527         icy_caps = gst_caps_new_simple ("application/x-icy",
528             "metadata-interval", G_TYPE_INT, icy_metaint, NULL);
529         gst_base_src_set_caps (GST_BASE_SRC (src), icy_caps);
530       }
531     }
532
533     /* FIXME: send tags with name, genre, url */
534     str_value = ne_get_response_header (src->request, "icy-name");
535     if (str_value) {
536       iradio_name = gst_neonhttp_src_unicodify (str_value);
537       if (iradio_name) {
538         gst_tag_list_add (tags, GST_TAG_MERGE_REPLACE, GST_TAG_ORGANIZATION,
539             iradio_name, NULL);
540         g_free (iradio_name);
541       }
542     }
543     str_value = ne_get_response_header (src->request, "icy-genre");
544     if (str_value) {
545       iradio_genre = gst_neonhttp_src_unicodify (str_value);
546       if (iradio_genre) {
547         gst_tag_list_add (tags, GST_TAG_MERGE_REPLACE, GST_TAG_GENRE,
548             iradio_genre, NULL);
549         g_free (iradio_genre);
550       }
551     }
552     str_value = ne_get_response_header (src->request, "icy-url");
553     if (str_value) {
554       iradio_url = gst_neonhttp_src_unicodify (str_value);
555       if (iradio_url) {
556         gst_tag_list_add (tags, GST_TAG_MERGE_REPLACE, GST_TAG_LOCATION,
557             iradio_url, NULL);
558         g_free (iradio_url);
559       }
560     }
561     if (!gst_tag_list_is_empty (tags)) {
562       GST_DEBUG_OBJECT (src, "pushing tag list %" GST_PTR_FORMAT, tags);
563       gst_pad_push_event (GST_BASE_SRC_PAD (src), gst_event_new_tag (tags));
564     } else {
565       gst_tag_list_unref (tags);
566     }
567   }
568
569   return TRUE;
570
571   /* ERRORS */
572 init_failed:
573   {
574     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
575         ("ne_sock_init() failed: %d", res));
576     return FALSE;
577   }
578 socket_error:
579   {
580     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
581         ("HTTP Request failed when opening socket: %d", res));
582     return FALSE;
583   }
584 wrong_proxy:
585   {
586     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
587         ("Proxy Server URI is invalid - make sure that either both proxy host "
588             "and port are specified or neither."));
589     return FALSE;
590   }
591 begin_req_failed:
592   {
593     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
594         ("Could not begin request: %d", res));
595     return FALSE;
596   }
597 }
598
599 /* close the socket and associated resources
600  * used both to recover from errors and go to NULL state */
601 static gboolean
602 gst_neonhttp_src_stop (GstBaseSrc * bsrc)
603 {
604   GstNeonhttpSrc *src;
605
606   src = GST_NEONHTTP_SRC (bsrc);
607
608   src->eos = FALSE;
609   src->content_size = -1;
610   src->read_position = 0;
611   src->seekable = TRUE;
612
613   gst_neonhttp_src_close_session (src);
614
615 #ifndef GST_DISABLE_GST_DEBUG
616   ne_debug_init (NULL, 0);
617 #endif
618   ne_oom_callback (NULL);
619   ne_sock_exit ();
620
621   return TRUE;
622 }
623
624 static gboolean
625 gst_neonhttp_src_get_size (GstBaseSrc * bsrc, guint64 * size)
626 {
627   GstNeonhttpSrc *src;
628
629   src = GST_NEONHTTP_SRC (bsrc);
630
631   if (src->content_size == -1)
632     return FALSE;
633
634   *size = src->content_size;
635
636   return TRUE;
637 }
638
639 static gboolean
640 gst_neonhttp_src_is_seekable (GstBaseSrc * bsrc)
641 {
642   return TRUE;
643 }
644
645 static gboolean
646 gst_neonhttp_src_do_seek (GstBaseSrc * bsrc, GstSegment * segment)
647 {
648   GstNeonhttpSrc *src;
649   gint res;
650   ne_session *session = NULL;
651   ne_request *request = NULL;
652
653   src = GST_NEONHTTP_SRC (bsrc);
654
655   if (!src->seekable)
656     return FALSE;
657
658   if (src->read_position == segment->start)
659     return TRUE;
660
661   res = gst_neonhttp_src_send_request_and_redirect (src,
662       &session, &request, segment->start, src->automatic_redirect);
663
664   /* if we are able to seek, replace the session */
665   if (res == NE_OK && session) {
666     gst_neonhttp_src_close_session (src);
667     src->session = session;
668     src->request = request;
669     src->read_position = segment->start;
670     return TRUE;
671   }
672
673   return FALSE;
674 }
675
676 static gboolean
677 gst_neonhttp_src_query (GstBaseSrc * bsrc, GstQuery * query)
678 {
679   GstNeonhttpSrc *src = GST_NEONHTTP_SRC (bsrc);
680   gboolean ret;
681
682   switch (GST_QUERY_TYPE (query)) {
683     case GST_QUERY_URI:
684       gst_query_set_uri (query, src->location);
685       ret = TRUE;
686       break;
687     default:
688       ret = FALSE;
689       break;
690   }
691
692   if (!ret)
693     ret = GST_BASE_SRC_CLASS (parent_class)->query (bsrc, query);
694
695   switch (GST_QUERY_TYPE (query)) {
696     case GST_QUERY_SCHEDULING:{
697       GstSchedulingFlags flags;
698       gint minsize, maxsize, align;
699
700       gst_query_parse_scheduling (query, &flags, &minsize, &maxsize, &align);
701       flags |= GST_SCHEDULING_FLAG_BANDWIDTH_LIMITED;
702       gst_query_set_scheduling (query, flags, minsize, maxsize, align);
703       break;
704     }
705     default:
706       break;
707   }
708
709   return ret;
710 }
711
712 static gboolean
713 gst_neonhttp_src_set_location (GstNeonhttpSrc * src, const gchar * uri,
714     GError ** err)
715 {
716   ne_uri_free (&src->uri);
717   if (src->location) {
718     ne_free (src->location);
719     src->location = NULL;
720   }
721   if (src->query_string) {
722     ne_free (src->query_string);
723     src->query_string = NULL;
724   }
725
726   if (ne_uri_parse (uri, &src->uri) != 0)
727     goto parse_error;
728
729   if (src->uri.scheme == NULL)
730     src->uri.scheme = g_strdup ("http");
731
732   if (src->uri.host == NULL)
733     src->uri.host = g_strdup (DEFAULT_LOCATION);
734
735   if (src->uri.port == 0) {
736     if (!strcmp (src->uri.scheme, "https"))
737       src->uri.port = HTTPS_DEFAULT_PORT;
738     else
739       src->uri.port = HTTP_DEFAULT_PORT;
740   }
741
742   if (!src->uri.path)
743     src->uri.path = g_strdup ("");
744
745   src->query_string = g_strjoin ("?", src->uri.path, src->uri.query, NULL);
746
747   src->location = ne_uri_unparse (&src->uri);
748
749   return TRUE;
750
751   /* ERRORS */
752 parse_error:
753   {
754     if (src->location) {
755       ne_free (src->location);
756       src->location = NULL;
757     }
758     if (src->query_string) {
759       ne_free (src->query_string);
760       src->query_string = NULL;
761     }
762     ne_uri_free (&src->uri);
763     return FALSE;
764   }
765 }
766
767 static gboolean
768 gst_neonhttp_src_set_proxy (GstNeonhttpSrc * src, const char *uri)
769 {
770   ne_uri_free (&src->proxy);
771
772   if (ne_uri_parse (uri, &src->proxy) != 0)
773     goto error;
774
775   if (src->proxy.scheme)
776     GST_WARNING ("The proxy schema shouldn't be defined (schema is '%s')",
777         src->proxy.scheme);
778
779   if (src->proxy.host && !src->proxy.port)
780     goto error;
781
782   if (!src->proxy.path || src->proxy.userinfo)
783     goto error;
784   return TRUE;
785
786   /* ERRORS */
787 error:
788   {
789     ne_uri_free (&src->proxy);
790     return FALSE;
791   }
792 }
793
794 static int
795 ssl_verify_callback (void *data, int failures, const ne_ssl_certificate * cert)
796 {
797   GstNeonhttpSrc *src = GST_NEONHTTP_SRC (data);
798
799   if ((failures & NE_SSL_UNTRUSTED) &&
800       src->accept_self_signed && !ne_ssl_cert_signedby (cert)) {
801     GST_ELEMENT_INFO (src, RESOURCE, READ,
802         (NULL), ("Accepting self-signed server certificate"));
803
804     failures &= ~NE_SSL_UNTRUSTED;
805   }
806
807   if (failures & NE_SSL_NOTYETVALID)
808     GST_ELEMENT_ERROR (src, RESOURCE, READ,
809         (NULL), ("Server certificate not valid yet"));
810   if (failures & NE_SSL_EXPIRED)
811     GST_ELEMENT_ERROR (src, RESOURCE, READ,
812         (NULL), ("Server certificate has expired"));
813   if (failures & NE_SSL_IDMISMATCH)
814     GST_ELEMENT_ERROR (src, RESOURCE, READ,
815         (NULL), ("Server certificate doesn't match hostname"));
816   if (failures & NE_SSL_UNTRUSTED)
817     GST_ELEMENT_ERROR (src, RESOURCE, READ,
818         (NULL), ("Server certificate signer not trusted"));
819
820   GST_DEBUG_OBJECT (src, "failures: %d\n", failures);
821
822   return failures;
823 }
824
825 /* Try to send the HTTP request to the Icecast server, and if possible deals with
826  * all the probable redirections (HTTP status code == 3xx)
827  */
828 static gint
829 gst_neonhttp_src_send_request_and_redirect (GstNeonhttpSrc * src,
830     ne_session ** ses, ne_request ** req, gint64 offset, gboolean do_redir)
831 {
832   ne_session *session = NULL;
833   ne_request *request = NULL;
834   gchar **c;
835   gint res;
836   gint http_status = 0;
837   guint request_count = 0;
838
839   do {
840     if (src->proxy.host && src->proxy.port) {
841       session =
842           ne_session_create (src->uri.scheme, src->uri.host, src->uri.port);
843       ne_session_proxy (session, src->proxy.host, src->proxy.port);
844     } else if (src->proxy.host || src->proxy.port) {
845       /* both proxy host and port must be specified or none */
846       return HTTP_REQUEST_WRONG_PROXY;
847     } else {
848       session =
849           ne_session_create (src->uri.scheme, src->uri.host, src->uri.port);
850     }
851
852     if (src->connect_timeout > 0) {
853       ne_set_connect_timeout (session, src->connect_timeout);
854     }
855
856     if (src->read_timeout > 0) {
857       ne_set_read_timeout (session, src->read_timeout);
858     }
859
860     ne_set_session_flag (session, NE_SESSFLAG_ICYPROTO, 1);
861     ne_ssl_set_verify (session, ssl_verify_callback, src);
862
863     request = ne_request_create (session, "GET", src->query_string);
864
865     if (src->user_agent) {
866       ne_add_request_header (request, "User-Agent", src->user_agent);
867     }
868
869     for (c = src->cookies; c != NULL && *c != NULL; ++c) {
870       GST_INFO ("Adding header Cookie : %s", *c);
871       ne_add_request_header (request, "Cookies", *c);
872     }
873
874     if (src->iradio_mode)
875       ne_add_request_header (request, "icy-metadata", "1");
876
877     if (offset > 0) {
878       ne_print_request_header (request, "Range",
879           "bytes=%" G_GINT64_FORMAT "-", offset);
880     }
881
882     res = ne_begin_request (request);
883
884     if (res == NE_OK) {
885       /* When the HTTP status code is 3xx, it is not the SHOUTcast streaming content yet;
886        * Reload the HTTP request with a new URI value */
887       http_status = ne_get_status (request)->code;
888       if (STATUS_IS_REDIRECTION (http_status) && do_redir) {
889         const gchar *redir;
890
891         /* the new URI value to go when redirecting can be found on the 'Location' HTTP header */
892         redir = ne_get_response_header (request, "Location");
893         if (redir != NULL) {
894           ne_uri_free (&src->uri);
895           gst_neonhttp_src_set_location (src, redir, NULL);
896           GST_LOG_OBJECT (src, "Got HTTP Status Code %d", http_status);
897           GST_LOG_OBJECT (src, "Using 'Location' header [%s]", src->uri.host);
898         }
899       }
900     }
901
902     if ((res != NE_OK) ||
903         (offset == 0 && http_status != 200) ||
904         (offset > 0 && http_status != 206 &&
905             !STATUS_IS_REDIRECTION (http_status))) {
906       ne_request_destroy (request);
907       request = NULL;
908       ne_close_connection (session);
909       ne_session_destroy (session);
910       session = NULL;
911       if (offset > 0 && http_status != 206 &&
912           !STATUS_IS_REDIRECTION (http_status)) {
913         src->seekable = FALSE;
914       }
915     }
916
917     /* if - NE_OK */
918     if (STATUS_IS_REDIRECTION (http_status) && do_redir) {
919       ++request_count;
920       GST_LOG_OBJECT (src, "redirect request_count is now %d", request_count);
921       if (request_count < MAX_HTTP_REDIRECTS_NUMBER && do_redir) {
922         GST_INFO_OBJECT (src, "Redirecting to %s", src->uri.host);
923       } else {
924         GST_WARNING_OBJECT (src, "Will not redirect, try again with a "
925             "different URI or redirect location %s", src->uri.host);
926       }
927       /* FIXME: when not redirecting automatically, shouldn't we post a 
928        * redirect element message on the bus? */
929     }
930     /* do the redirect, go back to send another HTTP request now using the 'Location' */
931   } while (do_redir && (request_count < MAX_HTTP_REDIRECTS_NUMBER)
932       && STATUS_IS_REDIRECTION (http_status));
933
934   if (session) {
935     *ses = session;
936     *req = request;
937   }
938
939   return res;
940 }
941
942 static gint
943 gst_neonhttp_src_request_dispatch (GstNeonhttpSrc * src, GstBuffer * outbuf)
944 {
945   GstMapInfo map = GST_MAP_INFO_INIT;
946   gint ret;
947   gint read = 0;
948   gint sizetoread;
949
950   /* Loop sending the request:
951    * Retry whilst authentication fails and we supply it. */
952
953   ssize_t len = 0;
954
955   if (!gst_buffer_map (outbuf, &map, GST_MAP_WRITE))
956     return -1;
957
958   sizetoread = map.size;
959
960   while (sizetoread > 0) {
961     len = ne_read_response_block (src->request, (gchar *) map.data + read,
962         sizetoread);
963     if (len > 0) {
964       read += len;
965       sizetoread -= len;
966     } else {
967       break;
968     }
969
970   }
971
972   gst_buffer_set_size (outbuf, read);
973   GST_BUFFER_OFFSET (outbuf) = src->read_position;
974
975   if (len < 0) {
976     read = -2;
977     goto done;
978   } else if (len == 0) {
979     ret = ne_end_request (src->request);
980     if (ret != NE_RETRY) {
981       if (ret == NE_OK) {
982         src->eos = TRUE;
983       } else {
984         read = -3;
985       }
986     }
987     goto done;
988   }
989
990   if (read > 0)
991     src->read_position += read;
992
993 done:
994
995   gst_buffer_unmap (outbuf, &map);
996
997   return read;
998 }
999
1000 static void
1001 gst_neonhttp_src_close_session (GstNeonhttpSrc * src)
1002 {
1003   if (src->request) {
1004     ne_request_destroy (src->request);
1005     src->request = NULL;
1006   }
1007
1008   if (src->session) {
1009     ne_close_connection (src->session);
1010     ne_session_destroy (src->session);
1011     src->session = NULL;
1012   }
1013 }
1014
1015 /* The following two charset mangling functions were copied from gnomevfssrc.
1016  * Preserve them under the unverified assumption that they do something vaguely
1017  * worthwhile.
1018  */
1019 static gchar *
1020 unicodify (const gchar * str, gint len, ...)
1021 {
1022   gchar *ret = NULL, *cset;
1023   va_list args;
1024   gsize bytes_read, bytes_written;
1025
1026   if (g_utf8_validate (str, len, NULL))
1027     return g_strndup (str, len >= 0 ? len : strlen (str));
1028
1029   va_start (args, len);
1030   while ((cset = va_arg (args, gchar *)) != NULL) {
1031     if (!strcmp (cset, "locale"))
1032       ret = g_locale_to_utf8 (str, len, &bytes_read, &bytes_written, NULL);
1033     else
1034       ret = g_convert (str, len, "UTF-8", cset,
1035           &bytes_read, &bytes_written, NULL);
1036     if (ret)
1037       break;
1038   }
1039   va_end (args);
1040
1041   return ret;
1042 }
1043
1044 static gchar *
1045 gst_neonhttp_src_unicodify (const gchar * str)
1046 {
1047   return unicodify (str, -1, "locale", "ISO-8859-1", NULL);
1048 }
1049
1050 /* GstURIHandler Interface */
1051 static guint
1052 gst_neonhttp_src_uri_get_type (GType type)
1053 {
1054   return GST_URI_SRC;
1055 }
1056
1057 static const gchar *const *
1058 gst_neonhttp_src_uri_get_protocols (GType type)
1059 {
1060   static const gchar *protocols[] = { "http", "https", NULL };
1061
1062   return protocols;
1063 }
1064
1065 static gchar *
1066 gst_neonhttp_src_uri_get_uri (GstURIHandler * handler)
1067 {
1068   GstNeonhttpSrc *src = GST_NEONHTTP_SRC (handler);
1069
1070   /* FIXME: make thread-safe */
1071   return g_strdup (src->location);
1072 }
1073
1074 static gboolean
1075 gst_neonhttp_src_uri_set_uri (GstURIHandler * handler, const gchar * uri,
1076     GError ** error)
1077 {
1078   GstNeonhttpSrc *src = GST_NEONHTTP_SRC (handler);
1079
1080   return gst_neonhttp_src_set_location (src, uri, error);
1081 }
1082
1083 static void
1084 gst_neonhttp_src_uri_handler_init (gpointer g_iface, gpointer iface_data)
1085 {
1086   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
1087
1088   iface->get_type = gst_neonhttp_src_uri_get_type;
1089   iface->get_protocols = gst_neonhttp_src_uri_get_protocols;
1090   iface->get_uri = gst_neonhttp_src_uri_get_uri;
1091   iface->set_uri = gst_neonhttp_src_uri_set_uri;
1092 }
1093
1094 /* entry point to initialize the plug-in
1095  * initialize the plug-in itself
1096  * register the element factories and pad templates
1097  * register the features
1098  */
1099 static gboolean
1100 plugin_init (GstPlugin * plugin)
1101 {
1102   GST_DEBUG_CATEGORY_INIT (neonhttpsrc_debug, "neonhttpsrc", 0,
1103       "NEON HTTP src");
1104
1105   return gst_element_register (plugin, "neonhttpsrc", GST_RANK_NONE,
1106       GST_TYPE_NEONHTTP_SRC);
1107 }
1108
1109 /* this is the structure that gst-register looks for
1110  * so keep the name plugin_desc, or you cannot get your plug-in registered */
1111 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1112     GST_VERSION_MINOR,
1113     neonhttpsrc,
1114     "lib neon http client src",
1115     plugin_init, VERSION, GST_LICENSE, GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)