souphttpsrc: remove unnecessary NULL checks before g_free()
[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 /* libsoup before 2.47.0 was stealing our main context from us,
85  * so we can't reliable use it to clean up all pending resources
86  * once we're done... let's just continue leaking on old versions.
87  * https://bugzilla.gnome.org/show_bug.cgi?id=663944
88  */
89 #if defined(SOUP_MINOR_VERSION) && SOUP_MINOR_VERSION >= 47
90 #define LIBSOUP_DOES_NOT_STEAL_OUR_CONTEXT 1
91 #endif
92
93 #include <gst/tag/tag.h>
94
95 GST_DEBUG_CATEGORY_STATIC (souphttpsrc_debug);
96 #define GST_CAT_DEFAULT souphttpsrc_debug
97
98 static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src",
99     GST_PAD_SRC,
100     GST_PAD_ALWAYS,
101     GST_STATIC_CAPS_ANY);
102
103 enum
104 {
105   PROP_0,
106   PROP_LOCATION,
107   PROP_IS_LIVE,
108   PROP_USER_AGENT,
109   PROP_AUTOMATIC_REDIRECT,
110   PROP_PROXY,
111   PROP_USER_ID,
112   PROP_USER_PW,
113   PROP_PROXY_ID,
114   PROP_PROXY_PW,
115   PROP_COOKIES,
116   PROP_IRADIO_MODE,
117   PROP_TIMEOUT,
118   PROP_EXTRA_HEADERS,
119   PROP_SOUP_LOG_LEVEL,
120   PROP_COMPRESS,
121   PROP_KEEP_ALIVE,
122   PROP_SSL_STRICT,
123   PROP_SSL_CA_FILE,
124   PROP_SSL_USE_SYSTEM_CA_FILE,
125   PROP_TLS_DATABASE,
126   PROP_RETRIES,
127   PROP_METHOD
128 };
129
130 #define DEFAULT_USER_AGENT           "GStreamer souphttpsrc "
131 #define DEFAULT_IRADIO_MODE          TRUE
132 #define DEFAULT_SOUP_LOG_LEVEL       SOUP_LOGGER_LOG_HEADERS
133 #define DEFAULT_COMPRESS             FALSE
134 #define DEFAULT_KEEP_ALIVE           FALSE
135 #define DEFAULT_SSL_STRICT           TRUE
136 #define DEFAULT_SSL_CA_FILE          NULL
137 #define DEFAULT_SSL_USE_SYSTEM_CA_FILE TRUE
138 #define DEFAULT_TLS_DATABASE         NULL
139 #define DEFAULT_TIMEOUT              15
140 #define DEFAULT_RETRIES              3
141 #define DEFAULT_SOUP_METHOD          NULL
142
143 static void gst_soup_http_src_uri_handler_init (gpointer g_iface,
144     gpointer iface_data);
145 static void gst_soup_http_src_finalize (GObject * gobject);
146 static void gst_soup_http_src_dispose (GObject * gobject);
147
148 static void gst_soup_http_src_set_property (GObject * object, guint prop_id,
149     const GValue * value, GParamSpec * pspec);
150 static void gst_soup_http_src_get_property (GObject * object, guint prop_id,
151     GValue * value, GParamSpec * pspec);
152
153 static GstStateChangeReturn gst_soup_http_src_change_state (GstElement *
154     element, GstStateChange transition);
155 static GstFlowReturn gst_soup_http_src_create (GstPushSrc * psrc,
156     GstBuffer ** outbuf);
157 static gboolean gst_soup_http_src_start (GstBaseSrc * bsrc);
158 static gboolean gst_soup_http_src_stop (GstBaseSrc * bsrc);
159 static gboolean gst_soup_http_src_get_size (GstBaseSrc * bsrc, guint64 * size);
160 static gboolean gst_soup_http_src_is_seekable (GstBaseSrc * bsrc);
161 static gboolean gst_soup_http_src_do_seek (GstBaseSrc * bsrc,
162     GstSegment * segment);
163 static gboolean gst_soup_http_src_query (GstBaseSrc * bsrc, GstQuery * query);
164 static gboolean gst_soup_http_src_unlock (GstBaseSrc * bsrc);
165 static gboolean gst_soup_http_src_unlock_stop (GstBaseSrc * bsrc);
166 static gboolean gst_soup_http_src_set_location (GstSoupHTTPSrc * src,
167     const gchar * uri, GError ** error);
168 static gboolean gst_soup_http_src_set_proxy (GstSoupHTTPSrc * src,
169     const gchar * uri);
170 static char *gst_soup_http_src_unicodify (const char *str);
171 static gboolean gst_soup_http_src_build_message (GstSoupHTTPSrc * src,
172     const gchar * method);
173 static void gst_soup_http_src_cancel_message (GstSoupHTTPSrc * src);
174 static void gst_soup_http_src_queue_message (GstSoupHTTPSrc * src);
175 static gboolean gst_soup_http_src_add_range_header (GstSoupHTTPSrc * src,
176     guint64 offset, guint64 stop_offset);
177 static void gst_soup_http_src_session_unpause_message (GstSoupHTTPSrc * src);
178 static void gst_soup_http_src_session_pause_message (GstSoupHTTPSrc * src);
179 static gboolean gst_soup_http_src_session_open (GstSoupHTTPSrc * src);
180 static void gst_soup_http_src_session_close (GstSoupHTTPSrc * src);
181 static void gst_soup_http_src_parse_status (SoupMessage * msg,
182     GstSoupHTTPSrc * src);
183 static void gst_soup_http_src_chunk_free (gpointer gstbuf);
184 static SoupBuffer *gst_soup_http_src_chunk_allocator (SoupMessage * msg,
185     gsize max_len, gpointer user_data);
186 static void gst_soup_http_src_got_chunk_cb (SoupMessage * msg,
187     SoupBuffer * chunk, GstSoupHTTPSrc * src);
188 static void gst_soup_http_src_response_cb (SoupSession * session,
189     SoupMessage * msg, GstSoupHTTPSrc * src);
190 static void gst_soup_http_src_got_headers_cb (SoupMessage * msg,
191     GstSoupHTTPSrc * src);
192 static void gst_soup_http_src_got_body_cb (SoupMessage * msg,
193     GstSoupHTTPSrc * src);
194 static void gst_soup_http_src_finished_cb (SoupMessage * msg,
195     GstSoupHTTPSrc * src);
196 static void gst_soup_http_src_authenticate_cb (SoupSession * session,
197     SoupMessage * msg, SoupAuth * auth, gboolean retrying,
198     GstSoupHTTPSrc * src);
199
200 #define gst_soup_http_src_parent_class parent_class
201 G_DEFINE_TYPE_WITH_CODE (GstSoupHTTPSrc, gst_soup_http_src, GST_TYPE_PUSH_SRC,
202     G_IMPLEMENT_INTERFACE (GST_TYPE_URI_HANDLER,
203         gst_soup_http_src_uri_handler_init));
204
205 static void
206 gst_soup_http_src_class_init (GstSoupHTTPSrcClass * klass)
207 {
208   GObjectClass *gobject_class;
209   GstElementClass *gstelement_class;
210   GstBaseSrcClass *gstbasesrc_class;
211   GstPushSrcClass *gstpushsrc_class;
212
213   gobject_class = (GObjectClass *) klass;
214   gstelement_class = (GstElementClass *) klass;
215   gstbasesrc_class = (GstBaseSrcClass *) klass;
216   gstpushsrc_class = (GstPushSrcClass *) klass;
217
218   gobject_class->set_property = gst_soup_http_src_set_property;
219   gobject_class->get_property = gst_soup_http_src_get_property;
220   gobject_class->finalize = gst_soup_http_src_finalize;
221   gobject_class->dispose = gst_soup_http_src_dispose;
222
223   g_object_class_install_property (gobject_class,
224       PROP_LOCATION,
225       g_param_spec_string ("location", "Location",
226           "Location to read from", "",
227           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
228   g_object_class_install_property (gobject_class,
229       PROP_USER_AGENT,
230       g_param_spec_string ("user-agent", "User-Agent",
231           "Value of the User-Agent HTTP request header field",
232           DEFAULT_USER_AGENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
233   g_object_class_install_property (gobject_class,
234       PROP_AUTOMATIC_REDIRECT,
235       g_param_spec_boolean ("automatic-redirect", "automatic-redirect",
236           "Automatically follow HTTP redirects (HTTP Status Code 3xx)",
237           TRUE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
238   g_object_class_install_property (gobject_class,
239       PROP_PROXY,
240       g_param_spec_string ("proxy", "Proxy",
241           "HTTP proxy server URI", "",
242           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
243   g_object_class_install_property (gobject_class,
244       PROP_USER_ID,
245       g_param_spec_string ("user-id", "user-id",
246           "HTTP location URI user id for authentication", "",
247           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
248   g_object_class_install_property (gobject_class, PROP_USER_PW,
249       g_param_spec_string ("user-pw", "user-pw",
250           "HTTP location URI user password for authentication", "",
251           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
252   g_object_class_install_property (gobject_class, PROP_PROXY_ID,
253       g_param_spec_string ("proxy-id", "proxy-id",
254           "HTTP proxy URI user id for authentication", "",
255           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
256   g_object_class_install_property (gobject_class, PROP_PROXY_PW,
257       g_param_spec_string ("proxy-pw", "proxy-pw",
258           "HTTP proxy URI user password for authentication", "",
259           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
260   g_object_class_install_property (gobject_class, PROP_COOKIES,
261       g_param_spec_boxed ("cookies", "Cookies", "HTTP request cookies",
262           G_TYPE_STRV, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
263   g_object_class_install_property (gobject_class, PROP_IS_LIVE,
264       g_param_spec_boolean ("is-live", "is-live", "Act like a live source",
265           FALSE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
266   g_object_class_install_property (gobject_class, PROP_TIMEOUT,
267       g_param_spec_uint ("timeout", "timeout",
268           "Value in seconds to timeout a blocking I/O (0 = No timeout).", 0,
269           3600, DEFAULT_TIMEOUT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
270   g_object_class_install_property (gobject_class, PROP_EXTRA_HEADERS,
271       g_param_spec_boxed ("extra-headers", "Extra Headers",
272           "Extra headers to append to the HTTP request",
273           GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
274   g_object_class_install_property (gobject_class, PROP_IRADIO_MODE,
275       g_param_spec_boolean ("iradio-mode", "iradio-mode",
276           "Enable internet radio mode (ask server to send shoutcast/icecast "
277           "metadata interleaved with the actual stream data)",
278           DEFAULT_IRADIO_MODE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
279
280  /**
281    * GstSoupHTTPSrc::http-log-level:
282    *
283    * If set and > 0, captures and dumps HTTP session data as
284    * log messages if log level >= GST_LEVEL_TRACE
285    *
286    * Since: 1.4
287    */
288   g_object_class_install_property (gobject_class, PROP_SOUP_LOG_LEVEL,
289       g_param_spec_enum ("http-log-level", "HTTP log level",
290           "Set log level for soup's HTTP session log",
291           SOUP_TYPE_LOGGER_LOG_LEVEL, DEFAULT_SOUP_LOG_LEVEL,
292           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
293
294  /**
295    * GstSoupHTTPSrc::compress:
296    *
297    * If set to %TRUE, souphttpsrc will automatically handle gzip
298    * and deflate Content-Encodings. This does not make much difference
299    * and causes more load for normal media files, but makes a real
300    * difference in size for plaintext files.
301    *
302    * Since: 1.4
303    */
304   g_object_class_install_property (gobject_class, PROP_COMPRESS,
305       g_param_spec_boolean ("compress", "Compress",
306           "Allow compressed content encodings",
307           DEFAULT_COMPRESS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
308
309  /**
310    * GstSoupHTTPSrc::keep-alive:
311    *
312    * If set to %TRUE, souphttpsrc will keep alive connections when being
313    * set to READY state and only will close connections when connecting
314    * to a different server or when going to NULL state..
315    *
316    * Since: 1.4
317    */
318   g_object_class_install_property (gobject_class, PROP_KEEP_ALIVE,
319       g_param_spec_boolean ("keep-alive", "keep-alive",
320           "Use HTTP persistent connections", DEFAULT_KEEP_ALIVE,
321           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
322
323  /**
324    * GstSoupHTTPSrc::ssl-strict:
325    *
326    * If set to %TRUE, souphttpsrc will reject all SSL certificates that
327    * are considered invalid.
328    *
329    * Since: 1.4
330    */
331   g_object_class_install_property (gobject_class, PROP_SSL_STRICT,
332       g_param_spec_boolean ("ssl-strict", "SSL Strict",
333           "Strict SSL certificate checking", DEFAULT_SSL_STRICT,
334           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
335
336  /**
337    * GstSoupHTTPSrc::ssl-ca-file:
338    *
339    * A SSL anchor CA file that should be used for checking certificates
340    * instead of the system CA file.
341    *
342    * If this property is non-%NULL, #GstSoupHTTPSrc::ssl-use-system-ca-file
343    * value will be ignored.
344    *
345    * Deprecated: Use #GstSoupHTTPSrc::tls-database property instead.
346    * Since: 1.4
347    */
348   g_object_class_install_property (gobject_class, PROP_SSL_CA_FILE,
349       g_param_spec_string ("ssl-ca-file", "SSL CA File",
350           "Location of a SSL anchor CA file to use", DEFAULT_SSL_CA_FILE,
351           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
352
353  /**
354    * GstSoupHTTPSrc::ssl-use-system-ca-file:
355    *
356    * If set to %TRUE, souphttpsrc will use the system's CA file for
357    * checking certificates, unless #GstSoupHTTPSrc::ssl-ca-file or
358    * #GstSoupHTTPSrc::tls-database are non-%NULL.
359    *
360    * Since: 1.4
361    */
362   g_object_class_install_property (gobject_class, PROP_SSL_USE_SYSTEM_CA_FILE,
363       g_param_spec_boolean ("ssl-use-system-ca-file", "Use System CA File",
364           "Use system CA file", DEFAULT_SSL_USE_SYSTEM_CA_FILE,
365           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
366
367   /**
368    * GstSoupHTTPSrc::tls-database:
369    *
370    * TLS database with anchor certificate authorities used to validate
371    * the server certificate.
372    *
373    * If this property is non-%NULL, #GstSoupHTTPSrc::ssl-use-system-ca-file
374    * and #GstSoupHTTPSrc::ssl-ca-file values will be ignored.
375    *
376    * Since: 1.6
377    */
378   g_object_class_install_property (gobject_class, PROP_TLS_DATABASE,
379       g_param_spec_object ("tls-database", "TLS database",
380           "TLS database with anchor certificate authorities used to validate the server certificate",
381           G_TYPE_TLS_DATABASE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
382
383  /**
384    * GstSoupHTTPSrc::retries:
385    *
386    * Maximum number of retries until giving up.
387    *
388    * Since: 1.4
389    */
390   g_object_class_install_property (gobject_class, PROP_RETRIES,
391       g_param_spec_int ("retries", "Retries",
392           "Maximum number of retries until giving up (-1=infinite)", -1,
393           G_MAXINT, DEFAULT_RETRIES,
394           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
395
396  /**
397    * GstSoupHTTPSrc::method
398    *
399    * The HTTP method to use when making a request
400    *
401    * Since: 1.6
402    */
403   g_object_class_install_property (gobject_class, PROP_METHOD,
404       g_param_spec_string ("method", "HTTP method",
405           "The HTTP method to use (GET, HEAD, OPTIONS, etc)",
406           DEFAULT_SOUP_METHOD, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
407
408   gst_element_class_add_pad_template (gstelement_class,
409       gst_static_pad_template_get (&srctemplate));
410
411   gst_element_class_set_static_metadata (gstelement_class, "HTTP client source",
412       "Source/Network",
413       "Receive data as a client over the network via HTTP using SOUP",
414       "Wouter Cloetens <wouter@mind.be>");
415   gstelement_class->change_state =
416       GST_DEBUG_FUNCPTR (gst_soup_http_src_change_state);
417
418   gstbasesrc_class->start = GST_DEBUG_FUNCPTR (gst_soup_http_src_start);
419   gstbasesrc_class->stop = GST_DEBUG_FUNCPTR (gst_soup_http_src_stop);
420   gstbasesrc_class->unlock = GST_DEBUG_FUNCPTR (gst_soup_http_src_unlock);
421   gstbasesrc_class->unlock_stop =
422       GST_DEBUG_FUNCPTR (gst_soup_http_src_unlock_stop);
423   gstbasesrc_class->get_size = GST_DEBUG_FUNCPTR (gst_soup_http_src_get_size);
424   gstbasesrc_class->is_seekable =
425       GST_DEBUG_FUNCPTR (gst_soup_http_src_is_seekable);
426   gstbasesrc_class->do_seek = GST_DEBUG_FUNCPTR (gst_soup_http_src_do_seek);
427   gstbasesrc_class->query = GST_DEBUG_FUNCPTR (gst_soup_http_src_query);
428
429   gstpushsrc_class->create = GST_DEBUG_FUNCPTR (gst_soup_http_src_create);
430
431   GST_DEBUG_CATEGORY_INIT (souphttpsrc_debug, "souphttpsrc", 0,
432       "SOUP HTTP src");
433 }
434
435 static void
436 gst_soup_http_src_reset (GstSoupHTTPSrc * src)
437 {
438   src->interrupted = FALSE;
439   src->retry = FALSE;
440   src->retry_count = 0;
441   src->have_size = FALSE;
442   src->got_headers = FALSE;
443   src->seekable = FALSE;
444   src->read_position = 0;
445   src->request_position = 0;
446   src->stop_position = -1;
447   src->content_size = 0;
448   src->have_body = FALSE;
449
450   src->ret = GST_FLOW_OK;
451
452   gst_caps_replace (&src->src_caps, NULL);
453   g_free (src->iradio_name);
454   src->iradio_name = NULL;
455   g_free (src->iradio_genre);
456   src->iradio_genre = NULL;
457   g_free (src->iradio_url);
458   src->iradio_url = NULL;
459 }
460
461 static void
462 gst_soup_http_src_init (GstSoupHTTPSrc * src)
463 {
464   const gchar *proxy;
465
466   g_mutex_init (&src->mutex);
467   g_cond_init (&src->request_finished_cond);
468   src->location = NULL;
469   src->redirection_uri = NULL;
470   src->automatic_redirect = TRUE;
471   src->user_agent = g_strdup (DEFAULT_USER_AGENT);
472   src->user_id = NULL;
473   src->user_pw = NULL;
474   src->proxy_id = NULL;
475   src->proxy_pw = NULL;
476   src->cookies = NULL;
477   src->iradio_mode = DEFAULT_IRADIO_MODE;
478   src->loop = NULL;
479   src->context = NULL;
480   src->session = NULL;
481   src->msg = NULL;
482   src->timeout = DEFAULT_TIMEOUT;
483   src->log_level = DEFAULT_SOUP_LOG_LEVEL;
484   src->ssl_strict = DEFAULT_SSL_STRICT;
485   src->ssl_use_system_ca_file = DEFAULT_SSL_USE_SYSTEM_CA_FILE;
486   src->tls_database = DEFAULT_TLS_DATABASE;
487   src->max_retries = DEFAULT_RETRIES;
488   src->method = DEFAULT_SOUP_METHOD;
489   proxy = g_getenv ("http_proxy");
490   if (!gst_soup_http_src_set_proxy (src, proxy)) {
491     GST_WARNING_OBJECT (src,
492         "The proxy in the http_proxy env var (\"%s\") cannot be parsed.",
493         proxy);
494   }
495
496   gst_base_src_set_automatic_eos (GST_BASE_SRC (src), FALSE);
497
498   gst_soup_http_src_reset (src);
499 }
500
501 static void
502 gst_soup_http_src_dispose (GObject * gobject)
503 {
504   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (gobject);
505
506   GST_DEBUG_OBJECT (src, "dispose");
507
508   gst_soup_http_src_session_close (src);
509
510   G_OBJECT_CLASS (parent_class)->dispose (gobject);
511 }
512
513 static void
514 gst_soup_http_src_finalize (GObject * gobject)
515 {
516   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (gobject);
517
518   GST_DEBUG_OBJECT (src, "finalize");
519
520   g_mutex_clear (&src->mutex);
521   g_cond_clear (&src->request_finished_cond);
522   g_free (src->location);
523   g_free (src->redirection_uri);
524   g_free (src->user_agent);
525   if (src->proxy != NULL) {
526     soup_uri_free (src->proxy);
527   }
528   g_free (src->user_id);
529   g_free (src->user_pw);
530   g_free (src->proxy_id);
531   g_free (src->proxy_pw);
532   g_strfreev (src->cookies);
533
534   if (src->extra_headers) {
535     gst_structure_free (src->extra_headers);
536     src->extra_headers = NULL;
537   }
538
539   g_free (src->ssl_ca_file);
540
541   if (src->tls_database)
542     g_object_unref (src->tls_database);
543   g_free (src->method);
544
545   G_OBJECT_CLASS (parent_class)->finalize (gobject);
546 }
547
548 static void
549 gst_soup_http_src_set_property (GObject * object, guint prop_id,
550     const GValue * value, GParamSpec * pspec)
551 {
552   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (object);
553
554   switch (prop_id) {
555     case PROP_LOCATION:
556     {
557       const gchar *location;
558
559       location = g_value_get_string (value);
560
561       if (location == NULL) {
562         GST_WARNING ("location property cannot be NULL");
563         goto done;
564       }
565       if (!gst_soup_http_src_set_location (src, location, NULL)) {
566         GST_WARNING ("badly formatted location");
567         goto done;
568       }
569       break;
570     }
571     case PROP_USER_AGENT:
572       g_free (src->user_agent);
573       src->user_agent = g_value_dup_string (value);
574       break;
575     case PROP_IRADIO_MODE:
576       src->iradio_mode = g_value_get_boolean (value);
577       break;
578     case PROP_AUTOMATIC_REDIRECT:
579       src->automatic_redirect = g_value_get_boolean (value);
580       break;
581     case PROP_PROXY:
582     {
583       const gchar *proxy;
584
585       proxy = g_value_get_string (value);
586       if (!gst_soup_http_src_set_proxy (src, proxy)) {
587         GST_WARNING ("badly formatted proxy URI");
588         goto done;
589       }
590       break;
591     }
592     case PROP_COOKIES:
593       g_strfreev (src->cookies);
594       src->cookies = g_strdupv (g_value_get_boxed (value));
595       break;
596     case PROP_IS_LIVE:
597       gst_base_src_set_live (GST_BASE_SRC (src), g_value_get_boolean (value));
598       break;
599     case PROP_USER_ID:
600       g_free (src->user_id);
601       src->user_id = g_value_dup_string (value);
602       break;
603     case PROP_USER_PW:
604       g_free (src->user_pw);
605       src->user_pw = g_value_dup_string (value);
606       break;
607     case PROP_PROXY_ID:
608       g_free (src->proxy_id);
609       src->proxy_id = g_value_dup_string (value);
610       break;
611     case PROP_PROXY_PW:
612       g_free (src->proxy_pw);
613       src->proxy_pw = g_value_dup_string (value);
614       break;
615     case PROP_TIMEOUT:
616       src->timeout = g_value_get_uint (value);
617       break;
618     case PROP_EXTRA_HEADERS:{
619       const GstStructure *s = gst_value_get_structure (value);
620
621       if (src->extra_headers)
622         gst_structure_free (src->extra_headers);
623
624       src->extra_headers = s ? gst_structure_copy (s) : NULL;
625       break;
626     }
627     case PROP_SOUP_LOG_LEVEL:
628       src->log_level = g_value_get_enum (value);
629       break;
630     case PROP_COMPRESS:
631       src->compress = g_value_get_boolean (value);
632       break;
633     case PROP_KEEP_ALIVE:
634       src->keep_alive = g_value_get_boolean (value);
635       break;
636     case PROP_SSL_STRICT:
637       src->ssl_strict = g_value_get_boolean (value);
638       break;
639     case PROP_SSL_CA_FILE:
640       g_free (src->ssl_ca_file);
641       src->ssl_ca_file = g_value_dup_string (value);
642       break;
643     case PROP_SSL_USE_SYSTEM_CA_FILE:
644       src->ssl_use_system_ca_file = g_value_get_boolean (value);
645       break;
646     case PROP_TLS_DATABASE:
647       g_clear_object (&src->tls_database);
648       src->tls_database = g_value_dup_object (value);
649       break;
650     case PROP_RETRIES:
651       src->max_retries = g_value_get_int (value);
652       break;
653     case PROP_METHOD:
654       g_free (src->method);
655       src->method = g_value_dup_string (value);
656       break;
657     default:
658       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
659       break;
660   }
661 done:
662   return;
663 }
664
665 static void
666 gst_soup_http_src_get_property (GObject * object, guint prop_id,
667     GValue * value, GParamSpec * pspec)
668 {
669   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (object);
670
671   switch (prop_id) {
672     case PROP_LOCATION:
673       g_value_set_string (value, src->location);
674       break;
675     case PROP_USER_AGENT:
676       g_value_set_string (value, src->user_agent);
677       break;
678     case PROP_AUTOMATIC_REDIRECT:
679       g_value_set_boolean (value, src->automatic_redirect);
680       break;
681     case PROP_PROXY:
682       if (src->proxy == NULL)
683         g_value_set_static_string (value, "");
684       else {
685         char *proxy = soup_uri_to_string (src->proxy, FALSE);
686
687         g_value_set_string (value, proxy);
688         g_free (proxy);
689       }
690       break;
691     case PROP_COOKIES:
692       g_value_set_boxed (value, g_strdupv (src->cookies));
693       break;
694     case PROP_IS_LIVE:
695       g_value_set_boolean (value, gst_base_src_is_live (GST_BASE_SRC (src)));
696       break;
697     case PROP_IRADIO_MODE:
698       g_value_set_boolean (value, src->iradio_mode);
699       break;
700     case PROP_USER_ID:
701       g_value_set_string (value, src->user_id);
702       break;
703     case PROP_USER_PW:
704       g_value_set_string (value, src->user_pw);
705       break;
706     case PROP_PROXY_ID:
707       g_value_set_string (value, src->proxy_id);
708       break;
709     case PROP_PROXY_PW:
710       g_value_set_string (value, src->proxy_pw);
711       break;
712     case PROP_TIMEOUT:
713       g_value_set_uint (value, src->timeout);
714       break;
715     case PROP_EXTRA_HEADERS:
716       gst_value_set_structure (value, src->extra_headers);
717       break;
718     case PROP_SOUP_LOG_LEVEL:
719       g_value_set_enum (value, src->log_level);
720       break;
721     case PROP_COMPRESS:
722       g_value_set_boolean (value, src->compress);
723       break;
724     case PROP_KEEP_ALIVE:
725       g_value_set_boolean (value, src->keep_alive);
726       break;
727     case PROP_SSL_STRICT:
728       g_value_set_boolean (value, src->ssl_strict);
729       break;
730     case PROP_SSL_CA_FILE:
731       g_value_set_string (value, src->ssl_ca_file);
732       break;
733     case PROP_SSL_USE_SYSTEM_CA_FILE:
734       g_value_set_boolean (value, src->ssl_use_system_ca_file);
735       break;
736     case PROP_TLS_DATABASE:
737       g_value_set_object (value, src->tls_database);
738       break;
739     case PROP_RETRIES:
740       g_value_set_int (value, src->max_retries);
741       break;
742     case PROP_METHOD:
743       g_value_set_string (value, src->method);
744       break;
745     default:
746       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
747       break;
748   }
749 }
750
751 static gchar *
752 gst_soup_http_src_unicodify (const gchar * str)
753 {
754   const gchar *env_vars[] = { "GST_ICY_TAG_ENCODING",
755     "GST_TAG_ENCODING", NULL
756   };
757
758   return gst_tag_freeform_string_to_utf8 (str, -1, env_vars);
759 }
760
761 static void
762 gst_soup_http_src_cancel_message (GstSoupHTTPSrc * src)
763 {
764   if (src->msg != NULL) {
765     GST_INFO_OBJECT (src, "Cancelling message");
766     src->session_io_status = GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_CANCELLED;
767     soup_session_cancel_message (src->session, src->msg, SOUP_STATUS_CANCELLED);
768   }
769   src->session_io_status = GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_IDLE;
770   src->msg = NULL;
771 }
772
773 static void
774 gst_soup_http_src_queue_message (GstSoupHTTPSrc * src)
775 {
776   soup_session_queue_message (src->session, src->msg,
777       (SoupSessionCallback) gst_soup_http_src_response_cb, src);
778   src->session_io_status = GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_QUEUED;
779 }
780
781 static gboolean
782 gst_soup_http_src_add_range_header (GstSoupHTTPSrc * src, guint64 offset,
783     guint64 stop_offset)
784 {
785   gchar buf[64];
786   gint rc;
787
788   soup_message_headers_remove (src->msg->request_headers, "Range");
789   if (offset || stop_offset != -1) {
790     if (stop_offset != -1) {
791       g_assert (offset != stop_offset);
792
793       rc = g_snprintf (buf, sizeof (buf), "bytes=%" G_GUINT64_FORMAT "-%"
794           G_GUINT64_FORMAT, offset, (stop_offset > 0) ? stop_offset - 1 :
795           stop_offset);
796     } else {
797       rc = g_snprintf (buf, sizeof (buf), "bytes=%" G_GUINT64_FORMAT "-",
798           offset);
799     }
800     if (rc > sizeof (buf) || rc < 0)
801       return FALSE;
802     soup_message_headers_append (src->msg->request_headers, "Range", buf);
803   }
804   src->read_position = offset;
805   return TRUE;
806 }
807
808 static gboolean
809 _append_extra_header (GQuark field_id, const GValue * value, gpointer user_data)
810 {
811   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (user_data);
812   const gchar *field_name = g_quark_to_string (field_id);
813   gchar *field_content = NULL;
814
815   if (G_VALUE_TYPE (value) == G_TYPE_STRING) {
816     field_content = g_value_dup_string (value);
817   } else {
818     GValue dest = { 0, };
819
820     g_value_init (&dest, G_TYPE_STRING);
821     if (g_value_transform (value, &dest)) {
822       field_content = g_value_dup_string (&dest);
823     }
824   }
825
826   if (field_content == NULL) {
827     GST_ERROR_OBJECT (src, "extra-headers field '%s' contains no value "
828         "or can't be converted to a string", field_name);
829     return FALSE;
830   }
831
832   GST_DEBUG_OBJECT (src, "Appending extra header: \"%s: %s\"", field_name,
833       field_content);
834   soup_message_headers_append (src->msg->request_headers, field_name,
835       field_content);
836
837   g_free (field_content);
838
839   return TRUE;
840 }
841
842 static gboolean
843 _append_extra_headers (GQuark field_id, const GValue * value,
844     gpointer user_data)
845 {
846   if (G_VALUE_TYPE (value) == GST_TYPE_ARRAY) {
847     guint n = gst_value_array_get_size (value);
848     guint i;
849
850     for (i = 0; i < n; i++) {
851       const GValue *v = gst_value_array_get_value (value, i);
852
853       if (!_append_extra_header (field_id, v, user_data))
854         return FALSE;
855     }
856   } else if (G_VALUE_TYPE (value) == GST_TYPE_LIST) {
857     guint n = gst_value_list_get_size (value);
858     guint i;
859
860     for (i = 0; i < n; i++) {
861       const GValue *v = gst_value_list_get_value (value, i);
862
863       if (!_append_extra_header (field_id, v, user_data))
864         return FALSE;
865     }
866   } else {
867     return _append_extra_header (field_id, value, user_data);
868   }
869
870   return TRUE;
871 }
872
873
874 static gboolean
875 gst_soup_http_src_add_extra_headers (GstSoupHTTPSrc * src)
876 {
877   if (!src->extra_headers)
878     return TRUE;
879
880   return gst_structure_foreach (src->extra_headers, _append_extra_headers, src);
881 }
882
883
884 static void
885 gst_soup_http_src_session_unpause_message (GstSoupHTTPSrc * src)
886 {
887   soup_session_unpause_message (src->session, src->msg);
888 }
889
890 static void
891 gst_soup_http_src_session_pause_message (GstSoupHTTPSrc * src)
892 {
893   soup_session_pause_message (src->session, src->msg);
894 }
895
896 static gboolean
897 gst_soup_http_src_session_open (GstSoupHTTPSrc * src)
898 {
899   if (src->session) {
900     GST_DEBUG_OBJECT (src, "Session is already open");
901     return TRUE;
902   }
903
904   if (!src->location) {
905     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (_("No URL set.")),
906         ("Missing location property"));
907     return FALSE;
908   }
909
910   if (!src->context)
911     src->context = g_main_context_new ();
912
913   if (!src->loop)
914     src->loop = g_main_loop_new (src->context, TRUE);
915   if (!src->loop) {
916     GST_ELEMENT_ERROR (src, LIBRARY, INIT,
917         (NULL), ("Failed to start GMainLoop"));
918     g_main_context_unref (src->context);
919     return FALSE;
920   }
921
922   if (!src->session) {
923     GST_DEBUG_OBJECT (src, "Creating session");
924     if (src->proxy == NULL) {
925       src->session =
926           soup_session_async_new_with_options (SOUP_SESSION_ASYNC_CONTEXT,
927           src->context, SOUP_SESSION_USER_AGENT, src->user_agent,
928           SOUP_SESSION_TIMEOUT, src->timeout,
929           SOUP_SESSION_SSL_STRICT, src->ssl_strict,
930           SOUP_SESSION_ADD_FEATURE_BY_TYPE, SOUP_TYPE_PROXY_RESOLVER_DEFAULT,
931           NULL);
932     } else {
933       src->session =
934           soup_session_async_new_with_options (SOUP_SESSION_ASYNC_CONTEXT,
935           src->context, SOUP_SESSION_PROXY_URI, src->proxy,
936           SOUP_SESSION_TIMEOUT, src->timeout,
937           SOUP_SESSION_SSL_STRICT, src->ssl_strict,
938           SOUP_SESSION_USER_AGENT, src->user_agent, NULL);
939     }
940
941     if (!src->session) {
942       GST_ELEMENT_ERROR (src, LIBRARY, INIT,
943           (NULL), ("Failed to create async session"));
944       return FALSE;
945     }
946
947     g_signal_connect (src->session, "authenticate",
948         G_CALLBACK (gst_soup_http_src_authenticate_cb), src);
949
950     /* Set up logging */
951     gst_soup_util_log_setup (src->session, src->log_level, GST_ELEMENT (src));
952     if (src->tls_database)
953       g_object_set (src->session, "tls-database", src->tls_database, NULL);
954     else if (src->ssl_ca_file)
955       g_object_set (src->session, "ssl-ca-file", src->ssl_ca_file, NULL);
956     else
957       g_object_set (src->session, "ssl-use-system-ca-file",
958           src->ssl_use_system_ca_file, NULL);
959   } else {
960     GST_DEBUG_OBJECT (src, "Re-using session");
961   }
962
963   if (src->compress)
964     soup_session_add_feature_by_type (src->session, SOUP_TYPE_CONTENT_DECODER);
965   else
966     soup_session_remove_feature_by_type (src->session,
967         SOUP_TYPE_CONTENT_DECODER);
968
969   return TRUE;
970 }
971
972 #ifdef LIBSOUP_DOES_NOT_STEAL_OUR_CONTEXT
973 static gboolean
974 dummy_idle_cb (gpointer data)
975 {
976   return FALSE /* Idle source is removed */ ;
977 }
978 #endif
979
980 static void
981 gst_soup_http_src_session_close (GstSoupHTTPSrc * src)
982 {
983   GST_DEBUG_OBJECT (src, "Closing session");
984
985   if (src->loop)
986     g_main_loop_quit (src->loop);
987
988   g_mutex_lock (&src->mutex);
989   if (src->session) {
990     soup_session_abort (src->session);  /* This unrefs the message. */
991     g_object_unref (src->session);
992     src->session = NULL;
993     src->msg = NULL;
994   }
995   if (src->loop) {
996 #ifdef LIBSOUP_DOES_NOT_STEAL_OUR_CONTEXT
997     GSource *idle_source;
998
999     /* Iterating the main context to give GIO cancellables a chance
1000      * to initiate cleanups. Wihout this, resources allocated by
1001      * libsoup for the connection are not released and socket fd is
1002      * leaked. */
1003     idle_source = g_idle_source_new ();
1004     /* Suppressing "idle souce without callback" warning */
1005     g_source_set_callback (idle_source, dummy_idle_cb, NULL, NULL);
1006     g_source_set_priority (idle_source, G_PRIORITY_LOW);
1007     g_source_attach (idle_source, src->context);
1008     /* Acquiring the context. Idle source guarantees that we'll not block. */
1009     g_main_context_push_thread_default (src->context);
1010     g_main_context_iteration (src->context, TRUE);
1011     /* Ensuring that there's no unhandled pending events left. */
1012     while (g_main_context_iteration (src->context, FALSE));
1013     g_main_context_pop_thread_default (src->context);
1014     g_source_unref (idle_source);
1015 #endif
1016
1017     g_main_loop_unref (src->loop);
1018     g_main_context_unref (src->context);
1019     src->loop = NULL;
1020     src->context = NULL;
1021   }
1022   g_mutex_unlock (&src->mutex);
1023 }
1024
1025 static void
1026 gst_soup_http_src_authenticate_cb (SoupSession * session, SoupMessage * msg,
1027     SoupAuth * auth, gboolean retrying, GstSoupHTTPSrc * src)
1028 {
1029   if (!retrying) {
1030     /* First time authentication only, if we fail and are called again with retry true fall through */
1031     if (msg->status_code == SOUP_STATUS_UNAUTHORIZED) {
1032       if (src->user_id && src->user_pw)
1033         soup_auth_authenticate (auth, src->user_id, src->user_pw);
1034     } else if (msg->status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED) {
1035       if (src->proxy_id && src->proxy_pw)
1036         soup_auth_authenticate (auth, src->proxy_id, src->proxy_pw);
1037     }
1038   }
1039 }
1040
1041 static void
1042 insert_http_header (const gchar * name, const gchar * value, gpointer user_data)
1043 {
1044   GstStructure *headers = user_data;
1045   const GValue *gv;
1046
1047   gv = gst_structure_get_value (headers, name);
1048   if (gv && GST_VALUE_HOLDS_ARRAY (gv)) {
1049     GValue v = G_VALUE_INIT;
1050
1051     g_value_init (&v, G_TYPE_STRING);
1052     g_value_set_string (&v, value);
1053     gst_value_array_append_value ((GValue *) gv, &v);
1054     g_value_unset (&v);
1055   } else if (gv && G_VALUE_HOLDS_STRING (gv)) {
1056     GValue arr = G_VALUE_INIT;
1057     GValue v = G_VALUE_INIT;
1058     const gchar *old_value = g_value_get_string (gv);
1059
1060     g_value_init (&arr, GST_TYPE_ARRAY);
1061     g_value_init (&v, G_TYPE_STRING);
1062     g_value_set_string (&v, old_value);
1063     gst_value_array_append_value (&arr, &v);
1064     g_value_set_string (&v, value);
1065     gst_value_array_append_value (&arr, &v);
1066
1067     gst_structure_set_value (headers, name, &arr);
1068     g_value_unset (&v);
1069     g_value_unset (&arr);
1070   } else {
1071     gst_structure_set (headers, name, G_TYPE_STRING, value, NULL);
1072   }
1073 }
1074
1075 static void
1076 gst_soup_http_src_got_headers_cb (SoupMessage * msg, GstSoupHTTPSrc * src)
1077 {
1078   const char *value;
1079   GstTagList *tag_list;
1080   GstBaseSrc *basesrc;
1081   guint64 newsize;
1082   GHashTable *params = NULL;
1083   GstEvent *http_headers_event;
1084   GstStructure *http_headers, *headers;
1085   const gchar *accept_ranges;
1086
1087   GST_INFO_OBJECT (src, "got headers");
1088
1089   if (msg->status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED &&
1090       src->proxy_id && src->proxy_pw)
1091     return;
1092
1093   if (src->automatic_redirect && SOUP_STATUS_IS_REDIRECTION (msg->status_code)) {
1094     src->redirection_uri = g_strdup (soup_message_headers_get_one
1095         (msg->response_headers, "Location"));
1096     src->redirection_permanent =
1097         (msg->status_code == SOUP_STATUS_MOVED_PERMANENTLY);
1098     GST_DEBUG_OBJECT (src, "%u redirect to \"%s\" (permanent %d)",
1099         msg->status_code, src->redirection_uri, src->redirection_permanent);
1100     return;
1101   }
1102
1103   if (msg->status_code == SOUP_STATUS_UNAUTHORIZED)
1104     return;
1105
1106   src->session_io_status = GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING;
1107   src->got_headers = TRUE;
1108
1109   http_headers = gst_structure_new_empty ("http-headers");
1110   gst_structure_set (http_headers, "uri", G_TYPE_STRING, src->location, NULL);
1111   if (src->redirection_uri)
1112     gst_structure_set (http_headers, "redirection-uri", G_TYPE_STRING,
1113         src->redirection_uri, NULL);
1114   headers = gst_structure_new_empty ("request-headers");
1115   soup_message_headers_foreach (msg->request_headers, insert_http_header,
1116       headers);
1117   gst_structure_set (http_headers, "request-headers", GST_TYPE_STRUCTURE,
1118       headers, NULL);
1119   gst_structure_free (headers);
1120   headers = gst_structure_new_empty ("response-headers");
1121   soup_message_headers_foreach (msg->response_headers, insert_http_header,
1122       headers);
1123   gst_structure_set (http_headers, "response-headers", GST_TYPE_STRUCTURE,
1124       headers, NULL);
1125   gst_structure_free (headers);
1126
1127   http_headers_event =
1128       gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM_STICKY, http_headers);
1129   gst_event_replace (&src->http_headers_event, http_headers_event);
1130   gst_event_unref (http_headers_event);
1131
1132   /* Parse Content-Length. */
1133   if (soup_message_headers_get_encoding (msg->response_headers) ==
1134       SOUP_ENCODING_CONTENT_LENGTH) {
1135     newsize = src->request_position +
1136         soup_message_headers_get_content_length (msg->response_headers);
1137     if (!src->have_size || (src->content_size != newsize)) {
1138       src->content_size = newsize;
1139       src->have_size = TRUE;
1140       src->seekable = TRUE;
1141       GST_DEBUG_OBJECT (src, "size = %" G_GUINT64_FORMAT, src->content_size);
1142
1143       basesrc = GST_BASE_SRC_CAST (src);
1144       basesrc->segment.duration = src->content_size;
1145       gst_element_post_message (GST_ELEMENT (src),
1146           gst_message_new_duration_changed (GST_OBJECT (src)));
1147     }
1148   }
1149
1150   /* If the server reports Accept-Ranges: none we don't have to try
1151    * doing range requests at all
1152    */
1153   if ((accept_ranges =
1154           soup_message_headers_get_one (msg->response_headers,
1155               "Accept-Ranges"))) {
1156     if (g_ascii_strcasecmp (accept_ranges, "none") == 0)
1157       src->seekable = FALSE;
1158   }
1159
1160   /* Icecast stuff */
1161   tag_list = gst_tag_list_new_empty ();
1162
1163   if ((value =
1164           soup_message_headers_get_one (msg->response_headers,
1165               "icy-metaint")) != NULL) {
1166     gint icy_metaint = atoi (value);
1167
1168     GST_DEBUG_OBJECT (src, "icy-metaint: %s (parsed: %d)", value, icy_metaint);
1169     if (icy_metaint > 0) {
1170       if (src->src_caps)
1171         gst_caps_unref (src->src_caps);
1172
1173       src->src_caps = gst_caps_new_simple ("application/x-icy",
1174           "metadata-interval", G_TYPE_INT, icy_metaint, NULL);
1175
1176       gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps);
1177     }
1178   }
1179   if ((value =
1180           soup_message_headers_get_content_type (msg->response_headers,
1181               &params)) != NULL) {
1182     GST_DEBUG_OBJECT (src, "Content-Type: %s", value);
1183     if (g_ascii_strcasecmp (value, "audio/L16") == 0) {
1184       gint channels = 2;
1185       gint rate = 44100;
1186       char *param;
1187
1188       if (src->src_caps)
1189         gst_caps_unref (src->src_caps);
1190
1191       param = g_hash_table_lookup (params, "channels");
1192       if (param != NULL)
1193         channels = atol (param);
1194
1195       param = g_hash_table_lookup (params, "rate");
1196       if (param != NULL)
1197         rate = atol (param);
1198
1199       src->src_caps = gst_caps_new_simple ("audio/x-raw",
1200           "format", G_TYPE_STRING, "S16BE",
1201           "layout", G_TYPE_STRING, "interleaved",
1202           "channels", G_TYPE_INT, channels, "rate", G_TYPE_INT, rate, NULL);
1203
1204       gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps);
1205     } else {
1206       /* Set the Content-Type field on the caps */
1207       if (src->src_caps) {
1208         src->src_caps = gst_caps_make_writable (src->src_caps);
1209         gst_caps_set_simple (src->src_caps, "content-type", G_TYPE_STRING,
1210             value, NULL);
1211         gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps);
1212       }
1213     }
1214   }
1215
1216   if (params != NULL)
1217     g_hash_table_destroy (params);
1218
1219   if ((value =
1220           soup_message_headers_get_one (msg->response_headers,
1221               "icy-name")) != NULL) {
1222     g_free (src->iradio_name);
1223     src->iradio_name = gst_soup_http_src_unicodify (value);
1224     if (src->iradio_name) {
1225       gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_ORGANIZATION,
1226           src->iradio_name, NULL);
1227     }
1228   }
1229   if ((value =
1230           soup_message_headers_get_one (msg->response_headers,
1231               "icy-genre")) != NULL) {
1232     g_free (src->iradio_genre);
1233     src->iradio_genre = gst_soup_http_src_unicodify (value);
1234     if (src->iradio_genre) {
1235       gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_GENRE,
1236           src->iradio_genre, NULL);
1237     }
1238   }
1239   if ((value = soup_message_headers_get_one (msg->response_headers, "icy-url"))
1240       != NULL) {
1241     g_free (src->iradio_url);
1242     src->iradio_url = gst_soup_http_src_unicodify (value);
1243     if (src->iradio_url) {
1244       gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_LOCATION,
1245           src->iradio_url, NULL);
1246     }
1247   }
1248   if (!gst_tag_list_is_empty (tag_list)) {
1249     GST_DEBUG_OBJECT (src,
1250         "calling gst_element_found_tags with %" GST_PTR_FORMAT, tag_list);
1251     gst_pad_push_event (GST_BASE_SRC_PAD (src), gst_event_new_tag (tag_list));
1252   } else {
1253     gst_tag_list_unref (tag_list);
1254   }
1255
1256   /* Handle HTTP errors. */
1257   gst_soup_http_src_parse_status (msg, src);
1258
1259   /* Check if Range header was respected. */
1260   if (src->ret == GST_FLOW_CUSTOM_ERROR &&
1261       src->read_position && msg->status_code != SOUP_STATUS_PARTIAL_CONTENT) {
1262     src->seekable = FALSE;
1263     GST_ELEMENT_ERROR (src, RESOURCE, SEEK,
1264         (_("Server does not support seeking.")),
1265         ("Server does not accept Range HTTP header, URL: %s, Redirect to: %s",
1266             src->location, GST_STR_NULL (src->redirection_uri)));
1267     src->ret = GST_FLOW_ERROR;
1268   }
1269
1270   /* If we are going to error out, stop all processing right here, so we
1271    * don't output any data (such as an error html page), and return
1272    * GST_FLOW_ERROR from the create function instead of having
1273    * got_chunk_cb overwrite src->ret with FLOW_OK again. */
1274   if (src->ret == GST_FLOW_ERROR || src->ret == GST_FLOW_EOS) {
1275     gst_soup_http_src_session_pause_message (src);
1276
1277     if (src->loop)
1278       g_main_loop_quit (src->loop);
1279   }
1280   g_cond_signal (&src->request_finished_cond);
1281 }
1282
1283 /* Have body. Signal EOS. */
1284 static void
1285 gst_soup_http_src_got_body_cb (SoupMessage * msg, GstSoupHTTPSrc * src)
1286 {
1287   if (G_UNLIKELY (msg != src->msg)) {
1288     GST_DEBUG_OBJECT (src, "got body, but not for current message");
1289     return;
1290   }
1291   if (G_UNLIKELY (src->session_io_status !=
1292           GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING)) {
1293     /* Probably a redirect. */
1294     return;
1295   }
1296   GST_DEBUG_OBJECT (src, "got body");
1297   src->ret = GST_FLOW_EOS;
1298   src->have_body = TRUE;
1299
1300   /* no need to interrupt the message here, we do it on the
1301    * finished_cb anyway if needed. And getting the body might mean
1302    * that the connection was hang up before finished. This happens when
1303    * the pipeline is stalled for too long (long pauses during playback).
1304    * Best to let it continue from here and pause because it reached the
1305    * final bytes based on content_size or received an out of range error */
1306 }
1307
1308 /* Finished. Signal EOS. */
1309 static void
1310 gst_soup_http_src_finished_cb (SoupMessage * msg, GstSoupHTTPSrc * src)
1311 {
1312   if (G_UNLIKELY (msg != src->msg)) {
1313     GST_DEBUG_OBJECT (src, "finished, but not for current message");
1314     return;
1315   }
1316   GST_INFO_OBJECT (src, "finished, io status: %d", src->session_io_status);
1317   src->ret = GST_FLOW_EOS;
1318   if (src->session_io_status == GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_CANCELLED) {
1319     /* gst_soup_http_src_cancel_message() triggered this; probably a seek
1320      * that occurred in the QUEUEING state; i.e. before the connection setup
1321      * was complete. Do nothing */
1322     GST_DEBUG_OBJECT (src, "cancelled");
1323   } else if (src->session_io_status ==
1324       GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING && src->read_position > 0 &&
1325       (src->have_size && src->read_position < src->content_size) &&
1326       (src->max_retries == -1 || src->retry_count < src->max_retries)) {
1327     /* The server disconnected while streaming. Reconnect and seeking to the
1328      * last location. */
1329     src->retry = TRUE;
1330     src->retry_count++;
1331     src->ret = GST_FLOW_CUSTOM_ERROR;
1332   } else if (G_UNLIKELY (src->session_io_status !=
1333           GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING)) {
1334     if (msg->method == SOUP_METHOD_HEAD) {
1335       GST_DEBUG_OBJECT (src, "Ignoring error %d:%s during HEAD request",
1336           msg->status_code, msg->reason_phrase);
1337     } else {
1338       gst_soup_http_src_parse_status (msg, src);
1339     }
1340   }
1341   if (src->loop)
1342     g_main_loop_quit (src->loop);
1343   g_cond_signal (&src->request_finished_cond);
1344 }
1345
1346 /* Buffer lifecycle management.
1347  *
1348  * gst_soup_http_src_create() runs the GMainLoop for this element, to let
1349  * Soup take control.
1350  * A GstBuffer is allocated in gst_soup_http_src_chunk_allocator() and
1351  * associated with a SoupBuffer.
1352  * Soup reads HTTP data in the GstBuffer's data buffer.
1353  * The gst_soup_http_src_got_chunk_cb() is then called with the SoupBuffer.
1354  * That sets gst_soup_http_src_create()'s return argument to the GstBuffer,
1355  * increments its refcount (to 2), pauses the flow of data from the HTTP
1356  * source to prevent gst_soup_http_src_got_chunk_cb() from being called
1357  * again and breaks out of the GMainLoop.
1358  * Because the SOUP_MESSAGE_OVERWRITE_CHUNKS flag is set, Soup frees the
1359  * SoupBuffer and calls gst_soup_http_src_chunk_free(), which decrements the
1360  * refcount (to 1).
1361  * gst_soup_http_src_create() returns the GstBuffer. It will be freed by a
1362  * downstream element.
1363  * If Soup fails to read HTTP data, it does not call
1364  * gst_soup_http_src_got_chunk_cb(), but still frees the SoupBuffer and
1365  * calls gst_soup_http_src_chunk_free(), which decrements the GstBuffer's
1366  * refcount to 0, freeing it.
1367  */
1368
1369 typedef struct
1370 {
1371   GstBuffer *buffer;
1372   GstMapInfo map;
1373 } SoupGstChunk;
1374
1375 static void
1376 gst_soup_http_src_chunk_free (gpointer user_data)
1377 {
1378   SoupGstChunk *chunk = (SoupGstChunk *) user_data;
1379
1380   gst_buffer_unmap (chunk->buffer, &chunk->map);
1381   gst_buffer_unref (chunk->buffer);
1382   g_slice_free (SoupGstChunk, chunk);
1383 }
1384
1385 static SoupBuffer *
1386 gst_soup_http_src_chunk_allocator (SoupMessage * msg, gsize max_len,
1387     gpointer user_data)
1388 {
1389   GstSoupHTTPSrc *src = (GstSoupHTTPSrc *) user_data;
1390   GstBaseSrc *basesrc = GST_BASE_SRC_CAST (src);
1391   GstBuffer *gstbuf;
1392   SoupBuffer *soupbuf;
1393   gsize length;
1394   GstFlowReturn rc;
1395   SoupGstChunk *chunk;
1396
1397   if (max_len)
1398     length = MIN (basesrc->blocksize, max_len);
1399   else
1400     length = basesrc->blocksize;
1401   GST_DEBUG_OBJECT (src, "alloc %" G_GSIZE_FORMAT " bytes <= %" G_GSIZE_FORMAT,
1402       length, max_len);
1403
1404   rc = GST_BASE_SRC_CLASS (parent_class)->alloc (basesrc, -1, length, &gstbuf);
1405   if (G_UNLIKELY (rc != GST_FLOW_OK)) {
1406     /* Failed to allocate buffer. Stall SoupSession and return error code
1407      * to create(). */
1408     src->ret = rc;
1409     g_main_loop_quit (src->loop);
1410     return NULL;
1411   }
1412
1413   chunk = g_slice_new0 (SoupGstChunk);
1414   chunk->buffer = gstbuf;
1415   gst_buffer_map (gstbuf, &chunk->map, GST_MAP_READWRITE);
1416
1417   soupbuf = soup_buffer_new_with_owner (chunk->map.data, chunk->map.size,
1418       chunk, gst_soup_http_src_chunk_free);
1419
1420   return soupbuf;
1421 }
1422
1423 static void
1424 gst_soup_http_src_got_chunk_cb (SoupMessage * msg, SoupBuffer * chunk,
1425     GstSoupHTTPSrc * src)
1426 {
1427   GstBaseSrc *basesrc;
1428   guint64 new_position;
1429   SoupGstChunk *gchunk;
1430
1431   if (G_UNLIKELY (msg != src->msg)) {
1432     GST_DEBUG_OBJECT (src, "got chunk, but not for current message");
1433     return;
1434   }
1435   if (G_UNLIKELY (!src->outbuf)) {
1436     GST_DEBUG_OBJECT (src, "got chunk but we're not expecting one");
1437     src->ret = GST_FLOW_OK;
1438     gst_soup_http_src_cancel_message (src);
1439     g_main_loop_quit (src->loop);
1440     return;
1441   }
1442
1443   /* We got data, reset the retry counter */
1444   src->retry_count = 0;
1445
1446   src->have_body = FALSE;
1447   if (G_UNLIKELY (src->session_io_status !=
1448           GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING)) {
1449     /* Probably a redirect. */
1450     return;
1451   }
1452   basesrc = GST_BASE_SRC_CAST (src);
1453   GST_DEBUG_OBJECT (src, "got chunk of %" G_GSIZE_FORMAT " bytes",
1454       chunk->length);
1455
1456   /* Extract the GstBuffer from the SoupBuffer and set its fields. */
1457   gchunk = (SoupGstChunk *) soup_buffer_get_owner (chunk);
1458   *src->outbuf = gchunk->buffer;
1459
1460   gst_buffer_resize (*src->outbuf, 0, chunk->length);
1461   GST_BUFFER_OFFSET (*src->outbuf) = basesrc->segment.position;
1462
1463   gst_buffer_ref (*src->outbuf);
1464
1465   new_position = src->read_position + chunk->length;
1466   if (G_LIKELY (src->request_position == src->read_position))
1467     src->request_position = new_position;
1468   src->read_position = new_position;
1469
1470   if (src->have_size) {
1471     if (new_position > src->content_size) {
1472       GST_DEBUG_OBJECT (src, "Got position previous estimated content size "
1473           "(%" G_GINT64_FORMAT " > %" G_GINT64_FORMAT ")", new_position,
1474           src->content_size);
1475       src->content_size = new_position;
1476       basesrc->segment.duration = src->content_size;
1477       gst_element_post_message (GST_ELEMENT (src),
1478           gst_message_new_duration_changed (GST_OBJECT (src)));
1479     } else if (new_position == src->content_size) {
1480       GST_DEBUG_OBJECT (src, "We're EOS now");
1481     }
1482   }
1483
1484   src->ret = GST_FLOW_OK;
1485   g_main_loop_quit (src->loop);
1486   gst_soup_http_src_session_pause_message (src);
1487 }
1488
1489 static void
1490 gst_soup_http_src_response_cb (SoupSession * session, SoupMessage * msg,
1491     GstSoupHTTPSrc * src)
1492 {
1493   if (G_UNLIKELY (msg != src->msg)) {
1494     GST_DEBUG_OBJECT (src, "got response %d: %s, but not for current message",
1495         msg->status_code, msg->reason_phrase);
1496     return;
1497   }
1498   if (G_UNLIKELY (src->session_io_status !=
1499           GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING)
1500       && SOUP_STATUS_IS_REDIRECTION (msg->status_code)) {
1501     /* Ignore redirections. */
1502     return;
1503   }
1504   GST_INFO_OBJECT (src, "got response %d: %s", msg->status_code,
1505       msg->reason_phrase);
1506   if (src->session_io_status == GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING &&
1507       src->read_position > 0 && (src->have_size
1508           && src->read_position < src->content_size) &&
1509       (src->max_retries == -1 || src->retry_count < src->max_retries)) {
1510     /* The server disconnected while streaming. Reconnect and seeking to the
1511      * last location. */
1512     src->retry = TRUE;
1513     src->retry_count++;
1514   } else {
1515     gst_soup_http_src_parse_status (msg, src);
1516   }
1517   /* The session's SoupMessage object expires after this callback returns. */
1518   src->msg = NULL;
1519   g_main_loop_quit (src->loop);
1520 }
1521
1522 #define SOUP_HTTP_SRC_ERROR(src,soup_msg,cat,code,error_message)     \
1523   GST_ELEMENT_ERROR ((src), cat, code, ("%s", error_message),        \
1524       ("%s (%d), URL: %s, Redirect to: %s", (soup_msg)->reason_phrase,                \
1525           (soup_msg)->status_code, (src)->location, GST_STR_NULL ((src)->redirection_uri)));
1526
1527 static void
1528 gst_soup_http_src_parse_status (SoupMessage * msg, GstSoupHTTPSrc * src)
1529 {
1530   if (msg->method == SOUP_METHOD_HEAD) {
1531     if (!SOUP_STATUS_IS_SUCCESSFUL (msg->status_code))
1532       GST_DEBUG_OBJECT (src, "Ignoring error %d during HEAD request",
1533           msg->status_code);
1534   } else if (SOUP_STATUS_IS_TRANSPORT_ERROR (msg->status_code)) {
1535     switch (msg->status_code) {
1536       case SOUP_STATUS_CANT_RESOLVE:
1537       case SOUP_STATUS_CANT_RESOLVE_PROXY:
1538         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, NOT_FOUND,
1539             _("Could not resolve server name."));
1540         src->ret = GST_FLOW_ERROR;
1541         break;
1542       case SOUP_STATUS_CANT_CONNECT:
1543       case SOUP_STATUS_CANT_CONNECT_PROXY:
1544         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, OPEN_READ,
1545             _("Could not establish connection to server."));
1546         src->ret = GST_FLOW_ERROR;
1547         break;
1548       case SOUP_STATUS_SSL_FAILED:
1549         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, OPEN_READ,
1550             _("Secure connection setup failed."));
1551         src->ret = GST_FLOW_ERROR;
1552         break;
1553       case SOUP_STATUS_IO_ERROR:
1554         if (src->max_retries == -1 || src->retry_count < src->max_retries) {
1555           src->retry = TRUE;
1556           src->retry_count++;
1557           src->ret = GST_FLOW_CUSTOM_ERROR;
1558         } else {
1559           SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, READ,
1560               _("A network error occurred, or the server closed the connection "
1561                   "unexpectedly."));
1562           src->ret = GST_FLOW_ERROR;
1563         }
1564         break;
1565       case SOUP_STATUS_MALFORMED:
1566         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, READ,
1567             _("Server sent bad data."));
1568         src->ret = GST_FLOW_ERROR;
1569         break;
1570       case SOUP_STATUS_CANCELLED:
1571         /* No error message when interrupted by program. */
1572         break;
1573     }
1574   } else if (SOUP_STATUS_IS_CLIENT_ERROR (msg->status_code) ||
1575       SOUP_STATUS_IS_REDIRECTION (msg->status_code) ||
1576       SOUP_STATUS_IS_SERVER_ERROR (msg->status_code)) {
1577     /* Report HTTP error. */
1578
1579     /* when content_size is unknown and we have just finished receiving
1580      * a body message, requests that go beyond the content limits will result
1581      * in an error. Here we convert those to EOS */
1582     if (msg->status_code == SOUP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE &&
1583         src->have_body && !src->have_size) {
1584       GST_DEBUG_OBJECT (src, "Requested range out of limits and received full "
1585           "body, returning EOS");
1586       src->ret = GST_FLOW_EOS;
1587       return;
1588     }
1589
1590     /* FIXME: reason_phrase is not translated and not suitable for user
1591      * error dialog according to libsoup documentation.
1592      */
1593     if (msg->status_code == SOUP_STATUS_NOT_FOUND) {
1594       GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND,
1595           ("%s", msg->reason_phrase),
1596           ("%s (%d), URL: %s, Redirect to: %s", msg->reason_phrase,
1597               msg->status_code, src->location,
1598               GST_STR_NULL (src->redirection_uri)));
1599     } else if (msg->status_code == SOUP_STATUS_UNAUTHORIZED
1600         || msg->status_code == SOUP_STATUS_PAYMENT_REQUIRED
1601         || msg->status_code == SOUP_STATUS_FORBIDDEN
1602         || msg->status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED) {
1603       GST_ELEMENT_ERROR (src, RESOURCE, NOT_AUTHORIZED, ("%s",
1604               msg->reason_phrase), ("%s (%d), URL: %s, Redirect to: %s",
1605               msg->reason_phrase, msg->status_code, src->location,
1606               GST_STR_NULL (src->redirection_uri)));
1607     } else {
1608       GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
1609           ("%s", msg->reason_phrase),
1610           ("%s (%d), URL: %s, Redirect to: %s", msg->reason_phrase,
1611               msg->status_code, src->location,
1612               GST_STR_NULL (src->redirection_uri)));
1613     }
1614     src->ret = GST_FLOW_ERROR;
1615   }
1616 }
1617
1618 static gboolean
1619 gst_soup_http_src_build_message (GstSoupHTTPSrc * src, const gchar * method)
1620 {
1621   g_return_val_if_fail (src->msg == NULL, FALSE);
1622
1623   src->msg = soup_message_new (method, src->location);
1624   if (!src->msg) {
1625     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
1626         ("Error parsing URL."), ("URL: %s", src->location));
1627     return FALSE;
1628   }
1629   src->session_io_status = GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_IDLE;
1630   if (!src->keep_alive) {
1631     soup_message_headers_append (src->msg->request_headers, "Connection",
1632         "close");
1633   }
1634   if (src->iradio_mode) {
1635     soup_message_headers_append (src->msg->request_headers, "icy-metadata",
1636         "1");
1637   }
1638   if (src->cookies) {
1639     gchar **cookie;
1640
1641     for (cookie = src->cookies; *cookie != NULL; cookie++) {
1642       soup_message_headers_append (src->msg->request_headers, "Cookie",
1643           *cookie);
1644     }
1645   }
1646   src->retry = FALSE;
1647
1648   g_signal_connect (src->msg, "got_headers",
1649       G_CALLBACK (gst_soup_http_src_got_headers_cb), src);
1650   g_signal_connect (src->msg, "got_body",
1651       G_CALLBACK (gst_soup_http_src_got_body_cb), src);
1652   g_signal_connect (src->msg, "finished",
1653       G_CALLBACK (gst_soup_http_src_finished_cb), src);
1654   g_signal_connect (src->msg, "got_chunk",
1655       G_CALLBACK (gst_soup_http_src_got_chunk_cb), src);
1656   soup_message_set_flags (src->msg, SOUP_MESSAGE_OVERWRITE_CHUNKS |
1657       (src->automatic_redirect ? 0 : SOUP_MESSAGE_NO_REDIRECT));
1658   soup_message_set_chunk_allocator (src->msg,
1659       gst_soup_http_src_chunk_allocator, src, NULL);
1660   gst_soup_http_src_add_range_header (src, src->request_position,
1661       src->stop_position);
1662
1663   gst_soup_http_src_add_extra_headers (src);
1664
1665   return TRUE;
1666 }
1667
1668 static GstFlowReturn
1669 gst_soup_http_src_do_request (GstSoupHTTPSrc * src, const gchar * method,
1670     GstBuffer ** outbuf)
1671 {
1672   /* If we're not OK, just go out of here */
1673   if (src->ret != GST_FLOW_OK) {
1674     GST_DEBUG_OBJECT (src, "Previous flow return not OK: %s",
1675         gst_flow_get_name (src->ret));
1676     return src->ret;
1677   }
1678
1679   GST_LOG_OBJECT (src, "Running request for method: %s", method);
1680   if (src->msg && (src->request_position != src->read_position)) {
1681     if (src->session_io_status == GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_IDLE) {
1682       /* EOS immediately if we have an empty segment */
1683       if (src->request_position == src->stop_position)
1684         return GST_FLOW_EOS;
1685
1686       gst_soup_http_src_add_range_header (src, src->request_position,
1687           src->stop_position);
1688     } else {
1689       GST_DEBUG_OBJECT (src, "Seek from position %" G_GUINT64_FORMAT
1690           " to %" G_GUINT64_FORMAT ": requeueing connection request",
1691           src->read_position, src->request_position);
1692       gst_soup_http_src_cancel_message (src);
1693     }
1694   }
1695   if (!src->msg) {
1696     /* EOS immediately if we have an empty segment */
1697     if (src->request_position == src->stop_position)
1698       return GST_FLOW_EOS;
1699
1700     if (!gst_soup_http_src_build_message (src, method))
1701       return GST_FLOW_ERROR;
1702   }
1703
1704   src->ret = GST_FLOW_CUSTOM_ERROR;
1705   src->outbuf = outbuf;
1706   do {
1707     if (src->interrupted) {
1708       GST_INFO_OBJECT (src, "interrupted");
1709       src->ret = GST_FLOW_FLUSHING;
1710       break;
1711     }
1712     if (src->retry) {
1713       GST_INFO_OBJECT (src, "Reconnecting");
1714
1715       /* EOS immediately if we have an empty segment */
1716       if (src->request_position == src->stop_position)
1717         return GST_FLOW_EOS;
1718
1719       if (!gst_soup_http_src_build_message (src, method))
1720         return GST_FLOW_ERROR;
1721       src->retry = FALSE;
1722       continue;
1723     }
1724     if (!src->msg) {
1725       GST_DEBUG_OBJECT (src, "EOS reached");
1726       break;
1727     }
1728
1729     switch (src->session_io_status) {
1730       case GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_IDLE:
1731         GST_INFO_OBJECT (src, "Queueing connection request");
1732         gst_soup_http_src_queue_message (src);
1733         break;
1734       case GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_QUEUED:
1735         break;
1736       case GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING:
1737         gst_soup_http_src_session_unpause_message (src);
1738         break;
1739       case GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_CANCELLED:
1740         /* Impossible. */
1741         break;
1742     }
1743
1744     if (src->ret == GST_FLOW_CUSTOM_ERROR) {
1745       g_main_context_push_thread_default (src->context);
1746       g_main_loop_run (src->loop);
1747       g_main_context_pop_thread_default (src->context);
1748     }
1749
1750   } while (src->ret == GST_FLOW_CUSTOM_ERROR);
1751
1752   /* Let the request finish if we had a stop position and are there */
1753   if (src->ret == GST_FLOW_OK && src->stop_position != -1
1754       && src->read_position >= src->stop_position) {
1755     src->outbuf = NULL;
1756     gst_soup_http_src_session_unpause_message (src);
1757     g_main_context_push_thread_default (src->context);
1758     g_main_loop_run (src->loop);
1759     g_main_context_pop_thread_default (src->context);
1760
1761     g_cond_signal (&src->request_finished_cond);
1762     /* Return OK unconditionally here, src->ret will
1763      * be most likely be EOS now but we want to
1764      * consume the buffer we got above */
1765     return GST_FLOW_OK;
1766   }
1767
1768   if (src->ret == GST_FLOW_CUSTOM_ERROR)
1769     src->ret = GST_FLOW_EOS;
1770   g_cond_signal (&src->request_finished_cond);
1771
1772   /* basesrc assumes that we don't return a buffer if
1773    * something else than OK is returned. It will just
1774    * leak any buffer we might accidentially provide
1775    * here.
1776    *
1777    * This can potentially happen during flushing.
1778    */
1779   if (src->ret != GST_FLOW_OK && outbuf && *outbuf) {
1780     gst_buffer_unref (*outbuf);
1781     *outbuf = NULL;
1782   }
1783
1784   return src->ret;
1785 }
1786
1787 static GstFlowReturn
1788 gst_soup_http_src_create (GstPushSrc * psrc, GstBuffer ** outbuf)
1789 {
1790   GstSoupHTTPSrc *src;
1791   GstFlowReturn ret;
1792   GstEvent *http_headers_event;
1793
1794   src = GST_SOUP_HTTP_SRC (psrc);
1795
1796   g_mutex_lock (&src->mutex);
1797   *outbuf = NULL;
1798   ret =
1799       gst_soup_http_src_do_request (src,
1800       src->method ? src->method : SOUP_METHOD_GET, outbuf);
1801   http_headers_event = src->http_headers_event;
1802   src->http_headers_event = NULL;
1803   g_mutex_unlock (&src->mutex);
1804
1805   if (http_headers_event)
1806     gst_pad_push_event (GST_BASE_SRC_PAD (src), http_headers_event);
1807
1808   return ret;
1809 }
1810
1811 static gboolean
1812 gst_soup_http_src_start (GstBaseSrc * bsrc)
1813 {
1814   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
1815
1816   GST_DEBUG_OBJECT (src, "start(\"%s\")", src->location);
1817
1818   return gst_soup_http_src_session_open (src);
1819 }
1820
1821 static gboolean
1822 gst_soup_http_src_stop (GstBaseSrc * bsrc)
1823 {
1824   GstSoupHTTPSrc *src;
1825
1826   src = GST_SOUP_HTTP_SRC (bsrc);
1827   GST_DEBUG_OBJECT (src, "stop()");
1828   if (src->keep_alive && !src->msg)
1829     gst_soup_http_src_cancel_message (src);
1830   else
1831     gst_soup_http_src_session_close (src);
1832
1833   gst_soup_http_src_reset (src);
1834   return TRUE;
1835 }
1836
1837 static GstStateChangeReturn
1838 gst_soup_http_src_change_state (GstElement * element, GstStateChange transition)
1839 {
1840   GstStateChangeReturn ret;
1841   GstSoupHTTPSrc *src;
1842
1843   src = GST_SOUP_HTTP_SRC (element);
1844
1845   switch (transition) {
1846     case GST_STATE_CHANGE_READY_TO_NULL:
1847       gst_soup_http_src_session_close (src);
1848       break;
1849     default:
1850       break;
1851   }
1852
1853   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1854
1855   return ret;
1856 }
1857
1858 /* Interrupt a blocking request. */
1859 static gboolean
1860 gst_soup_http_src_unlock (GstBaseSrc * bsrc)
1861 {
1862   GstSoupHTTPSrc *src;
1863
1864   src = GST_SOUP_HTTP_SRC (bsrc);
1865   GST_DEBUG_OBJECT (src, "unlock()");
1866
1867   src->interrupted = TRUE;
1868   src->ret = GST_FLOW_FLUSHING;
1869   if (src->loop)
1870     g_main_loop_quit (src->loop);
1871   g_cond_signal (&src->request_finished_cond);
1872   return TRUE;
1873 }
1874
1875 /* Interrupt interrupt. */
1876 static gboolean
1877 gst_soup_http_src_unlock_stop (GstBaseSrc * bsrc)
1878 {
1879   GstSoupHTTPSrc *src;
1880
1881   src = GST_SOUP_HTTP_SRC (bsrc);
1882   GST_DEBUG_OBJECT (src, "unlock_stop()");
1883
1884   src->interrupted = FALSE;
1885   src->ret = GST_FLOW_OK;
1886   return TRUE;
1887 }
1888
1889 static gboolean
1890 gst_soup_http_src_get_size (GstBaseSrc * bsrc, guint64 * size)
1891 {
1892   GstSoupHTTPSrc *src;
1893
1894   src = GST_SOUP_HTTP_SRC (bsrc);
1895
1896   if (src->have_size) {
1897     GST_DEBUG_OBJECT (src, "get_size() = %" G_GUINT64_FORMAT,
1898         src->content_size);
1899     *size = src->content_size;
1900     return TRUE;
1901   }
1902   GST_DEBUG_OBJECT (src, "get_size() = FALSE");
1903   return FALSE;
1904 }
1905
1906 static void
1907 gst_soup_http_src_check_seekable (GstSoupHTTPSrc * src)
1908 {
1909   GstFlowReturn ret = GST_FLOW_OK;
1910
1911   /* Special case to check if the server allows range requests
1912    * before really starting to get data in the buffer creation
1913    * loops.
1914    */
1915   if (!src->got_headers && GST_STATE (src) >= GST_STATE_PAUSED) {
1916     g_mutex_lock (&src->mutex);
1917     while (!src->got_headers && !src->interrupted && ret == GST_FLOW_OK) {
1918       if ((src->msg && src->msg->method != SOUP_METHOD_HEAD) &&
1919           src->session_io_status != GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_IDLE) {
1920         /* wait for the current request to finish */
1921         g_cond_wait (&src->request_finished_cond, &src->mutex);
1922       } else {
1923         if (gst_soup_http_src_session_open (src)) {
1924           ret = gst_soup_http_src_do_request (src, SOUP_METHOD_HEAD, NULL);
1925         }
1926       }
1927     }
1928     if (src->ret == GST_FLOW_EOS) {
1929       /* A HEAD request shouldn't lead to EOS */
1930       src->ret = GST_FLOW_OK;
1931     }
1932     /* resets status to idle */
1933     gst_soup_http_src_cancel_message (src);
1934     g_mutex_unlock (&src->mutex);
1935   }
1936 }
1937
1938 static gboolean
1939 gst_soup_http_src_is_seekable (GstBaseSrc * bsrc)
1940 {
1941   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
1942
1943   gst_soup_http_src_check_seekable (src);
1944
1945   return src->seekable;
1946 }
1947
1948 static gboolean
1949 gst_soup_http_src_do_seek (GstBaseSrc * bsrc, GstSegment * segment)
1950 {
1951   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
1952
1953   GST_DEBUG_OBJECT (src, "do_seek(%" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT
1954       ")", segment->start, segment->stop);
1955   if (src->read_position == segment->start &&
1956       src->request_position == src->read_position &&
1957       src->stop_position == segment->stop) {
1958     GST_DEBUG_OBJECT (src,
1959         "Seek to current read/end position and no seek pending");
1960     return TRUE;
1961   }
1962
1963   gst_soup_http_src_check_seekable (src);
1964
1965   /* If we have no headers we don't know yet if it is seekable or not.
1966    * Store the start position and error out later if it isn't */
1967   if (src->got_headers && !src->seekable) {
1968     GST_WARNING_OBJECT (src, "Not seekable");
1969     return FALSE;
1970   }
1971
1972   if (segment->rate < 0.0 || segment->format != GST_FORMAT_BYTES) {
1973     GST_WARNING_OBJECT (src, "Invalid seek segment");
1974     return FALSE;
1975   }
1976
1977   if (src->have_size && segment->start >= src->content_size) {
1978     GST_WARNING_OBJECT (src,
1979         "Potentially seeking behind end of file, might EOS immediately");
1980   }
1981
1982   /* Wait for create() to handle the jump in offset. */
1983   src->request_position = segment->start;
1984   src->stop_position = segment->stop;
1985
1986   return TRUE;
1987 }
1988
1989 static gboolean
1990 gst_soup_http_src_query (GstBaseSrc * bsrc, GstQuery * query)
1991 {
1992   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
1993   gboolean ret;
1994   GstSchedulingFlags flags;
1995   gint minsize, maxsize, align;
1996
1997   switch (GST_QUERY_TYPE (query)) {
1998     case GST_QUERY_URI:
1999       gst_query_set_uri (query, src->location);
2000       if (src->redirection_uri != NULL) {
2001         gst_query_set_uri_redirection (query, src->redirection_uri);
2002         gst_query_set_uri_redirection_permanent (query,
2003             src->redirection_permanent);
2004       }
2005       ret = TRUE;
2006       break;
2007     default:
2008       ret = FALSE;
2009       break;
2010   }
2011
2012   if (!ret)
2013     ret = GST_BASE_SRC_CLASS (parent_class)->query (bsrc, query);
2014
2015   switch (GST_QUERY_TYPE (query)) {
2016     case GST_QUERY_SCHEDULING:
2017       gst_query_parse_scheduling (query, &flags, &minsize, &maxsize, &align);
2018       flags |= GST_SCHEDULING_FLAG_BANDWIDTH_LIMITED;
2019       gst_query_set_scheduling (query, flags, minsize, maxsize, align);
2020       break;
2021     default:
2022       break;
2023   }
2024
2025   return ret;
2026 }
2027
2028 static gboolean
2029 gst_soup_http_src_set_location (GstSoupHTTPSrc * src, const gchar * uri,
2030     GError ** error)
2031 {
2032   const char *alt_schemes[] = { "icy://", "icyx://" };
2033   guint i;
2034
2035   if (src->location) {
2036     g_free (src->location);
2037     src->location = NULL;
2038   }
2039
2040   if (uri == NULL)
2041     return FALSE;
2042
2043   for (i = 0; i < G_N_ELEMENTS (alt_schemes); i++) {
2044     if (g_str_has_prefix (uri, alt_schemes[i])) {
2045       src->location =
2046           g_strdup_printf ("http://%s", uri + strlen (alt_schemes[i]));
2047       return TRUE;
2048     }
2049   }
2050
2051   if (src->redirection_uri) {
2052     g_free (src->redirection_uri);
2053     src->redirection_uri = NULL;
2054   }
2055
2056   src->location = g_strdup (uri);
2057
2058   return TRUE;
2059 }
2060
2061 static gboolean
2062 gst_soup_http_src_set_proxy (GstSoupHTTPSrc * src, const gchar * uri)
2063 {
2064   if (src->proxy) {
2065     soup_uri_free (src->proxy);
2066     src->proxy = NULL;
2067   }
2068
2069   if (uri == NULL || *uri == '\0')
2070     return TRUE;
2071
2072   if (g_str_has_prefix (uri, "http://")) {
2073     src->proxy = soup_uri_new (uri);
2074   } else {
2075     gchar *new_uri = g_strconcat ("http://", uri, NULL);
2076
2077     src->proxy = soup_uri_new (new_uri);
2078     g_free (new_uri);
2079   }
2080
2081   return (src->proxy != NULL);
2082 }
2083
2084 static guint
2085 gst_soup_http_src_uri_get_type (GType type)
2086 {
2087   return GST_URI_SRC;
2088 }
2089
2090 static const gchar *const *
2091 gst_soup_http_src_uri_get_protocols (GType type)
2092 {
2093   static const gchar *protocols[] = { "http", "https", "icy", "icyx", NULL };
2094
2095   return protocols;
2096 }
2097
2098 static gchar *
2099 gst_soup_http_src_uri_get_uri (GstURIHandler * handler)
2100 {
2101   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (handler);
2102
2103   /* FIXME: make thread-safe */
2104   return g_strdup (src->location);
2105 }
2106
2107 static gboolean
2108 gst_soup_http_src_uri_set_uri (GstURIHandler * handler, const gchar * uri,
2109     GError ** error)
2110 {
2111   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (handler);
2112
2113   return gst_soup_http_src_set_location (src, uri, error);
2114 }
2115
2116 static void
2117 gst_soup_http_src_uri_handler_init (gpointer g_iface, gpointer iface_data)
2118 {
2119   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
2120
2121   iface->get_type = gst_soup_http_src_uri_get_type;
2122   iface->get_protocols = gst_soup_http_src_uri_get_protocols;
2123   iface->get_uri = gst_soup_http_src_uri_get_uri;
2124   iface->set_uri = gst_soup_http_src_uri_set_uri;
2125 }