souphttpsrc: refactor to use Soup's sync API
[platform/upstream/gst-plugins-good.git] / ext / soup / gstsouphttpsrc.c
1 /* GStreamer
2  * Copyright (C) 2007-2008 Wouter Cloetens <wouter@mind.be>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library 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 GNU
12  * Library General Public License for more
13  */
14
15 /**
16  * SECTION:element-souphttpsrc
17  *
18  * This plugin reads data from a remote location specified by a URI.
19  * Supported protocols are 'http', 'https'.
20  *
21  * An HTTP proxy must be specified by its URL.
22  * If the "http_proxy" environment variable is set, its value is used.
23  * If built with libsoup's GNOME integration features, the GNOME proxy
24  * configuration will be used, or failing that, proxy autodetection.
25  * The #GstSoupHTTPSrc:proxy property can be used to override the default.
26  *
27  * In case the #GstSoupHTTPSrc:iradio-mode property is set and the location is
28  * an HTTP resource, souphttpsrc will send special Icecast HTTP headers to the
29  * server to request additional Icecast meta-information.
30  * If the server is not an Icecast server, it will behave as if the
31  * #GstSoupHTTPSrc:iradio-mode property were not set. If it is, souphttpsrc will
32  * output data with a media type of application/x-icy, in which case you will
33  * need to use the #ICYDemux element as follow-up element to extract the Icecast
34  * metadata and to determine the underlying media type.
35  *
36  * <refsect2>
37  * <title>Example launch line</title>
38  * |[
39  * gst-launch-1.0 -v souphttpsrc location=https://some.server.org/index.html
40  *     ! filesink location=/home/joe/server.html
41  * ]| The above pipeline reads a web page from a server using the HTTPS protocol
42  * and writes it to a local file.
43  * |[
44  * gst-launch-1.0 -v souphttpsrc user-agent="FooPlayer 0.99 beta"
45  *     automatic-redirect=false proxy=http://proxy.intranet.local:8080
46  *     location=http://music.foobar.com/demo.mp3 ! mad ! audioconvert
47  *     ! audioresample ! alsasink
48  * ]| The above pipeline will read and decode and play an mp3 file from a
49  * web server using the HTTP protocol. If the server sends redirects,
50  * the request fails instead of following the redirect. The specified
51  * HTTP proxy server is used. The User-Agent HTTP request header
52  * is set to a custom string instead of "GStreamer souphttpsrc."
53  * |[
54  * gst-launch-1.0 -v souphttpsrc location=http://10.11.12.13/mjpeg
55  *     do-timestamp=true ! multipartdemux
56  *     ! image/jpeg,width=640,height=480 ! matroskamux
57  *     ! filesink location=mjpeg.mkv
58  * ]| The above pipeline reads a motion JPEG stream from an IP camera
59  * using the HTTP protocol, encoded as mime/multipart image/jpeg
60  * parts, and writes a Matroska motion JPEG file. The width and
61  * height properties are set in the caps to provide the Matroska
62  * multiplexer with the information to set this in the header.
63  * Timestamps are set on the buffers as they arrive from the camera.
64  * These are used by the mime/multipart demultiplexer to emit timestamps
65  * on the JPEG-encoded video frame buffers. This allows the Matroska
66  * multiplexer to timestamp the frames in the resulting file.
67  * </refsect2>
68  */
69
70 #ifdef HAVE_CONFIG_H
71 #include "config.h"
72 #endif
73
74 #include <string.h>
75 #ifdef HAVE_STDLIB_H
76 #include <stdlib.h>             /* atoi() */
77 #endif
78 #include <gst/gstelement.h>
79 #include <gst/gst-i18n-plugin.h>
80 #include <libsoup/soup.h>
81 #include "gstsouphttpsrc.h"
82 #include "gstsouputils.h"
83
84 #include <gst/tag/tag.h>
85
86 GST_DEBUG_CATEGORY_STATIC (souphttpsrc_debug);
87 #define GST_CAT_DEFAULT souphttpsrc_debug
88
89 static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src",
90     GST_PAD_SRC,
91     GST_PAD_ALWAYS,
92     GST_STATIC_CAPS_ANY);
93
94 enum
95 {
96   PROP_0,
97   PROP_LOCATION,
98   PROP_IS_LIVE,
99   PROP_USER_AGENT,
100   PROP_AUTOMATIC_REDIRECT,
101   PROP_PROXY,
102   PROP_USER_ID,
103   PROP_USER_PW,
104   PROP_PROXY_ID,
105   PROP_PROXY_PW,
106   PROP_COOKIES,
107   PROP_IRADIO_MODE,
108   PROP_TIMEOUT,
109   PROP_EXTRA_HEADERS,
110   PROP_SOUP_LOG_LEVEL,
111   PROP_COMPRESS,
112   PROP_KEEP_ALIVE,
113   PROP_SSL_STRICT,
114   PROP_SSL_CA_FILE,
115   PROP_SSL_USE_SYSTEM_CA_FILE,
116   PROP_TLS_DATABASE,
117   PROP_RETRIES,
118   PROP_METHOD,
119   PROP_TLS_INTERACTION,
120 };
121
122 #define DEFAULT_USER_AGENT           "GStreamer souphttpsrc "
123 #define DEFAULT_IRADIO_MODE          TRUE
124 #define DEFAULT_SOUP_LOG_LEVEL       SOUP_LOGGER_LOG_HEADERS
125 #define DEFAULT_COMPRESS             FALSE
126 #define DEFAULT_KEEP_ALIVE           FALSE
127 #define DEFAULT_SSL_STRICT           TRUE
128 #define DEFAULT_SSL_CA_FILE          NULL
129 #define DEFAULT_SSL_USE_SYSTEM_CA_FILE TRUE
130 #define DEFAULT_TLS_DATABASE         NULL
131 #define DEFAULT_TLS_INTERACTION      NULL
132 #define DEFAULT_TIMEOUT              15
133 #define DEFAULT_RETRIES              3
134 #define DEFAULT_SOUP_METHOD          NULL
135
136 static void gst_soup_http_src_uri_handler_init (gpointer g_iface,
137     gpointer iface_data);
138 static void gst_soup_http_src_finalize (GObject * gobject);
139 static void gst_soup_http_src_dispose (GObject * gobject);
140
141 static void gst_soup_http_src_set_property (GObject * object, guint prop_id,
142     const GValue * value, GParamSpec * pspec);
143 static void gst_soup_http_src_get_property (GObject * object, guint prop_id,
144     GValue * value, GParamSpec * pspec);
145
146 static GstStateChangeReturn gst_soup_http_src_change_state (GstElement *
147     element, GstStateChange transition);
148 static GstFlowReturn gst_soup_http_src_create (GstPushSrc * psrc,
149     GstBuffer ** outbuf);
150 static gboolean gst_soup_http_src_start (GstBaseSrc * bsrc);
151 static gboolean gst_soup_http_src_stop (GstBaseSrc * bsrc);
152 static gboolean gst_soup_http_src_get_size (GstBaseSrc * bsrc, guint64 * size);
153 static gboolean gst_soup_http_src_is_seekable (GstBaseSrc * bsrc);
154 static gboolean gst_soup_http_src_do_seek (GstBaseSrc * bsrc,
155     GstSegment * segment);
156 static gboolean gst_soup_http_src_query (GstBaseSrc * bsrc, GstQuery * query);
157 static gboolean gst_soup_http_src_unlock (GstBaseSrc * bsrc);
158 static gboolean gst_soup_http_src_unlock_stop (GstBaseSrc * bsrc);
159 static gboolean gst_soup_http_src_set_location (GstSoupHTTPSrc * src,
160     const gchar * uri, GError ** error);
161 static gboolean gst_soup_http_src_set_proxy (GstSoupHTTPSrc * src,
162     const gchar * uri);
163 static char *gst_soup_http_src_unicodify (const char *str);
164 static gboolean gst_soup_http_src_build_message (GstSoupHTTPSrc * src,
165     const gchar * method);
166 static void gst_soup_http_src_cancel_message (GstSoupHTTPSrc * src);
167 static gboolean gst_soup_http_src_add_range_header (GstSoupHTTPSrc * src,
168     guint64 offset, guint64 stop_offset);
169 static gboolean gst_soup_http_src_session_open (GstSoupHTTPSrc * src);
170 static void gst_soup_http_src_session_close (GstSoupHTTPSrc * src);
171 static void gst_soup_http_src_parse_status (SoupMessage * msg,
172     GstSoupHTTPSrc * src);
173 static void gst_soup_http_src_got_headers (GstSoupHTTPSrc * src,
174     SoupMessage * msg);
175 static void gst_soup_http_src_authenticate_cb (SoupSession * session,
176     SoupMessage * msg, SoupAuth * auth, gboolean retrying,
177     GstSoupHTTPSrc * src);
178
179 #define gst_soup_http_src_parent_class parent_class
180 G_DEFINE_TYPE_WITH_CODE (GstSoupHTTPSrc, gst_soup_http_src, GST_TYPE_PUSH_SRC,
181     G_IMPLEMENT_INTERFACE (GST_TYPE_URI_HANDLER,
182         gst_soup_http_src_uri_handler_init));
183
184 static void
185 gst_soup_http_src_class_init (GstSoupHTTPSrcClass * klass)
186 {
187   GObjectClass *gobject_class;
188   GstElementClass *gstelement_class;
189   GstBaseSrcClass *gstbasesrc_class;
190   GstPushSrcClass *gstpushsrc_class;
191
192   gobject_class = (GObjectClass *) klass;
193   gstelement_class = (GstElementClass *) klass;
194   gstbasesrc_class = (GstBaseSrcClass *) klass;
195   gstpushsrc_class = (GstPushSrcClass *) klass;
196
197   gobject_class->set_property = gst_soup_http_src_set_property;
198   gobject_class->get_property = gst_soup_http_src_get_property;
199   gobject_class->finalize = gst_soup_http_src_finalize;
200   gobject_class->dispose = gst_soup_http_src_dispose;
201
202   g_object_class_install_property (gobject_class,
203       PROP_LOCATION,
204       g_param_spec_string ("location", "Location",
205           "Location to read from", "",
206           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
207   g_object_class_install_property (gobject_class,
208       PROP_USER_AGENT,
209       g_param_spec_string ("user-agent", "User-Agent",
210           "Value of the User-Agent HTTP request header field",
211           DEFAULT_USER_AGENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
212   g_object_class_install_property (gobject_class,
213       PROP_AUTOMATIC_REDIRECT,
214       g_param_spec_boolean ("automatic-redirect", "automatic-redirect",
215           "Automatically follow HTTP redirects (HTTP Status Code 3xx)",
216           TRUE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
217   g_object_class_install_property (gobject_class,
218       PROP_PROXY,
219       g_param_spec_string ("proxy", "Proxy",
220           "HTTP proxy server URI", "",
221           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
222   g_object_class_install_property (gobject_class,
223       PROP_USER_ID,
224       g_param_spec_string ("user-id", "user-id",
225           "HTTP location URI user id for authentication", "",
226           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
227   g_object_class_install_property (gobject_class, PROP_USER_PW,
228       g_param_spec_string ("user-pw", "user-pw",
229           "HTTP location URI user password for authentication", "",
230           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
231   g_object_class_install_property (gobject_class, PROP_PROXY_ID,
232       g_param_spec_string ("proxy-id", "proxy-id",
233           "HTTP proxy URI user id for authentication", "",
234           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
235   g_object_class_install_property (gobject_class, PROP_PROXY_PW,
236       g_param_spec_string ("proxy-pw", "proxy-pw",
237           "HTTP proxy URI user password for authentication", "",
238           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
239   g_object_class_install_property (gobject_class, PROP_COOKIES,
240       g_param_spec_boxed ("cookies", "Cookies", "HTTP request cookies",
241           G_TYPE_STRV, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
242   g_object_class_install_property (gobject_class, PROP_IS_LIVE,
243       g_param_spec_boolean ("is-live", "is-live", "Act like a live source",
244           FALSE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
245   g_object_class_install_property (gobject_class, PROP_TIMEOUT,
246       g_param_spec_uint ("timeout", "timeout",
247           "Value in seconds to timeout a blocking I/O (0 = No timeout).", 0,
248           3600, DEFAULT_TIMEOUT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
249   g_object_class_install_property (gobject_class, PROP_EXTRA_HEADERS,
250       g_param_spec_boxed ("extra-headers", "Extra Headers",
251           "Extra headers to append to the HTTP request",
252           GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
253   g_object_class_install_property (gobject_class, PROP_IRADIO_MODE,
254       g_param_spec_boolean ("iradio-mode", "iradio-mode",
255           "Enable internet radio mode (ask server to send shoutcast/icecast "
256           "metadata interleaved with the actual stream data)",
257           DEFAULT_IRADIO_MODE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
258
259  /**
260    * GstSoupHTTPSrc::http-log-level:
261    *
262    * If set and > 0, captures and dumps HTTP session data as
263    * log messages if log level >= GST_LEVEL_TRACE
264    *
265    * Since: 1.4
266    */
267   g_object_class_install_property (gobject_class, PROP_SOUP_LOG_LEVEL,
268       g_param_spec_enum ("http-log-level", "HTTP log level",
269           "Set log level for soup's HTTP session log",
270           SOUP_TYPE_LOGGER_LOG_LEVEL, DEFAULT_SOUP_LOG_LEVEL,
271           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
272
273  /**
274    * GstSoupHTTPSrc::compress:
275    *
276    * If set to %TRUE, souphttpsrc will automatically handle gzip
277    * and deflate Content-Encodings. This does not make much difference
278    * and causes more load for normal media files, but makes a real
279    * difference in size for plaintext files.
280    *
281    * Since: 1.4
282    */
283   g_object_class_install_property (gobject_class, PROP_COMPRESS,
284       g_param_spec_boolean ("compress", "Compress",
285           "Allow compressed content encodings",
286           DEFAULT_COMPRESS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
287
288  /**
289    * GstSoupHTTPSrc::keep-alive:
290    *
291    * If set to %TRUE, souphttpsrc will keep alive connections when being
292    * set to READY state and only will close connections when connecting
293    * to a different server or when going to NULL state..
294    *
295    * Since: 1.4
296    */
297   g_object_class_install_property (gobject_class, PROP_KEEP_ALIVE,
298       g_param_spec_boolean ("keep-alive", "keep-alive",
299           "Use HTTP persistent connections", DEFAULT_KEEP_ALIVE,
300           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
301
302  /**
303    * GstSoupHTTPSrc::ssl-strict:
304    *
305    * If set to %TRUE, souphttpsrc will reject all SSL certificates that
306    * are considered invalid.
307    *
308    * Since: 1.4
309    */
310   g_object_class_install_property (gobject_class, PROP_SSL_STRICT,
311       g_param_spec_boolean ("ssl-strict", "SSL Strict",
312           "Strict SSL certificate checking", DEFAULT_SSL_STRICT,
313           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
314
315  /**
316    * GstSoupHTTPSrc::ssl-ca-file:
317    *
318    * A SSL anchor CA file that should be used for checking certificates
319    * instead of the system CA file.
320    *
321    * If this property is non-%NULL, #GstSoupHTTPSrc::ssl-use-system-ca-file
322    * value will be ignored.
323    *
324    * Deprecated: Use #GstSoupHTTPSrc::tls-database property instead.
325    * Since: 1.4
326    */
327   g_object_class_install_property (gobject_class, PROP_SSL_CA_FILE,
328       g_param_spec_string ("ssl-ca-file", "SSL CA File",
329           "Location of a SSL anchor CA file to use", DEFAULT_SSL_CA_FILE,
330           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
331
332  /**
333    * GstSoupHTTPSrc::ssl-use-system-ca-file:
334    *
335    * If set to %TRUE, souphttpsrc will use the system's CA file for
336    * checking certificates, unless #GstSoupHTTPSrc::ssl-ca-file or
337    * #GstSoupHTTPSrc::tls-database are non-%NULL.
338    *
339    * Since: 1.4
340    */
341   g_object_class_install_property (gobject_class, PROP_SSL_USE_SYSTEM_CA_FILE,
342       g_param_spec_boolean ("ssl-use-system-ca-file", "Use System CA File",
343           "Use system CA file", DEFAULT_SSL_USE_SYSTEM_CA_FILE,
344           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
345
346   /**
347    * GstSoupHTTPSrc::tls-database:
348    *
349    * TLS database with anchor certificate authorities used to validate
350    * the server certificate.
351    *
352    * If this property is non-%NULL, #GstSoupHTTPSrc::ssl-use-system-ca-file
353    * and #GstSoupHTTPSrc::ssl-ca-file values will be ignored.
354    *
355    * Since: 1.6
356    */
357   g_object_class_install_property (gobject_class, PROP_TLS_DATABASE,
358       g_param_spec_object ("tls-database", "TLS database",
359           "TLS database with anchor certificate authorities used to validate the server certificate",
360           G_TYPE_TLS_DATABASE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
361
362   /**
363    * GstSoupHTTPSrc::tls-interaction:
364    *
365    * A #GTlsInteraction object to be used when the connection or certificate
366    * database need to interact with the user. This will be used to prompt the
367    * user for passwords or certificate where necessary.
368    *
369    * Since: 1.8
370    */
371   g_object_class_install_property (gobject_class, PROP_TLS_INTERACTION,
372       g_param_spec_object ("tls-interaction", "TLS interaction",
373           "A GTlsInteraction object to be used when the connection or certificate database need to interact with the user.",
374           G_TYPE_TLS_INTERACTION, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
375
376  /**
377    * GstSoupHTTPSrc::retries:
378    *
379    * Maximum number of retries until giving up.
380    *
381    * Since: 1.4
382    */
383   g_object_class_install_property (gobject_class, PROP_RETRIES,
384       g_param_spec_int ("retries", "Retries",
385           "Maximum number of retries until giving up (-1=infinite)", -1,
386           G_MAXINT, DEFAULT_RETRIES,
387           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
388
389  /**
390    * GstSoupHTTPSrc::method
391    *
392    * The HTTP method to use when making a request
393    *
394    * Since: 1.6
395    */
396   g_object_class_install_property (gobject_class, PROP_METHOD,
397       g_param_spec_string ("method", "HTTP method",
398           "The HTTP method to use (GET, HEAD, OPTIONS, etc)",
399           DEFAULT_SOUP_METHOD, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
400
401   gst_element_class_add_static_pad_template (gstelement_class, &srctemplate);
402
403   gst_element_class_set_static_metadata (gstelement_class, "HTTP client source",
404       "Source/Network",
405       "Receive data as a client over the network via HTTP using SOUP",
406       "Wouter Cloetens <wouter@mind.be>");
407   gstelement_class->change_state =
408       GST_DEBUG_FUNCPTR (gst_soup_http_src_change_state);
409
410   gstbasesrc_class->start = GST_DEBUG_FUNCPTR (gst_soup_http_src_start);
411   gstbasesrc_class->stop = GST_DEBUG_FUNCPTR (gst_soup_http_src_stop);
412   gstbasesrc_class->unlock = GST_DEBUG_FUNCPTR (gst_soup_http_src_unlock);
413   gstbasesrc_class->unlock_stop =
414       GST_DEBUG_FUNCPTR (gst_soup_http_src_unlock_stop);
415   gstbasesrc_class->get_size = GST_DEBUG_FUNCPTR (gst_soup_http_src_get_size);
416   gstbasesrc_class->is_seekable =
417       GST_DEBUG_FUNCPTR (gst_soup_http_src_is_seekable);
418   gstbasesrc_class->do_seek = GST_DEBUG_FUNCPTR (gst_soup_http_src_do_seek);
419   gstbasesrc_class->query = GST_DEBUG_FUNCPTR (gst_soup_http_src_query);
420
421   gstpushsrc_class->create = GST_DEBUG_FUNCPTR (gst_soup_http_src_create);
422
423   GST_DEBUG_CATEGORY_INIT (souphttpsrc_debug, "souphttpsrc", 0,
424       "SOUP HTTP src");
425 }
426
427 static void
428 gst_soup_http_src_reset (GstSoupHTTPSrc * src)
429 {
430   src->retry_count = 0;
431   src->have_size = FALSE;
432   src->got_headers = FALSE;
433   src->seekable = FALSE;
434   src->read_position = 0;
435   src->request_position = 0;
436   src->stop_position = -1;
437   src->content_size = 0;
438   src->have_body = FALSE;
439
440   src->ret = GST_FLOW_OK;
441   g_cancellable_reset (src->cancellable);
442   if (src->input_stream) {
443     g_object_unref (src->input_stream);
444     src->input_stream = NULL;
445   }
446
447   gst_caps_replace (&src->src_caps, NULL);
448   g_free (src->iradio_name);
449   src->iradio_name = NULL;
450   g_free (src->iradio_genre);
451   src->iradio_genre = NULL;
452   g_free (src->iradio_url);
453   src->iradio_url = NULL;
454 }
455
456 static void
457 gst_soup_http_src_init (GstSoupHTTPSrc * src)
458 {
459   const gchar *proxy;
460
461   g_mutex_init (&src->mutex);
462   g_cond_init (&src->have_headers_cond);
463   src->cancellable = g_cancellable_new ();
464   src->location = NULL;
465   src->redirection_uri = NULL;
466   src->automatic_redirect = TRUE;
467   src->user_agent = g_strdup (DEFAULT_USER_AGENT);
468   src->user_id = NULL;
469   src->user_pw = NULL;
470   src->proxy_id = NULL;
471   src->proxy_pw = NULL;
472   src->cookies = NULL;
473   src->iradio_mode = DEFAULT_IRADIO_MODE;
474   src->session = NULL;
475   src->msg = NULL;
476   src->timeout = DEFAULT_TIMEOUT;
477   src->log_level = DEFAULT_SOUP_LOG_LEVEL;
478   src->ssl_strict = DEFAULT_SSL_STRICT;
479   src->ssl_use_system_ca_file = DEFAULT_SSL_USE_SYSTEM_CA_FILE;
480   src->tls_database = DEFAULT_TLS_DATABASE;
481   src->tls_interaction = DEFAULT_TLS_INTERACTION;
482   src->max_retries = DEFAULT_RETRIES;
483   src->method = DEFAULT_SOUP_METHOD;
484   proxy = g_getenv ("http_proxy");
485   if (!gst_soup_http_src_set_proxy (src, proxy)) {
486     GST_WARNING_OBJECT (src,
487         "The proxy in the http_proxy env var (\"%s\") cannot be parsed.",
488         proxy);
489   }
490
491   gst_base_src_set_automatic_eos (GST_BASE_SRC (src), FALSE);
492
493   gst_soup_http_src_reset (src);
494 }
495
496 static void
497 gst_soup_http_src_dispose (GObject * gobject)
498 {
499   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (gobject);
500
501   GST_DEBUG_OBJECT (src, "dispose");
502
503   gst_soup_http_src_session_close (src);
504
505   G_OBJECT_CLASS (parent_class)->dispose (gobject);
506 }
507
508 static void
509 gst_soup_http_src_finalize (GObject * gobject)
510 {
511   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (gobject);
512
513   GST_DEBUG_OBJECT (src, "finalize");
514
515   g_mutex_clear (&src->mutex);
516   g_cond_clear (&src->have_headers_cond);
517   g_object_unref (src->cancellable);
518   g_free (src->location);
519   g_free (src->redirection_uri);
520   g_free (src->user_agent);
521   if (src->proxy != NULL) {
522     soup_uri_free (src->proxy);
523   }
524   g_free (src->user_id);
525   g_free (src->user_pw);
526   g_free (src->proxy_id);
527   g_free (src->proxy_pw);
528   g_strfreev (src->cookies);
529
530   if (src->extra_headers) {
531     gst_structure_free (src->extra_headers);
532     src->extra_headers = NULL;
533   }
534
535   g_free (src->ssl_ca_file);
536
537   if (src->tls_database)
538     g_object_unref (src->tls_database);
539   g_free (src->method);
540
541   if (src->tls_interaction)
542     g_object_unref (src->tls_interaction);
543
544   G_OBJECT_CLASS (parent_class)->finalize (gobject);
545 }
546
547 static void
548 gst_soup_http_src_set_property (GObject * object, guint prop_id,
549     const GValue * value, GParamSpec * pspec)
550 {
551   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (object);
552
553   switch (prop_id) {
554     case PROP_LOCATION:
555     {
556       const gchar *location;
557
558       location = g_value_get_string (value);
559
560       if (location == NULL) {
561         GST_WARNING ("location property cannot be NULL");
562         goto done;
563       }
564       if (!gst_soup_http_src_set_location (src, location, NULL)) {
565         GST_WARNING ("badly formatted location");
566         goto done;
567       }
568       break;
569     }
570     case PROP_USER_AGENT:
571       g_free (src->user_agent);
572       src->user_agent = g_value_dup_string (value);
573       break;
574     case PROP_IRADIO_MODE:
575       src->iradio_mode = g_value_get_boolean (value);
576       break;
577     case PROP_AUTOMATIC_REDIRECT:
578       src->automatic_redirect = g_value_get_boolean (value);
579       break;
580     case PROP_PROXY:
581     {
582       const gchar *proxy;
583
584       proxy = g_value_get_string (value);
585       if (!gst_soup_http_src_set_proxy (src, proxy)) {
586         GST_WARNING ("badly formatted proxy URI");
587         goto done;
588       }
589       break;
590     }
591     case PROP_COOKIES:
592       g_strfreev (src->cookies);
593       src->cookies = g_strdupv (g_value_get_boxed (value));
594       break;
595     case PROP_IS_LIVE:
596       gst_base_src_set_live (GST_BASE_SRC (src), g_value_get_boolean (value));
597       break;
598     case PROP_USER_ID:
599       g_free (src->user_id);
600       src->user_id = g_value_dup_string (value);
601       break;
602     case PROP_USER_PW:
603       g_free (src->user_pw);
604       src->user_pw = g_value_dup_string (value);
605       break;
606     case PROP_PROXY_ID:
607       g_free (src->proxy_id);
608       src->proxy_id = g_value_dup_string (value);
609       break;
610     case PROP_PROXY_PW:
611       g_free (src->proxy_pw);
612       src->proxy_pw = g_value_dup_string (value);
613       break;
614     case PROP_TIMEOUT:
615       src->timeout = g_value_get_uint (value);
616       break;
617     case PROP_EXTRA_HEADERS:{
618       const GstStructure *s = gst_value_get_structure (value);
619
620       if (src->extra_headers)
621         gst_structure_free (src->extra_headers);
622
623       src->extra_headers = s ? gst_structure_copy (s) : NULL;
624       break;
625     }
626     case PROP_SOUP_LOG_LEVEL:
627       src->log_level = g_value_get_enum (value);
628       break;
629     case PROP_COMPRESS:
630       src->compress = g_value_get_boolean (value);
631       break;
632     case PROP_KEEP_ALIVE:
633       src->keep_alive = g_value_get_boolean (value);
634       break;
635     case PROP_SSL_STRICT:
636       src->ssl_strict = g_value_get_boolean (value);
637       break;
638     case PROP_SSL_CA_FILE:
639       g_free (src->ssl_ca_file);
640       src->ssl_ca_file = g_value_dup_string (value);
641       break;
642     case PROP_SSL_USE_SYSTEM_CA_FILE:
643       src->ssl_use_system_ca_file = g_value_get_boolean (value);
644       break;
645     case PROP_TLS_DATABASE:
646       g_clear_object (&src->tls_database);
647       src->tls_database = g_value_dup_object (value);
648       break;
649     case PROP_TLS_INTERACTION:
650       g_clear_object (&src->tls_interaction);
651       src->tls_interaction = g_value_dup_object (value);
652       break;
653     case PROP_RETRIES:
654       src->max_retries = g_value_get_int (value);
655       break;
656     case PROP_METHOD:
657       g_free (src->method);
658       src->method = g_value_dup_string (value);
659       break;
660     default:
661       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
662       break;
663   }
664 done:
665   return;
666 }
667
668 static void
669 gst_soup_http_src_get_property (GObject * object, guint prop_id,
670     GValue * value, GParamSpec * pspec)
671 {
672   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (object);
673
674   switch (prop_id) {
675     case PROP_LOCATION:
676       g_value_set_string (value, src->location);
677       break;
678     case PROP_USER_AGENT:
679       g_value_set_string (value, src->user_agent);
680       break;
681     case PROP_AUTOMATIC_REDIRECT:
682       g_value_set_boolean (value, src->automatic_redirect);
683       break;
684     case PROP_PROXY:
685       if (src->proxy == NULL)
686         g_value_set_static_string (value, "");
687       else {
688         char *proxy = soup_uri_to_string (src->proxy, FALSE);
689
690         g_value_set_string (value, proxy);
691         g_free (proxy);
692       }
693       break;
694     case PROP_COOKIES:
695       g_value_set_boxed (value, g_strdupv (src->cookies));
696       break;
697     case PROP_IS_LIVE:
698       g_value_set_boolean (value, gst_base_src_is_live (GST_BASE_SRC (src)));
699       break;
700     case PROP_IRADIO_MODE:
701       g_value_set_boolean (value, src->iradio_mode);
702       break;
703     case PROP_USER_ID:
704       g_value_set_string (value, src->user_id);
705       break;
706     case PROP_USER_PW:
707       g_value_set_string (value, src->user_pw);
708       break;
709     case PROP_PROXY_ID:
710       g_value_set_string (value, src->proxy_id);
711       break;
712     case PROP_PROXY_PW:
713       g_value_set_string (value, src->proxy_pw);
714       break;
715     case PROP_TIMEOUT:
716       g_value_set_uint (value, src->timeout);
717       break;
718     case PROP_EXTRA_HEADERS:
719       gst_value_set_structure (value, src->extra_headers);
720       break;
721     case PROP_SOUP_LOG_LEVEL:
722       g_value_set_enum (value, src->log_level);
723       break;
724     case PROP_COMPRESS:
725       g_value_set_boolean (value, src->compress);
726       break;
727     case PROP_KEEP_ALIVE:
728       g_value_set_boolean (value, src->keep_alive);
729       break;
730     case PROP_SSL_STRICT:
731       g_value_set_boolean (value, src->ssl_strict);
732       break;
733     case PROP_SSL_CA_FILE:
734       g_value_set_string (value, src->ssl_ca_file);
735       break;
736     case PROP_SSL_USE_SYSTEM_CA_FILE:
737       g_value_set_boolean (value, src->ssl_use_system_ca_file);
738       break;
739     case PROP_TLS_DATABASE:
740       g_value_set_object (value, src->tls_database);
741       break;
742     case PROP_TLS_INTERACTION:
743       g_value_set_object (value, src->tls_interaction);
744       break;
745     case PROP_RETRIES:
746       g_value_set_int (value, src->max_retries);
747       break;
748     case PROP_METHOD:
749       g_value_set_string (value, src->method);
750       break;
751     default:
752       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
753       break;
754   }
755 }
756
757 static gchar *
758 gst_soup_http_src_unicodify (const gchar * str)
759 {
760   const gchar *env_vars[] = { "GST_ICY_TAG_ENCODING",
761     "GST_TAG_ENCODING", NULL
762   };
763
764   return gst_tag_freeform_string_to_utf8 (str, -1, env_vars);
765 }
766
767 static void
768 gst_soup_http_src_cancel_message (GstSoupHTTPSrc * src)
769 {
770   g_cancellable_cancel (src->cancellable);
771   g_cond_signal (&src->have_headers_cond);
772 }
773
774 static gboolean
775 gst_soup_http_src_add_range_header (GstSoupHTTPSrc * src, guint64 offset,
776     guint64 stop_offset)
777 {
778   gchar buf[64];
779   gint rc;
780
781   soup_message_headers_remove (src->msg->request_headers, "Range");
782   if (offset || stop_offset != -1) {
783     if (stop_offset != -1) {
784       g_assert (offset != stop_offset);
785
786       rc = g_snprintf (buf, sizeof (buf), "bytes=%" G_GUINT64_FORMAT "-%"
787           G_GUINT64_FORMAT, offset, (stop_offset > 0) ? stop_offset - 1 :
788           stop_offset);
789     } else {
790       rc = g_snprintf (buf, sizeof (buf), "bytes=%" G_GUINT64_FORMAT "-",
791           offset);
792     }
793     if (rc > sizeof (buf) || rc < 0)
794       return FALSE;
795     soup_message_headers_append (src->msg->request_headers, "Range", buf);
796   }
797   src->read_position = offset;
798   return TRUE;
799 }
800
801 static gboolean
802 _append_extra_header (GQuark field_id, const GValue * value, gpointer user_data)
803 {
804   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (user_data);
805   const gchar *field_name = g_quark_to_string (field_id);
806   gchar *field_content = NULL;
807
808   if (G_VALUE_TYPE (value) == G_TYPE_STRING) {
809     field_content = g_value_dup_string (value);
810   } else {
811     GValue dest = { 0, };
812
813     g_value_init (&dest, G_TYPE_STRING);
814     if (g_value_transform (value, &dest)) {
815       field_content = g_value_dup_string (&dest);
816     }
817   }
818
819   if (field_content == NULL) {
820     GST_ERROR_OBJECT (src, "extra-headers field '%s' contains no value "
821         "or can't be converted to a string", field_name);
822     return FALSE;
823   }
824
825   GST_DEBUG_OBJECT (src, "Appending extra header: \"%s: %s\"", field_name,
826       field_content);
827   soup_message_headers_append (src->msg->request_headers, field_name,
828       field_content);
829
830   g_free (field_content);
831
832   return TRUE;
833 }
834
835 static gboolean
836 _append_extra_headers (GQuark field_id, const GValue * value,
837     gpointer user_data)
838 {
839   if (G_VALUE_TYPE (value) == GST_TYPE_ARRAY) {
840     guint n = gst_value_array_get_size (value);
841     guint i;
842
843     for (i = 0; i < n; i++) {
844       const GValue *v = gst_value_array_get_value (value, i);
845
846       if (!_append_extra_header (field_id, v, user_data))
847         return FALSE;
848     }
849   } else if (G_VALUE_TYPE (value) == GST_TYPE_LIST) {
850     guint n = gst_value_list_get_size (value);
851     guint i;
852
853     for (i = 0; i < n; i++) {
854       const GValue *v = gst_value_list_get_value (value, i);
855
856       if (!_append_extra_header (field_id, v, user_data))
857         return FALSE;
858     }
859   } else {
860     return _append_extra_header (field_id, value, user_data);
861   }
862
863   return TRUE;
864 }
865
866
867 static gboolean
868 gst_soup_http_src_add_extra_headers (GstSoupHTTPSrc * src)
869 {
870   if (!src->extra_headers)
871     return TRUE;
872
873   return gst_structure_foreach (src->extra_headers, _append_extra_headers, src);
874 }
875
876 static gboolean
877 gst_soup_http_src_session_open (GstSoupHTTPSrc * src)
878 {
879   if (src->session) {
880     GST_DEBUG_OBJECT (src, "Session is already open");
881     return TRUE;
882   }
883
884   if (!src->location) {
885     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (_("No URL set.")),
886         ("Missing location property"));
887     return FALSE;
888   }
889
890   if (!src->session) {
891     GST_DEBUG_OBJECT (src, "Creating session");
892     if (src->proxy == NULL) {
893       src->session =
894           soup_session_new_with_options (SOUP_SESSION_USER_AGENT,
895           src->user_agent, SOUP_SESSION_TIMEOUT, src->timeout,
896           SOUP_SESSION_SSL_STRICT, src->ssl_strict,
897           SOUP_SESSION_ADD_FEATURE_BY_TYPE, SOUP_TYPE_PROXY_RESOLVER_DEFAULT,
898           SOUP_SESSION_TLS_INTERACTION, src->tls_interaction, NULL);
899     } else {
900       src->session =
901           soup_session_new_with_options (SOUP_SESSION_PROXY_URI, src->proxy,
902           SOUP_SESSION_TIMEOUT, src->timeout,
903           SOUP_SESSION_SSL_STRICT, src->ssl_strict,
904           SOUP_SESSION_USER_AGENT, src->user_agent,
905           SOUP_SESSION_TLS_INTERACTION, src->tls_interaction, NULL);
906     }
907
908     if (!src->session) {
909       GST_ELEMENT_ERROR (src, LIBRARY, INIT,
910           (NULL), ("Failed to create async session"));
911       return FALSE;
912     }
913
914     g_signal_connect (src->session, "authenticate",
915         G_CALLBACK (gst_soup_http_src_authenticate_cb), src);
916
917     /* Set up logging */
918     gst_soup_util_log_setup (src->session, src->log_level, GST_ELEMENT (src));
919     if (src->tls_database)
920       g_object_set (src->session, "tls-database", src->tls_database, NULL);
921     else if (src->ssl_ca_file)
922       g_object_set (src->session, "ssl-ca-file", src->ssl_ca_file, NULL);
923     else
924       g_object_set (src->session, "ssl-use-system-ca-file",
925           src->ssl_use_system_ca_file, NULL);
926   } else {
927     GST_DEBUG_OBJECT (src, "Re-using session");
928   }
929
930   if (src->compress)
931     soup_session_add_feature_by_type (src->session, SOUP_TYPE_CONTENT_DECODER);
932   else
933     soup_session_remove_feature_by_type (src->session,
934         SOUP_TYPE_CONTENT_DECODER);
935
936   return TRUE;
937 }
938
939 static void
940 gst_soup_http_src_session_close (GstSoupHTTPSrc * src)
941 {
942   GST_DEBUG_OBJECT (src, "Closing session");
943
944   g_mutex_lock (&src->mutex);
945   if (src->session) {
946     soup_session_abort (src->session);  /* This unrefs the message. */
947     g_object_unref (src->session);
948     src->session = NULL;
949     src->msg = NULL;
950   }
951   g_mutex_unlock (&src->mutex);
952 }
953
954 static void
955 gst_soup_http_src_authenticate_cb (SoupSession * session, SoupMessage * msg,
956     SoupAuth * auth, gboolean retrying, GstSoupHTTPSrc * src)
957 {
958   if (!retrying) {
959     /* First time authentication only, if we fail and are called again with retry true fall through */
960     if (msg->status_code == SOUP_STATUS_UNAUTHORIZED) {
961       if (src->user_id && src->user_pw)
962         soup_auth_authenticate (auth, src->user_id, src->user_pw);
963     } else if (msg->status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED) {
964       if (src->proxy_id && src->proxy_pw)
965         soup_auth_authenticate (auth, src->proxy_id, src->proxy_pw);
966     }
967   }
968 }
969
970 static void
971 insert_http_header (const gchar * name, const gchar * value, gpointer user_data)
972 {
973   GstStructure *headers = user_data;
974   const GValue *gv;
975
976   gv = gst_structure_get_value (headers, name);
977   if (gv && GST_VALUE_HOLDS_ARRAY (gv)) {
978     GValue v = G_VALUE_INIT;
979
980     g_value_init (&v, G_TYPE_STRING);
981     g_value_set_string (&v, value);
982     gst_value_array_append_value ((GValue *) gv, &v);
983     g_value_unset (&v);
984   } else if (gv && G_VALUE_HOLDS_STRING (gv)) {
985     GValue arr = G_VALUE_INIT;
986     GValue v = G_VALUE_INIT;
987     const gchar *old_value = g_value_get_string (gv);
988
989     g_value_init (&arr, GST_TYPE_ARRAY);
990     g_value_init (&v, G_TYPE_STRING);
991     g_value_set_string (&v, old_value);
992     gst_value_array_append_value (&arr, &v);
993     g_value_set_string (&v, value);
994     gst_value_array_append_value (&arr, &v);
995
996     gst_structure_set_value (headers, name, &arr);
997     g_value_unset (&v);
998     g_value_unset (&arr);
999   } else {
1000     gst_structure_set (headers, name, G_TYPE_STRING, value, NULL);
1001   }
1002 }
1003
1004 static void
1005 gst_soup_http_src_got_headers (GstSoupHTTPSrc * src, SoupMessage * msg)
1006 {
1007   const char *value;
1008   GstTagList *tag_list;
1009   GstBaseSrc *basesrc;
1010   guint64 newsize;
1011   GHashTable *params = NULL;
1012   GstEvent *http_headers_event;
1013   GstStructure *http_headers, *headers;
1014   const gchar *accept_ranges;
1015
1016   GST_INFO_OBJECT (src, "got headers");
1017
1018   if (msg->status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED &&
1019       src->proxy_id && src->proxy_pw)
1020     return;
1021
1022   if (src->automatic_redirect && SOUP_STATUS_IS_REDIRECTION (msg->status_code)) {
1023     src->redirection_uri = g_strdup (soup_message_headers_get_one
1024         (msg->response_headers, "Location"));
1025     src->redirection_permanent =
1026         (msg->status_code == SOUP_STATUS_MOVED_PERMANENTLY);
1027     GST_DEBUG_OBJECT (src, "%u redirect to \"%s\" (permanent %d)",
1028         msg->status_code, src->redirection_uri, src->redirection_permanent);
1029     return;
1030   }
1031
1032   if (msg->status_code == SOUP_STATUS_UNAUTHORIZED) {
1033     /* force an error */
1034     gst_soup_http_src_parse_status (msg, src);
1035     return;
1036   }
1037
1038   src->got_headers = TRUE;
1039   g_cond_broadcast (&src->have_headers_cond);
1040
1041   http_headers = gst_structure_new_empty ("http-headers");
1042   gst_structure_set (http_headers, "uri", G_TYPE_STRING, src->location, NULL);
1043   if (src->redirection_uri)
1044     gst_structure_set (http_headers, "redirection-uri", G_TYPE_STRING,
1045         src->redirection_uri, NULL);
1046   headers = gst_structure_new_empty ("request-headers");
1047   soup_message_headers_foreach (msg->request_headers, insert_http_header,
1048       headers);
1049   gst_structure_set (http_headers, "request-headers", GST_TYPE_STRUCTURE,
1050       headers, NULL);
1051   gst_structure_free (headers);
1052   headers = gst_structure_new_empty ("response-headers");
1053   soup_message_headers_foreach (msg->response_headers, insert_http_header,
1054       headers);
1055   gst_structure_set (http_headers, "response-headers", GST_TYPE_STRUCTURE,
1056       headers, NULL);
1057   gst_structure_free (headers);
1058
1059   http_headers_event =
1060       gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM_STICKY, http_headers);
1061   gst_event_replace (&src->http_headers_event, http_headers_event);
1062   gst_event_unref (http_headers_event);
1063
1064   /* Parse Content-Length. */
1065   if (soup_message_headers_get_encoding (msg->response_headers) ==
1066       SOUP_ENCODING_CONTENT_LENGTH) {
1067     newsize = src->request_position +
1068         soup_message_headers_get_content_length (msg->response_headers);
1069     if (!src->have_size || (src->content_size != newsize)) {
1070       src->content_size = newsize;
1071       src->have_size = TRUE;
1072       src->seekable = TRUE;
1073       GST_DEBUG_OBJECT (src, "size = %" G_GUINT64_FORMAT, src->content_size);
1074
1075       basesrc = GST_BASE_SRC_CAST (src);
1076       basesrc->segment.duration = src->content_size;
1077       gst_element_post_message (GST_ELEMENT (src),
1078           gst_message_new_duration_changed (GST_OBJECT (src)));
1079     }
1080   }
1081
1082   /* If the server reports Accept-Ranges: none we don't have to try
1083    * doing range requests at all
1084    */
1085   if ((accept_ranges =
1086           soup_message_headers_get_one (msg->response_headers,
1087               "Accept-Ranges"))) {
1088     if (g_ascii_strcasecmp (accept_ranges, "none") == 0)
1089       src->seekable = FALSE;
1090   }
1091
1092   /* Icecast stuff */
1093   tag_list = gst_tag_list_new_empty ();
1094
1095   if ((value =
1096           soup_message_headers_get_one (msg->response_headers,
1097               "icy-metaint")) != NULL) {
1098     gint icy_metaint = atoi (value);
1099
1100     GST_DEBUG_OBJECT (src, "icy-metaint: %s (parsed: %d)", value, icy_metaint);
1101     if (icy_metaint > 0) {
1102       if (src->src_caps)
1103         gst_caps_unref (src->src_caps);
1104
1105       src->src_caps = gst_caps_new_simple ("application/x-icy",
1106           "metadata-interval", G_TYPE_INT, icy_metaint, NULL);
1107
1108       gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps);
1109     }
1110   }
1111   if ((value =
1112           soup_message_headers_get_content_type (msg->response_headers,
1113               &params)) != NULL) {
1114     GST_DEBUG_OBJECT (src, "Content-Type: %s", value);
1115     if (g_ascii_strcasecmp (value, "audio/L16") == 0) {
1116       gint channels = 2;
1117       gint rate = 44100;
1118       char *param;
1119
1120       if (src->src_caps)
1121         gst_caps_unref (src->src_caps);
1122
1123       param = g_hash_table_lookup (params, "channels");
1124       if (param != NULL)
1125         channels = atol (param);
1126
1127       param = g_hash_table_lookup (params, "rate");
1128       if (param != NULL)
1129         rate = atol (param);
1130
1131       src->src_caps = gst_caps_new_simple ("audio/x-raw",
1132           "format", G_TYPE_STRING, "S16BE",
1133           "layout", G_TYPE_STRING, "interleaved",
1134           "channels", G_TYPE_INT, channels, "rate", G_TYPE_INT, rate, NULL);
1135
1136       gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps);
1137     } else {
1138       /* Set the Content-Type field on the caps */
1139       if (src->src_caps) {
1140         src->src_caps = gst_caps_make_writable (src->src_caps);
1141         gst_caps_set_simple (src->src_caps, "content-type", G_TYPE_STRING,
1142             value, NULL);
1143         gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps);
1144       }
1145     }
1146   }
1147
1148   if (params != NULL)
1149     g_hash_table_destroy (params);
1150
1151   if ((value =
1152           soup_message_headers_get_one (msg->response_headers,
1153               "icy-name")) != NULL) {
1154     g_free (src->iradio_name);
1155     src->iradio_name = gst_soup_http_src_unicodify (value);
1156     if (src->iradio_name) {
1157       gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_ORGANIZATION,
1158           src->iradio_name, NULL);
1159     }
1160   }
1161   if ((value =
1162           soup_message_headers_get_one (msg->response_headers,
1163               "icy-genre")) != NULL) {
1164     g_free (src->iradio_genre);
1165     src->iradio_genre = gst_soup_http_src_unicodify (value);
1166     if (src->iradio_genre) {
1167       gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_GENRE,
1168           src->iradio_genre, NULL);
1169     }
1170   }
1171   if ((value = soup_message_headers_get_one (msg->response_headers, "icy-url"))
1172       != NULL) {
1173     g_free (src->iradio_url);
1174     src->iradio_url = gst_soup_http_src_unicodify (value);
1175     if (src->iradio_url) {
1176       gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_LOCATION,
1177           src->iradio_url, NULL);
1178     }
1179   }
1180   if (!gst_tag_list_is_empty (tag_list)) {
1181     GST_DEBUG_OBJECT (src,
1182         "calling gst_element_found_tags with %" GST_PTR_FORMAT, tag_list);
1183     gst_pad_push_event (GST_BASE_SRC_PAD (src), gst_event_new_tag (tag_list));
1184   } else {
1185     gst_tag_list_unref (tag_list);
1186   }
1187
1188   /* Handle HTTP errors. */
1189   gst_soup_http_src_parse_status (msg, src);
1190
1191   /* Check if Range header was respected. */
1192   if (src->ret == GST_FLOW_CUSTOM_ERROR &&
1193       src->read_position && msg->status_code != SOUP_STATUS_PARTIAL_CONTENT) {
1194     src->seekable = FALSE;
1195     GST_ELEMENT_ERROR (src, RESOURCE, SEEK,
1196         (_("Server does not support seeking.")),
1197         ("Server does not accept Range HTTP header, URL: %s, Redirect to: %s",
1198             src->location, GST_STR_NULL (src->redirection_uri)));
1199     src->ret = GST_FLOW_ERROR;
1200   }
1201
1202   /* If we are going to error out, stop all processing right here, so we
1203    * don't output any data (such as an error html page), and return
1204    * GST_FLOW_ERROR from the create function instead of having
1205    * got_chunk_cb overwrite src->ret with FLOW_OK again. */
1206   if (src->ret == GST_FLOW_ERROR || src->ret == GST_FLOW_EOS) {
1207   }
1208 }
1209
1210 static GstBuffer *
1211 gst_soup_http_src_alloc_buffer (GstSoupHTTPSrc * src)
1212 {
1213   GstBaseSrc *basesrc = GST_BASE_SRC_CAST (src);
1214   GstFlowReturn rc;
1215   GstBuffer *gstbuf;
1216
1217   rc = GST_BASE_SRC_CLASS (parent_class)->alloc (basesrc, -1,
1218       basesrc->blocksize, &gstbuf);
1219   if (G_UNLIKELY (rc != GST_FLOW_OK)) {
1220     return NULL;
1221   }
1222
1223   return gstbuf;
1224 }
1225
1226 #define SOUP_HTTP_SRC_ERROR(src,soup_msg,cat,code,error_message)     \
1227   GST_ELEMENT_ERROR ((src), cat, code, ("%s", error_message),        \
1228       ("%s (%d), URL: %s, Redirect to: %s", (soup_msg)->reason_phrase,                \
1229           (soup_msg)->status_code, (src)->location, GST_STR_NULL ((src)->redirection_uri)));
1230
1231 static void
1232 gst_soup_http_src_parse_status (SoupMessage * msg, GstSoupHTTPSrc * src)
1233 {
1234   if (msg->method == SOUP_METHOD_HEAD) {
1235     if (!SOUP_STATUS_IS_SUCCESSFUL (msg->status_code))
1236       GST_DEBUG_OBJECT (src, "Ignoring error %d during HEAD request",
1237           msg->status_code);
1238   } else if (SOUP_STATUS_IS_TRANSPORT_ERROR (msg->status_code)) {
1239     switch (msg->status_code) {
1240       case SOUP_STATUS_CANT_RESOLVE:
1241       case SOUP_STATUS_CANT_RESOLVE_PROXY:
1242         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, NOT_FOUND,
1243             _("Could not resolve server name."));
1244         src->ret = GST_FLOW_ERROR;
1245         break;
1246       case SOUP_STATUS_CANT_CONNECT:
1247       case SOUP_STATUS_CANT_CONNECT_PROXY:
1248         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, OPEN_READ,
1249             _("Could not establish connection to server."));
1250         src->ret = GST_FLOW_ERROR;
1251         break;
1252       case SOUP_STATUS_SSL_FAILED:
1253         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, OPEN_READ,
1254             _("Secure connection setup failed."));
1255         src->ret = GST_FLOW_ERROR;
1256         break;
1257       case SOUP_STATUS_IO_ERROR:
1258         if (src->max_retries == -1 || src->retry_count < src->max_retries) {
1259           src->ret = GST_FLOW_CUSTOM_ERROR;
1260         } else {
1261           SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, READ,
1262               _("A network error occurred, or the server closed the connection "
1263                   "unexpectedly."));
1264           src->ret = GST_FLOW_ERROR;
1265         }
1266         break;
1267       case SOUP_STATUS_MALFORMED:
1268         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, READ,
1269             _("Server sent bad data."));
1270         src->ret = GST_FLOW_ERROR;
1271         break;
1272       case SOUP_STATUS_CANCELLED:
1273         /* No error message when interrupted by program. */
1274         break;
1275     }
1276   } else if (SOUP_STATUS_IS_CLIENT_ERROR (msg->status_code) ||
1277       SOUP_STATUS_IS_REDIRECTION (msg->status_code) ||
1278       SOUP_STATUS_IS_SERVER_ERROR (msg->status_code)) {
1279     /* Report HTTP error. */
1280
1281     /* when content_size is unknown and we have just finished receiving
1282      * a body message, requests that go beyond the content limits will result
1283      * in an error. Here we convert those to EOS */
1284     if (msg->status_code == SOUP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE &&
1285         src->have_body && !src->have_size) {
1286       GST_DEBUG_OBJECT (src, "Requested range out of limits and received full "
1287           "body, returning EOS");
1288       src->ret = GST_FLOW_EOS;
1289       return;
1290     }
1291
1292     /* FIXME: reason_phrase is not translated and not suitable for user
1293      * error dialog according to libsoup documentation.
1294      */
1295     if (msg->status_code == SOUP_STATUS_NOT_FOUND) {
1296       GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND,
1297           ("%s", msg->reason_phrase),
1298           ("%s (%d), URL: %s, Redirect to: %s", msg->reason_phrase,
1299               msg->status_code, src->location,
1300               GST_STR_NULL (src->redirection_uri)));
1301     } else if (msg->status_code == SOUP_STATUS_UNAUTHORIZED
1302         || msg->status_code == SOUP_STATUS_PAYMENT_REQUIRED
1303         || msg->status_code == SOUP_STATUS_FORBIDDEN
1304         || msg->status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED) {
1305       GST_ELEMENT_ERROR (src, RESOURCE, NOT_AUTHORIZED, ("%s",
1306               msg->reason_phrase), ("%s (%d), URL: %s, Redirect to: %s",
1307               msg->reason_phrase, msg->status_code, src->location,
1308               GST_STR_NULL (src->redirection_uri)));
1309     } else {
1310       GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
1311           ("%s", msg->reason_phrase),
1312           ("%s (%d), URL: %s, Redirect to: %s", msg->reason_phrase,
1313               msg->status_code, src->location,
1314               GST_STR_NULL (src->redirection_uri)));
1315     }
1316     src->ret = GST_FLOW_ERROR;
1317   }
1318 }
1319
1320 static gboolean
1321 gst_soup_http_src_build_message (GstSoupHTTPSrc * src, const gchar * method)
1322 {
1323   g_return_val_if_fail (src->msg == NULL, FALSE);
1324
1325   src->msg = soup_message_new (method, src->location);
1326   if (!src->msg) {
1327     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
1328         ("Error parsing URL."), ("URL: %s", src->location));
1329     return FALSE;
1330   }
1331   if (!src->keep_alive) {
1332     soup_message_headers_append (src->msg->request_headers, "Connection",
1333         "close");
1334   }
1335   if (src->iradio_mode) {
1336     soup_message_headers_append (src->msg->request_headers, "icy-metadata",
1337         "1");
1338   }
1339   if (src->cookies) {
1340     gchar **cookie;
1341
1342     for (cookie = src->cookies; *cookie != NULL; cookie++) {
1343       soup_message_headers_append (src->msg->request_headers, "Cookie",
1344           *cookie);
1345     }
1346   }
1347
1348   soup_message_set_flags (src->msg, SOUP_MESSAGE_OVERWRITE_CHUNKS |
1349       (src->automatic_redirect ? 0 : SOUP_MESSAGE_NO_REDIRECT));
1350   gst_soup_http_src_add_range_header (src, src->request_position,
1351       src->stop_position);
1352
1353   gst_soup_http_src_add_extra_headers (src);
1354
1355   return TRUE;
1356 }
1357
1358 static GstFlowReturn
1359 gst_soup_http_src_send_message (GstSoupHTTPSrc * src)
1360 {
1361   g_return_val_if_fail (src->msg != NULL, GST_FLOW_ERROR);
1362
1363   /* FIXME We are ignoring the GError here, might be useful to debug */
1364   src->input_stream =
1365       soup_session_send (src->session, src->msg, src->cancellable, NULL);
1366   gst_soup_http_src_got_headers (src, src->msg);
1367   if (src->ret != GST_FLOW_OK) {
1368     return src->ret;
1369   }
1370
1371   if (!src->input_stream) {
1372     GST_DEBUG_OBJECT (src, "Didn't get an input stream");
1373     return GST_FLOW_ERROR;
1374   }
1375
1376   if (SOUP_STATUS_IS_SUCCESSFUL (src->msg->status_code)) {
1377     GST_DEBUG_OBJECT (src, "Successfully got a reply");
1378   } else {
1379     /* FIXME - be more helpful to people debugging */
1380     return GST_FLOW_ERROR;
1381   }
1382
1383   return GST_FLOW_OK;
1384 }
1385
1386 static GstFlowReturn
1387 gst_soup_http_src_do_request (GstSoupHTTPSrc * src, const gchar * method)
1388 {
1389   if (src->max_retries != -1 && src->retry_count > src->max_retries) {
1390     GST_DEBUG_OBJECT (src, "Max retries reached");
1391     src->ret = GST_FLOW_ERROR;
1392     return src->ret;
1393   }
1394
1395   src->retry_count++;
1396   /* EOS immediately if we have an empty segment */
1397   if (src->request_position == src->stop_position)
1398     return GST_FLOW_EOS;
1399
1400   GST_LOG_OBJECT (src, "Running request for method: %s", method);
1401
1402   /* Update the position if we are retrying */
1403   if (src->msg && (src->request_position != src->read_position)) {
1404     gst_soup_http_src_add_range_header (src, src->request_position,
1405         src->stop_position);
1406   }
1407
1408   if (!src->msg) {
1409     if (!gst_soup_http_src_build_message (src, method)) {
1410       return GST_FLOW_ERROR;
1411     }
1412   }
1413
1414   if (g_cancellable_is_cancelled (src->cancellable)) {
1415     GST_INFO_OBJECT (src, "interrupted");
1416     src->ret = GST_FLOW_FLUSHING;
1417     goto done;
1418   }
1419   src->ret = gst_soup_http_src_send_message (src);
1420
1421 done:
1422   return src->ret;
1423 }
1424
1425 static void
1426 gst_soup_http_src_update_position (GstSoupHTTPSrc * src, gint64 bytes_read)
1427 {
1428   GstBaseSrc *basesrc = GST_BASE_SRC_CAST (src);
1429   guint64 new_position;
1430
1431   new_position = src->read_position + bytes_read;
1432   if (G_LIKELY (src->request_position == src->read_position))
1433     src->request_position = new_position;
1434   src->read_position = new_position;
1435
1436   if (src->have_size) {
1437     if (new_position > src->content_size) {
1438       GST_DEBUG_OBJECT (src, "Got position previous estimated content size "
1439           "(%" G_GINT64_FORMAT " > %" G_GINT64_FORMAT ")", new_position,
1440           src->content_size);
1441       src->content_size = new_position;
1442       basesrc->segment.duration = src->content_size;
1443       gst_element_post_message (GST_ELEMENT (src),
1444           gst_message_new_duration_changed (GST_OBJECT (src)));
1445     } else if (new_position == src->content_size) {
1446       GST_DEBUG_OBJECT (src, "We're EOS now");
1447     }
1448   }
1449 }
1450
1451 static GstFlowReturn
1452 gst_soup_http_src_read_buffer (GstSoupHTTPSrc * src, GstBuffer ** outbuf)
1453 {
1454   gssize read_bytes;
1455   GstMapInfo mapinfo;
1456   GstBaseSrc *bsrc;
1457   GstFlowReturn ret;
1458
1459   bsrc = GST_BASE_SRC_CAST (src);
1460
1461   *outbuf = gst_soup_http_src_alloc_buffer (src);
1462   if (!*outbuf) {
1463     GST_WARNING_OBJECT (src, "Failed to allocate buffer");
1464     return GST_FLOW_ERROR;
1465   }
1466
1467   if (!gst_buffer_map (*outbuf, &mapinfo, GST_MAP_WRITE)) {
1468     GST_WARNING_OBJECT (src, "Failed to map buffer");
1469     return GST_FLOW_ERROR;
1470   }
1471
1472   read_bytes =
1473       g_input_stream_read (src->input_stream, mapinfo.data, mapinfo.size,
1474       src->cancellable, NULL);
1475   GST_DEBUG_OBJECT (src, "Read %" G_GSSIZE_FORMAT " bytes from http input",
1476       read_bytes);
1477
1478   g_mutex_lock (&src->mutex);
1479   if (g_cancellable_is_cancelled (src->cancellable)) {
1480     g_mutex_unlock (&src->mutex);
1481     return GST_FLOW_FLUSHING;
1482   }
1483   g_mutex_unlock (&src->mutex);
1484
1485   gst_buffer_unmap (*outbuf, &mapinfo);
1486   if (read_bytes > 0) {
1487     gst_buffer_set_size (*outbuf, read_bytes);
1488     GST_BUFFER_OFFSET (*outbuf) = bsrc->segment.position;
1489     ret = GST_FLOW_OK;
1490     gst_soup_http_src_update_position (src, read_bytes);
1491
1492     /* Got some data, reset retry counter */
1493     src->retry_count = 0;
1494   } else {
1495     gst_buffer_unref (*outbuf);
1496     if (read_bytes < 0) {
1497       /* Maybe the server disconnected, retry */
1498       ret = GST_FLOW_CUSTOM_ERROR;
1499     } else {
1500       ret = GST_FLOW_EOS;
1501       src->have_body = TRUE;
1502     }
1503   }
1504   return ret;
1505 }
1506
1507 static GstFlowReturn
1508 gst_soup_http_src_create (GstPushSrc * psrc, GstBuffer ** outbuf)
1509 {
1510   GstSoupHTTPSrc *src;
1511   GstFlowReturn ret = GST_FLOW_OK;
1512   GstEvent *http_headers_event = NULL;
1513
1514   src = GST_SOUP_HTTP_SRC (psrc);
1515
1516 retry:
1517   g_mutex_lock (&src->mutex);
1518
1519   /* Check for pending position change */
1520   if (src->request_position != src->read_position) {
1521     if (src->input_stream) {
1522       g_input_stream_close (src->input_stream, src->cancellable, NULL);
1523       g_object_unref (src->input_stream);
1524       src->input_stream = NULL;
1525     }
1526   }
1527
1528   if (g_cancellable_is_cancelled (src->cancellable)) {
1529     ret = GST_FLOW_FLUSHING;
1530     g_mutex_unlock (&src->mutex);
1531     goto done;
1532   }
1533
1534   /* If we have no open connection to the server, start one */
1535   if (!src->input_stream) {
1536     *outbuf = NULL;
1537     ret =
1538         gst_soup_http_src_do_request (src,
1539         src->method ? src->method : SOUP_METHOD_GET);
1540     http_headers_event = src->http_headers_event;
1541     src->http_headers_event = NULL;
1542   }
1543   g_mutex_unlock (&src->mutex);
1544
1545   if (ret == GST_FLOW_OK || ret == GST_FLOW_CUSTOM_ERROR) {
1546     if (http_headers_event) {
1547       gst_pad_push_event (GST_BASE_SRC_PAD (src), http_headers_event);
1548       http_headers_event = NULL;
1549     }
1550   }
1551
1552   if (ret == GST_FLOW_OK)
1553     ret = gst_soup_http_src_read_buffer (src, outbuf);
1554
1555 done:
1556   GST_DEBUG_OBJECT (src, "Returning %d %s", ret, gst_flow_get_name (ret));
1557   if (ret != GST_FLOW_OK) {
1558     if (http_headers_event)
1559       gst_event_unref (http_headers_event);
1560
1561     g_mutex_lock (&src->mutex);
1562     if (src->input_stream) {
1563       g_object_unref (src->input_stream);
1564       src->input_stream = NULL;
1565     }
1566     g_mutex_unlock (&src->mutex);
1567     if (ret == GST_FLOW_CUSTOM_ERROR)
1568       goto retry;
1569   }
1570   return ret;
1571 }
1572
1573 static gboolean
1574 gst_soup_http_src_start (GstBaseSrc * bsrc)
1575 {
1576   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
1577
1578   GST_DEBUG_OBJECT (src, "start(\"%s\")", src->location);
1579
1580   return gst_soup_http_src_session_open (src);
1581 }
1582
1583 static gboolean
1584 gst_soup_http_src_stop (GstBaseSrc * bsrc)
1585 {
1586   GstSoupHTTPSrc *src;
1587
1588   src = GST_SOUP_HTTP_SRC (bsrc);
1589   GST_DEBUG_OBJECT (src, "stop()");
1590   if (src->keep_alive && !src->msg)
1591     gst_soup_http_src_cancel_message (src);
1592   else
1593     gst_soup_http_src_session_close (src);
1594
1595   gst_soup_http_src_reset (src);
1596   return TRUE;
1597 }
1598
1599 static GstStateChangeReturn
1600 gst_soup_http_src_change_state (GstElement * element, GstStateChange transition)
1601 {
1602   GstStateChangeReturn ret;
1603   GstSoupHTTPSrc *src;
1604
1605   src = GST_SOUP_HTTP_SRC (element);
1606
1607   switch (transition) {
1608     case GST_STATE_CHANGE_READY_TO_NULL:
1609       gst_soup_http_src_session_close (src);
1610       break;
1611     default:
1612       break;
1613   }
1614
1615   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1616
1617   return ret;
1618 }
1619
1620 /* Interrupt a blocking request. */
1621 static gboolean
1622 gst_soup_http_src_unlock (GstBaseSrc * bsrc)
1623 {
1624   GstSoupHTTPSrc *src;
1625
1626   src = GST_SOUP_HTTP_SRC (bsrc);
1627   GST_DEBUG_OBJECT (src, "unlock()");
1628
1629   src->ret = GST_FLOW_FLUSHING;
1630   gst_soup_http_src_cancel_message (src);
1631   return TRUE;
1632 }
1633
1634 /* Interrupt interrupt. */
1635 static gboolean
1636 gst_soup_http_src_unlock_stop (GstBaseSrc * bsrc)
1637 {
1638   GstSoupHTTPSrc *src;
1639
1640   src = GST_SOUP_HTTP_SRC (bsrc);
1641   GST_DEBUG_OBJECT (src, "unlock_stop()");
1642
1643   src->ret = GST_FLOW_OK;
1644   g_cancellable_reset (src->cancellable);
1645   return TRUE;
1646 }
1647
1648 static gboolean
1649 gst_soup_http_src_get_size (GstBaseSrc * bsrc, guint64 * size)
1650 {
1651   GstSoupHTTPSrc *src;
1652
1653   src = GST_SOUP_HTTP_SRC (bsrc);
1654
1655   if (src->have_size) {
1656     GST_DEBUG_OBJECT (src, "get_size() = %" G_GUINT64_FORMAT,
1657         src->content_size);
1658     *size = src->content_size;
1659     return TRUE;
1660   }
1661   GST_DEBUG_OBJECT (src, "get_size() = FALSE");
1662   return FALSE;
1663 }
1664
1665 static void
1666 gst_soup_http_src_check_seekable (GstSoupHTTPSrc * src)
1667 {
1668   GstFlowReturn ret = GST_FLOW_OK;
1669
1670   /* Special case to check if the server allows range requests
1671    * before really starting to get data in the buffer creation
1672    * loops.
1673    */
1674   if (!src->got_headers && GST_STATE (src) >= GST_STATE_PAUSED) {
1675     g_mutex_lock (&src->mutex);
1676     while (!src->got_headers && !g_cancellable_is_cancelled (src->cancellable)
1677         && ret == GST_FLOW_OK) {
1678       if ((src->msg && src->msg->method != SOUP_METHOD_HEAD)) {
1679         /* wait for the current request to finish */
1680         g_cond_wait (&src->have_headers_cond, &src->mutex);
1681       } else {
1682         if (gst_soup_http_src_session_open (src)) {
1683           ret = gst_soup_http_src_do_request (src, SOUP_METHOD_HEAD);
1684         }
1685       }
1686     }
1687     if (src->ret == GST_FLOW_EOS) {
1688       /* A HEAD request shouldn't lead to EOS */
1689       src->ret = GST_FLOW_OK;
1690     }
1691     g_mutex_unlock (&src->mutex);
1692   }
1693 }
1694
1695 static gboolean
1696 gst_soup_http_src_is_seekable (GstBaseSrc * bsrc)
1697 {
1698   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
1699
1700   gst_soup_http_src_check_seekable (src);
1701
1702   return src->seekable;
1703 }
1704
1705 static gboolean
1706 gst_soup_http_src_do_seek (GstBaseSrc * bsrc, GstSegment * segment)
1707 {
1708   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
1709
1710   GST_DEBUG_OBJECT (src, "do_seek(%" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT
1711       ")", segment->start, segment->stop);
1712   if (src->read_position == segment->start &&
1713       src->request_position == src->read_position &&
1714       src->stop_position == segment->stop) {
1715     GST_DEBUG_OBJECT (src,
1716         "Seek to current read/end position and no seek pending");
1717     return TRUE;
1718   }
1719
1720   gst_soup_http_src_check_seekable (src);
1721
1722   /* If we have no headers we don't know yet if it is seekable or not.
1723    * Store the start position and error out later if it isn't */
1724   if (src->got_headers && !src->seekable) {
1725     GST_WARNING_OBJECT (src, "Not seekable");
1726     return FALSE;
1727   }
1728
1729   if (segment->rate < 0.0 || segment->format != GST_FORMAT_BYTES) {
1730     GST_WARNING_OBJECT (src, "Invalid seek segment");
1731     return FALSE;
1732   }
1733
1734   if (src->have_size && segment->start >= src->content_size) {
1735     GST_WARNING_OBJECT (src,
1736         "Potentially seeking behind end of file, might EOS immediately");
1737   }
1738
1739   /* Wait for create() to handle the jump in offset. */
1740   src->request_position = segment->start;
1741   src->stop_position = segment->stop;
1742
1743   return TRUE;
1744 }
1745
1746 static gboolean
1747 gst_soup_http_src_query (GstBaseSrc * bsrc, GstQuery * query)
1748 {
1749   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
1750   gboolean ret;
1751   GstSchedulingFlags flags;
1752   gint minsize, maxsize, align;
1753
1754   switch (GST_QUERY_TYPE (query)) {
1755     case GST_QUERY_URI:
1756       gst_query_set_uri (query, src->location);
1757       if (src->redirection_uri != NULL) {
1758         gst_query_set_uri_redirection (query, src->redirection_uri);
1759         gst_query_set_uri_redirection_permanent (query,
1760             src->redirection_permanent);
1761       }
1762       ret = TRUE;
1763       break;
1764     default:
1765       ret = FALSE;
1766       break;
1767   }
1768
1769   if (!ret)
1770     ret = GST_BASE_SRC_CLASS (parent_class)->query (bsrc, query);
1771
1772   switch (GST_QUERY_TYPE (query)) {
1773     case GST_QUERY_SCHEDULING:
1774       gst_query_parse_scheduling (query, &flags, &minsize, &maxsize, &align);
1775       flags |= GST_SCHEDULING_FLAG_BANDWIDTH_LIMITED;
1776       gst_query_set_scheduling (query, flags, minsize, maxsize, align);
1777       break;
1778     default:
1779       break;
1780   }
1781
1782   return ret;
1783 }
1784
1785 static gboolean
1786 gst_soup_http_src_set_location (GstSoupHTTPSrc * src, const gchar * uri,
1787     GError ** error)
1788 {
1789   const char *alt_schemes[] = { "icy://", "icyx://" };
1790   guint i;
1791
1792   if (src->location) {
1793     g_free (src->location);
1794     src->location = NULL;
1795   }
1796
1797   if (uri == NULL)
1798     return FALSE;
1799
1800   for (i = 0; i < G_N_ELEMENTS (alt_schemes); i++) {
1801     if (g_str_has_prefix (uri, alt_schemes[i])) {
1802       src->location =
1803           g_strdup_printf ("http://%s", uri + strlen (alt_schemes[i]));
1804       return TRUE;
1805     }
1806   }
1807
1808   if (src->redirection_uri) {
1809     g_free (src->redirection_uri);
1810     src->redirection_uri = NULL;
1811   }
1812
1813   src->location = g_strdup (uri);
1814
1815   return TRUE;
1816 }
1817
1818 static gboolean
1819 gst_soup_http_src_set_proxy (GstSoupHTTPSrc * src, const gchar * uri)
1820 {
1821   if (src->proxy) {
1822     soup_uri_free (src->proxy);
1823     src->proxy = NULL;
1824   }
1825
1826   if (uri == NULL || *uri == '\0')
1827     return TRUE;
1828
1829   if (g_str_has_prefix (uri, "http://")) {
1830     src->proxy = soup_uri_new (uri);
1831   } else {
1832     gchar *new_uri = g_strconcat ("http://", uri, NULL);
1833
1834     src->proxy = soup_uri_new (new_uri);
1835     g_free (new_uri);
1836   }
1837
1838   return (src->proxy != NULL);
1839 }
1840
1841 static guint
1842 gst_soup_http_src_uri_get_type (GType type)
1843 {
1844   return GST_URI_SRC;
1845 }
1846
1847 static const gchar *const *
1848 gst_soup_http_src_uri_get_protocols (GType type)
1849 {
1850   static const gchar *protocols[] = { "http", "https", "icy", "icyx", NULL };
1851
1852   return protocols;
1853 }
1854
1855 static gchar *
1856 gst_soup_http_src_uri_get_uri (GstURIHandler * handler)
1857 {
1858   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (handler);
1859
1860   /* FIXME: make thread-safe */
1861   return g_strdup (src->location);
1862 }
1863
1864 static gboolean
1865 gst_soup_http_src_uri_set_uri (GstURIHandler * handler, const gchar * uri,
1866     GError ** error)
1867 {
1868   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (handler);
1869
1870   return gst_soup_http_src_set_location (src, uri, error);
1871 }
1872
1873 static void
1874 gst_soup_http_src_uri_handler_init (gpointer g_iface, gpointer iface_data)
1875 {
1876   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
1877
1878   iface->get_type = gst_soup_http_src_uri_get_type;
1879   iface->get_protocols = gst_soup_http_src_uri_get_protocols;
1880   iface->get_uri = gst_soup_http_src_uri_get_uri;
1881   iface->set_uri = gst_soup_http_src_uri_set_uri;
1882 }