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