dc8b86a3cf030180bee1738f2ee838524f49c9af
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-good / ext / soup / gstsouphttpsrc.c
1 /* GStreamer
2  * Copyright (C) 2007-2008 Wouter Cloetens <wouter@mind.be>
3  * Copyright (C) 2021 Igalia S.L.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more
14  */
15
16 /**
17  * SECTION:element-souphttpsrc
18  * @title: souphttpsrc
19  *
20  * This plugin reads data from a remote location specified by a URI.
21  * Supported protocols are 'http', 'https'.
22  *
23  * An HTTP proxy must be specified by its URL.
24  * If the "http_proxy" environment variable is set, its value is used.
25  * If built with libsoup's GNOME integration features, the GNOME proxy
26  * configuration will be used, or failing that, proxy autodetection.
27  * The #GstSoupHTTPSrc:proxy property can be used to override the default.
28  *
29  * In case the #GstSoupHTTPSrc:iradio-mode property is set and the location is
30  * an HTTP resource, souphttpsrc will send special Icecast HTTP headers to the
31  * server to request additional Icecast meta-information.
32  * If the server is not an Icecast server, it will behave as if the
33  * #GstSoupHTTPSrc:iradio-mode property were not set. If it is, souphttpsrc will
34  * output data with a media type of application/x-icy, in which case you will
35  * need to use the #GstICYDemux element as follow-up element to extract the Icecast
36  * metadata and to determine the underlying media type.
37  *
38  * ## Example launch line
39  * |[
40  * gst-launch-1.0 -v souphttpsrc location=https://some.server.org/index.html
41  *     ! filesink location=/home/joe/server.html
42  * ]| The above pipeline reads a web page from a server using the HTTPS protocol
43  * and writes it to a local file.
44  * |[
45  * gst-launch-1.0 -v souphttpsrc user-agent="FooPlayer 0.99 beta"
46  *     automatic-redirect=false proxy=http://proxy.intranet.local:8080
47  *     location=http://music.foobar.com/demo.mp3 ! mpgaudioparse
48  *     ! mpg123audiodec ! audioconvert ! audioresample ! autoaudiosink
49  * ]| The above pipeline will read and decode and play an mp3 file from a
50  * web server using the HTTP protocol. If the server sends redirects,
51  * the request fails instead of following the redirect. The specified
52  * HTTP proxy server is used. The User-Agent HTTP request header
53  * is set to a custom string instead of "GStreamer souphttpsrc."
54  * |[
55  * gst-launch-1.0 -v souphttpsrc location=http://10.11.12.13/mjpeg
56  *     do-timestamp=true ! multipartdemux
57  *     ! image/jpeg,width=640,height=480 ! matroskamux
58  *     ! filesink location=mjpeg.mkv
59  * ]| The above pipeline reads a motion JPEG stream from an IP camera
60  * using the HTTP protocol, encoded as mime/multipart image/jpeg
61  * parts, and writes a Matroska motion JPEG file. The width and
62  * height properties are set in the caps to provide the Matroska
63  * multiplexer with the information to set this in the header.
64  * Timestamps are set on the buffers as they arrive from the camera.
65  * These are used by the mime/multipart demultiplexer to emit timestamps
66  * on the JPEG-encoded video frame buffers. This allows the Matroska
67  * multiplexer to timestamp the frames in the resulting file.
68  *
69  */
70
71 #ifdef HAVE_CONFIG_H
72 #include "config.h"
73 #endif
74
75 #include <string.h>
76 #ifdef HAVE_STDLIB_H
77 #include <stdlib.h>             /* atoi() */
78 #endif
79 #include <gst/gstelement.h>
80 #include <glib/gi18n-lib.h>
81 #include "gstsoupelements.h"
82 #include "gstsouphttpsrc.h"
83 #include "gstsouputils.h"
84
85 #include <gst/tag/tag.h>
86
87 /* this is a simple wrapper class around SoupSession; it exists in order to
88  * have a refcountable owner for the actual SoupSession + the thread it runs
89  * in and its main loop (we cannot inverse the ownership hierarchy, because
90  * the thread + loop are actually longer lived than the session)
91  *
92  * it is entirely private to this implementation
93  */
94
95 #define GST_TYPE_SOUP_SESSION (gst_soup_session_get_type())
96 #define GST_SOUP_SESSION(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), GST_TYPE_SOUP_SESSION, GstSoupSession))
97 #define gst_soup_session_parent_class session_parent_class
98
99 GType gst_soup_session_get_type (void);
100
101 typedef struct _GstSoupSessionClass GstSoupSessionClass;
102
103 struct _GstSoupSession
104 {
105   GObject parent_instance;
106
107   SoupSession *session;
108   GThread *thread;
109   GMainLoop *loop;
110 };
111
112 struct _GstSoupSessionClass
113 {
114   GObjectClass parent_class;
115 };
116
117 G_DEFINE_TYPE (GstSoupSession, gst_soup_session, G_TYPE_OBJECT);
118
119 static void
120 gst_soup_session_init (GstSoupSession * sess)
121 {
122 }
123
124 static gboolean
125 _soup_session_finalize_cb (gpointer user_data)
126 {
127   GstSoupSession *sess = user_data;
128
129   g_main_loop_quit (sess->loop);
130
131   return FALSE;
132 }
133
134 static void
135 gst_soup_session_finalize (GObject * obj)
136 {
137   GstSoupSession *sess = GST_SOUP_SESSION (obj);
138   GSource *src;
139
140   /* handle disposing of failure cases */
141   if (!sess->loop) {
142     goto cleanup;
143   }
144
145   src = g_idle_source_new ();
146
147   g_source_set_callback (src, _soup_session_finalize_cb, sess, NULL);
148   g_source_attach (src, g_main_loop_get_context (sess->loop));
149   g_source_unref (src);
150
151   /* finish off thread and the loop; ensure it's not from the thread */
152   g_assert (!g_main_context_is_owner (g_main_loop_get_context (sess->loop)));
153   g_thread_join (sess->thread);
154   g_main_loop_unref (sess->loop);
155 cleanup:
156   G_OBJECT_CLASS (session_parent_class)->finalize (obj);
157 }
158
159 static void
160 gst_soup_session_class_init (GstSoupSessionClass * klass)
161 {
162   GObjectClass *gclass = G_OBJECT_CLASS (klass);
163
164   gclass->finalize = gst_soup_session_finalize;
165 }
166
167 GST_DEBUG_CATEGORY_STATIC (souphttpsrc_debug);
168 #define GST_CAT_DEFAULT souphttpsrc_debug
169
170 #define GST_SOUP_SESSION_CONTEXT "gst.soup.session"
171
172 static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src",
173     GST_PAD_SRC,
174     GST_PAD_ALWAYS,
175     GST_STATIC_CAPS_ANY);
176
177 enum
178 {
179   PROP_0,
180   PROP_LOCATION,
181   PROP_IS_LIVE,
182   PROP_USER_AGENT,
183   PROP_AUTOMATIC_REDIRECT,
184   PROP_PROXY,
185   PROP_USER_ID,
186   PROP_USER_PW,
187   PROP_PROXY_ID,
188   PROP_PROXY_PW,
189   PROP_COOKIES,
190   PROP_IRADIO_MODE,
191   PROP_TIMEOUT,
192   PROP_EXTRA_HEADERS,
193   PROP_SOUP_LOG_LEVEL,
194   PROP_COMPRESS,
195   PROP_KEEP_ALIVE,
196   PROP_SSL_STRICT,
197   PROP_SSL_CA_FILE,
198   PROP_SSL_USE_SYSTEM_CA_FILE,
199   PROP_TLS_DATABASE,
200   PROP_RETRIES,
201   PROP_METHOD,
202   PROP_TLS_INTERACTION,
203 };
204
205 #define DEFAULT_USER_AGENT           "GStreamer souphttpsrc " PACKAGE_VERSION " "
206 #define DEFAULT_IRADIO_MODE          TRUE
207 #define DEFAULT_SOUP_LOG_LEVEL       SOUP_LOGGER_LOG_HEADERS
208 #define DEFAULT_COMPRESS             FALSE
209 #define DEFAULT_KEEP_ALIVE           TRUE
210 #define DEFAULT_SSL_STRICT           TRUE
211 #define DEFAULT_SSL_CA_FILE          NULL
212 #define DEFAULT_SSL_USE_SYSTEM_CA_FILE TRUE
213 #define DEFAULT_TLS_DATABASE         NULL
214 #define DEFAULT_TLS_INTERACTION      NULL
215 #define DEFAULT_TIMEOUT              15
216 #define DEFAULT_RETRIES              3
217 #define DEFAULT_SOUP_METHOD          NULL
218
219 #define GROW_BLOCKSIZE_LIMIT 1
220 #define GROW_BLOCKSIZE_COUNT 1
221 #define GROW_BLOCKSIZE_FACTOR 2
222 #define REDUCE_BLOCKSIZE_LIMIT 0.20
223 #define REDUCE_BLOCKSIZE_COUNT 2
224 #define REDUCE_BLOCKSIZE_FACTOR 0.5
225 #define GROW_TIME_LIMIT (1 * GST_SECOND)
226
227 static void gst_soup_http_src_uri_handler_init (gpointer g_iface,
228     gpointer iface_data);
229 static void gst_soup_http_src_finalize (GObject * gobject);
230 static void gst_soup_http_src_dispose (GObject * gobject);
231
232 static void gst_soup_http_src_set_property (GObject * object, guint prop_id,
233     const GValue * value, GParamSpec * pspec);
234 static void gst_soup_http_src_get_property (GObject * object, guint prop_id,
235     GValue * value, GParamSpec * pspec);
236
237 static GstStateChangeReturn gst_soup_http_src_change_state (GstElement *
238     element, GstStateChange transition);
239 static void gst_soup_http_src_set_context (GstElement * element,
240     GstContext * context);
241 static GstFlowReturn gst_soup_http_src_create (GstPushSrc * psrc,
242     GstBuffer ** outbuf);
243 static gboolean gst_soup_http_src_start (GstBaseSrc * bsrc);
244 static gboolean gst_soup_http_src_stop (GstBaseSrc * bsrc);
245 static gboolean gst_soup_http_src_get_size (GstBaseSrc * bsrc, guint64 * size);
246 static gboolean gst_soup_http_src_is_seekable (GstBaseSrc * bsrc);
247 static gboolean gst_soup_http_src_do_seek (GstBaseSrc * bsrc,
248     GstSegment * segment);
249 static gboolean gst_soup_http_src_query (GstBaseSrc * bsrc, GstQuery * query);
250 static gboolean gst_soup_http_src_unlock (GstBaseSrc * bsrc);
251 static gboolean gst_soup_http_src_unlock_stop (GstBaseSrc * bsrc);
252 static gboolean gst_soup_http_src_set_location (GstSoupHTTPSrc * src,
253     const gchar * uri, GError ** error);
254 static gboolean gst_soup_http_src_set_proxy (GstSoupHTTPSrc * src,
255     const gchar * uri);
256 static char *gst_soup_http_src_unicodify (const char *str);
257 static gboolean gst_soup_http_src_build_message (GstSoupHTTPSrc * src,
258     const gchar * method);
259 static gboolean gst_soup_http_src_add_range_header (GstSoupHTTPSrc * src,
260     guint64 offset, guint64 stop_offset);
261 static gboolean gst_soup_http_src_session_open (GstSoupHTTPSrc * src);
262 static void gst_soup_http_src_session_close (GstSoupHTTPSrc * src);
263 static GstFlowReturn gst_soup_http_src_parse_status (SoupMessage * msg,
264     GstSoupHTTPSrc * src);
265 static GstFlowReturn gst_soup_http_src_got_headers (GstSoupHTTPSrc * src,
266     SoupMessage * msg);
267 static void gst_soup_http_src_authenticate_cb_2 (SoupSession *,
268     SoupMessage * msg, SoupAuth * auth, gboolean retrying, gpointer);
269 static gboolean gst_soup_http_src_authenticate_cb (SoupMessage * msg,
270     SoupAuth * auth, gboolean retrying, gpointer);
271 static gboolean gst_soup_http_src_accept_certificate_cb (SoupMessage * msg,
272     GTlsCertificate * tls_certificate, GTlsCertificateFlags tls_errors,
273     gpointer user_data);
274
275 #define gst_soup_http_src_parent_class parent_class
276 G_DEFINE_TYPE_WITH_CODE (GstSoupHTTPSrc, gst_soup_http_src, GST_TYPE_PUSH_SRC,
277     G_IMPLEMENT_INTERFACE (GST_TYPE_URI_HANDLER,
278         gst_soup_http_src_uri_handler_init));
279
280 static gboolean souphttpsrc_element_init (GstPlugin * plugin);
281 GST_ELEMENT_REGISTER_DEFINE_CUSTOM (souphttpsrc, souphttpsrc_element_init);
282
283 static void
284 gst_soup_http_src_class_init (GstSoupHTTPSrcClass * klass)
285 {
286   GObjectClass *gobject_class;
287   GstElementClass *gstelement_class;
288   GstBaseSrcClass *gstbasesrc_class;
289   GstPushSrcClass *gstpushsrc_class;
290
291   gobject_class = (GObjectClass *) klass;
292   gstelement_class = (GstElementClass *) klass;
293   gstbasesrc_class = (GstBaseSrcClass *) klass;
294   gstpushsrc_class = (GstPushSrcClass *) klass;
295
296   gobject_class->set_property = gst_soup_http_src_set_property;
297   gobject_class->get_property = gst_soup_http_src_get_property;
298   gobject_class->finalize = gst_soup_http_src_finalize;
299   gobject_class->dispose = gst_soup_http_src_dispose;
300
301   g_object_class_install_property (gobject_class,
302       PROP_LOCATION,
303       g_param_spec_string ("location", "Location",
304           "Location to read from", "",
305           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
306   g_object_class_install_property (gobject_class,
307       PROP_USER_AGENT,
308       g_param_spec_string ("user-agent", "User-Agent",
309           "Value of the User-Agent HTTP request header field",
310           DEFAULT_USER_AGENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
311   g_object_class_install_property (gobject_class,
312       PROP_AUTOMATIC_REDIRECT,
313       g_param_spec_boolean ("automatic-redirect", "automatic-redirect",
314           "Automatically follow HTTP redirects (HTTP Status Code 3xx)",
315           TRUE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
316   g_object_class_install_property (gobject_class,
317       PROP_PROXY,
318       g_param_spec_string ("proxy", "Proxy",
319           "HTTP proxy server URI", "",
320           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
321   g_object_class_install_property (gobject_class,
322       PROP_USER_ID,
323       g_param_spec_string ("user-id", "user-id",
324           "HTTP location URI user id for authentication", "",
325           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
326   g_object_class_install_property (gobject_class, PROP_USER_PW,
327       g_param_spec_string ("user-pw", "user-pw",
328           "HTTP location URI user password for authentication", "",
329           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
330   g_object_class_install_property (gobject_class, PROP_PROXY_ID,
331       g_param_spec_string ("proxy-id", "proxy-id",
332           "HTTP proxy URI user id for authentication", "",
333           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
334   g_object_class_install_property (gobject_class, PROP_PROXY_PW,
335       g_param_spec_string ("proxy-pw", "proxy-pw",
336           "HTTP proxy URI user password for authentication", "",
337           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
338   g_object_class_install_property (gobject_class, PROP_COOKIES,
339       g_param_spec_boxed ("cookies", "Cookies", "HTTP request cookies",
340           G_TYPE_STRV, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
341   g_object_class_install_property (gobject_class, PROP_IS_LIVE,
342       g_param_spec_boolean ("is-live", "is-live", "Act like a live source",
343           FALSE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
344   g_object_class_install_property (gobject_class, PROP_TIMEOUT,
345       g_param_spec_uint ("timeout", "timeout",
346           "Value in seconds to timeout a blocking I/O (0 = No timeout).", 0,
347           3600, DEFAULT_TIMEOUT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
348   g_object_class_install_property (gobject_class, PROP_EXTRA_HEADERS,
349       g_param_spec_boxed ("extra-headers", "Extra Headers",
350           "Extra headers to append to the HTTP request",
351           GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
352   g_object_class_install_property (gobject_class, PROP_IRADIO_MODE,
353       g_param_spec_boolean ("iradio-mode", "iradio-mode",
354           "Enable internet radio mode (ask server to send shoutcast/icecast "
355           "metadata interleaved with the actual stream data)",
356           DEFAULT_IRADIO_MODE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
357
358  /**
359    * GstSoupHTTPSrc::http-log-level:
360    *
361    * If set and > 0, captures and dumps HTTP session data as
362    * log messages if log level >= GST_LEVEL_TRACE
363    *
364    * Since: 1.4
365    */
366   g_object_class_install_property (gobject_class, PROP_SOUP_LOG_LEVEL,
367       g_param_spec_enum ("http-log-level", "HTTP log level",
368           "Set log level for soup's HTTP session log",
369           _soup_logger_log_level_get_type (),
370           DEFAULT_SOUP_LOG_LEVEL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
371
372   /**
373    * GstSoupHTTPSrc::compress:
374    *
375    * If set to %TRUE, souphttpsrc will automatically handle gzip
376    * and deflate Content-Encodings. This does not make much difference
377    * and causes more load for normal media files, but makes a real
378    * difference in size for plaintext files.
379    *
380    * Since: 1.4
381    */
382   g_object_class_install_property (gobject_class, PROP_COMPRESS,
383       g_param_spec_boolean ("compress", "Compress",
384           "Allow compressed content encodings",
385           DEFAULT_COMPRESS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
386
387  /**
388    * GstSoupHTTPSrc::keep-alive:
389    *
390    * If set to %TRUE, souphttpsrc will keep alive connections when being
391    * set to READY state and only will close connections when connecting
392    * to a different server or when going to NULL state..
393    *
394    * Since: 1.4
395    */
396   g_object_class_install_property (gobject_class, PROP_KEEP_ALIVE,
397       g_param_spec_boolean ("keep-alive", "keep-alive",
398           "Use HTTP persistent connections", DEFAULT_KEEP_ALIVE,
399           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
400
401  /**
402    * GstSoupHTTPSrc::ssl-strict:
403    *
404    * If set to %TRUE, souphttpsrc will reject all SSL certificates that
405    * are considered invalid.
406    *
407    * Since: 1.4
408    */
409   g_object_class_install_property (gobject_class, PROP_SSL_STRICT,
410       g_param_spec_boolean ("ssl-strict", "SSL Strict",
411           "Strict SSL certificate checking", DEFAULT_SSL_STRICT,
412           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
413
414  /**
415    * GstSoupHTTPSrc::ssl-ca-file:
416    *
417    * A SSL anchor CA file that should be used for checking certificates
418    * instead of the system CA file.
419    *
420    * If this property is non-%NULL, #GstSoupHTTPSrc::ssl-use-system-ca-file
421    * value will be ignored.
422    *
423    * Deprecated: Use #GstSoupHTTPSrc::tls-database property instead. This
424    * property is no-op when libsoup3 is being used at runtime.
425    *
426    * Since: 1.4
427    */
428   g_object_class_install_property (gobject_class, PROP_SSL_CA_FILE,
429       g_param_spec_string ("ssl-ca-file", "SSL CA File",
430           "Location of a SSL anchor CA file to use", DEFAULT_SSL_CA_FILE,
431           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
432
433   /**
434    * GstSoupHTTPSrc::ssl-use-system-ca-file:
435    *
436    * If set to %TRUE, souphttpsrc will use the system's CA file for
437    * checking certificates, unless #GstSoupHTTPSrc::ssl-ca-file or
438    * #GstSoupHTTPSrc::tls-database are non-%NULL.
439    *
440    * Deprecated: This property is no-op when libsoup3 is being used at runtime.
441    *
442    * Since: 1.4
443    */
444   g_object_class_install_property (gobject_class, PROP_SSL_USE_SYSTEM_CA_FILE,
445       g_param_spec_boolean ("ssl-use-system-ca-file", "Use System CA File",
446           "Use system CA file", DEFAULT_SSL_USE_SYSTEM_CA_FILE,
447           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
448
449   /**
450    * GstSoupHTTPSrc::tls-database:
451    *
452    * TLS database with anchor certificate authorities used to validate
453    * the server certificate.
454    *
455    * If this property is non-%NULL, #GstSoupHTTPSrc::ssl-use-system-ca-file
456    * and #GstSoupHTTPSrc::ssl-ca-file values will be ignored.
457    *
458    * Since: 1.6
459    */
460   g_object_class_install_property (gobject_class, PROP_TLS_DATABASE,
461       g_param_spec_object ("tls-database", "TLS database",
462           "TLS database with anchor certificate authorities used to validate the server certificate",
463           G_TYPE_TLS_DATABASE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
464
465   /**
466    * GstSoupHTTPSrc::tls-interaction:
467    *
468    * A #GTlsInteraction object to be used when the connection or certificate
469    * database need to interact with the user. This will be used to prompt the
470    * user for passwords or certificate where necessary.
471    *
472    * Since: 1.8
473    */
474   g_object_class_install_property (gobject_class, PROP_TLS_INTERACTION,
475       g_param_spec_object ("tls-interaction", "TLS interaction",
476           "A GTlsInteraction object to be used when the connection or certificate database need to interact with the user.",
477           G_TYPE_TLS_INTERACTION, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
478
479  /**
480    * GstSoupHTTPSrc::retries:
481    *
482    * Maximum number of retries until giving up.
483    *
484    * Since: 1.4
485    */
486   g_object_class_install_property (gobject_class, PROP_RETRIES,
487       g_param_spec_int ("retries", "Retries",
488           "Maximum number of retries until giving up (-1=infinite)", -1,
489           G_MAXINT, DEFAULT_RETRIES,
490           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
491
492  /**
493    * GstSoupHTTPSrc::method
494    *
495    * The HTTP method to use when making a request
496    *
497    * Since: 1.6
498    */
499   g_object_class_install_property (gobject_class, PROP_METHOD,
500       g_param_spec_string ("method", "HTTP method",
501           "The HTTP method to use (GET, HEAD, OPTIONS, etc)",
502           DEFAULT_SOUP_METHOD, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
503
504   gst_element_class_add_static_pad_template (gstelement_class, &srctemplate);
505
506   gst_element_class_set_static_metadata (gstelement_class, "HTTP client source",
507       "Source/Network",
508       "Receive data as a client over the network via HTTP using SOUP",
509       "Wouter Cloetens <wouter@mind.be>");
510   gstelement_class->change_state =
511       GST_DEBUG_FUNCPTR (gst_soup_http_src_change_state);
512   gstelement_class->set_context =
513       GST_DEBUG_FUNCPTR (gst_soup_http_src_set_context);
514
515   gstbasesrc_class->start = GST_DEBUG_FUNCPTR (gst_soup_http_src_start);
516   gstbasesrc_class->stop = GST_DEBUG_FUNCPTR (gst_soup_http_src_stop);
517   gstbasesrc_class->unlock = GST_DEBUG_FUNCPTR (gst_soup_http_src_unlock);
518   gstbasesrc_class->unlock_stop =
519       GST_DEBUG_FUNCPTR (gst_soup_http_src_unlock_stop);
520   gstbasesrc_class->get_size = GST_DEBUG_FUNCPTR (gst_soup_http_src_get_size);
521   gstbasesrc_class->is_seekable =
522       GST_DEBUG_FUNCPTR (gst_soup_http_src_is_seekable);
523   gstbasesrc_class->do_seek = GST_DEBUG_FUNCPTR (gst_soup_http_src_do_seek);
524   gstbasesrc_class->query = GST_DEBUG_FUNCPTR (gst_soup_http_src_query);
525
526   gstpushsrc_class->create = GST_DEBUG_FUNCPTR (gst_soup_http_src_create);
527 }
528
529 static void
530 gst_soup_http_src_reset (GstSoupHTTPSrc * src)
531 {
532   src->retry_count = 0;
533   src->have_size = FALSE;
534   src->got_headers = FALSE;
535   src->headers_ret = GST_FLOW_OK;
536   src->seekable = FALSE;
537   src->read_position = 0;
538   src->request_position = 0;
539   src->stop_position = -1;
540   src->content_size = 0;
541   src->have_body = FALSE;
542
543   src->reduce_blocksize_count = 0;
544   src->increase_blocksize_count = 0;
545   src->last_socket_read_time = 0;
546
547   g_cancellable_reset (src->cancellable);
548
549   gst_caps_replace (&src->src_caps, NULL);
550   g_free (src->iradio_name);
551   src->iradio_name = NULL;
552   g_free (src->iradio_genre);
553   src->iradio_genre = NULL;
554   g_free (src->iradio_url);
555   src->iradio_url = NULL;
556 }
557
558 static void
559 gst_soup_http_src_init (GstSoupHTTPSrc * src)
560 {
561   const gchar *proxy;
562
563   g_mutex_init (&src->session_mutex);
564   g_cond_init (&src->session_cond);
565   src->cancellable = g_cancellable_new ();
566   src->location = NULL;
567   src->redirection_uri = NULL;
568   src->automatic_redirect = TRUE;
569   src->user_agent = g_strdup (DEFAULT_USER_AGENT);
570   src->user_id = NULL;
571   src->user_pw = NULL;
572   src->proxy_id = NULL;
573   src->proxy_pw = NULL;
574   src->cookies = NULL;
575   src->iradio_mode = DEFAULT_IRADIO_MODE;
576   src->session = NULL;
577   src->external_session = NULL;
578   src->msg = NULL;
579   src->timeout = DEFAULT_TIMEOUT;
580   src->log_level = DEFAULT_SOUP_LOG_LEVEL;
581   src->compress = DEFAULT_COMPRESS;
582   src->keep_alive = DEFAULT_KEEP_ALIVE;
583   src->ssl_strict = DEFAULT_SSL_STRICT;
584   src->ssl_use_system_ca_file = DEFAULT_SSL_USE_SYSTEM_CA_FILE;
585   src->tls_database = DEFAULT_TLS_DATABASE;
586   src->tls_interaction = DEFAULT_TLS_INTERACTION;
587   src->max_retries = DEFAULT_RETRIES;
588   src->method = DEFAULT_SOUP_METHOD;
589   src->minimum_blocksize = gst_base_src_get_blocksize (GST_BASE_SRC_CAST (src));
590   proxy = g_getenv ("http_proxy");
591   if (!gst_soup_http_src_set_proxy (src, proxy)) {
592     GST_WARNING_OBJECT (src,
593         "The proxy in the http_proxy env var (\"%s\") cannot be parsed.",
594         proxy);
595   }
596
597   gst_base_src_set_automatic_eos (GST_BASE_SRC (src), FALSE);
598
599   gst_soup_http_src_reset (src);
600 }
601
602 static void
603 gst_soup_http_src_dispose (GObject * gobject)
604 {
605   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (gobject);
606
607   GST_DEBUG_OBJECT (src, "dispose");
608
609   gst_soup_http_src_session_close (src);
610
611   g_clear_object (&src->external_session);
612
613   G_OBJECT_CLASS (parent_class)->dispose (gobject);
614 }
615
616 static void
617 gst_soup_http_src_finalize (GObject * gobject)
618 {
619   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (gobject);
620
621   GST_DEBUG_OBJECT (src, "finalize");
622
623   g_mutex_clear (&src->session_mutex);
624   g_cond_clear (&src->session_cond);
625   g_object_unref (src->cancellable);
626   g_free (src->location);
627   g_free (src->redirection_uri);
628   g_free (src->user_agent);
629   if (src->proxy != NULL) {
630     gst_soup_uri_free (src->proxy);
631   }
632   g_free (src->user_id);
633   g_free (src->user_pw);
634   g_free (src->proxy_id);
635   g_free (src->proxy_pw);
636   g_strfreev (src->cookies);
637
638   if (src->extra_headers) {
639     gst_structure_free (src->extra_headers);
640     src->extra_headers = NULL;
641   }
642
643   g_free (src->ssl_ca_file);
644
645   if (src->tls_database)
646     g_object_unref (src->tls_database);
647   g_free (src->method);
648
649   if (src->tls_interaction)
650     g_object_unref (src->tls_interaction);
651
652   G_OBJECT_CLASS (parent_class)->finalize (gobject);
653 }
654
655 static void
656 gst_soup_http_src_set_property (GObject * object, guint prop_id,
657     const GValue * value, GParamSpec * pspec)
658 {
659   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (object);
660
661   switch (prop_id) {
662     case PROP_LOCATION:
663     {
664       const gchar *location;
665
666       location = g_value_get_string (value);
667
668       if (location == NULL) {
669         GST_WARNING ("location property cannot be NULL");
670         goto done;
671       }
672       if (!gst_soup_http_src_set_location (src, location, NULL)) {
673         GST_WARNING ("badly formatted location");
674         goto done;
675       }
676       break;
677     }
678     case PROP_USER_AGENT:
679       g_free (src->user_agent);
680       src->user_agent = g_value_dup_string (value);
681       break;
682     case PROP_IRADIO_MODE:
683       src->iradio_mode = g_value_get_boolean (value);
684       break;
685     case PROP_AUTOMATIC_REDIRECT:
686       src->automatic_redirect = g_value_get_boolean (value);
687       break;
688     case PROP_PROXY:
689     {
690       const gchar *proxy;
691
692       proxy = g_value_get_string (value);
693       if (!gst_soup_http_src_set_proxy (src, proxy)) {
694         GST_WARNING ("badly formatted proxy URI");
695         goto done;
696       }
697       break;
698     }
699     case PROP_COOKIES:
700       g_strfreev (src->cookies);
701       src->cookies = g_strdupv (g_value_get_boxed (value));
702       break;
703     case PROP_IS_LIVE:
704       gst_base_src_set_live (GST_BASE_SRC (src), g_value_get_boolean (value));
705       break;
706     case PROP_USER_ID:
707       g_free (src->user_id);
708       src->user_id = g_value_dup_string (value);
709       break;
710     case PROP_USER_PW:
711       g_free (src->user_pw);
712       src->user_pw = g_value_dup_string (value);
713       break;
714     case PROP_PROXY_ID:
715       g_free (src->proxy_id);
716       src->proxy_id = g_value_dup_string (value);
717       break;
718     case PROP_PROXY_PW:
719       g_free (src->proxy_pw);
720       src->proxy_pw = g_value_dup_string (value);
721       break;
722     case PROP_TIMEOUT:
723       src->timeout = g_value_get_uint (value);
724       break;
725     case PROP_EXTRA_HEADERS:{
726       const GstStructure *s = gst_value_get_structure (value);
727
728       if (src->extra_headers)
729         gst_structure_free (src->extra_headers);
730
731       src->extra_headers = s ? gst_structure_copy (s) : NULL;
732       break;
733     }
734     case PROP_SOUP_LOG_LEVEL:
735       src->log_level = g_value_get_enum (value);
736       break;
737     case PROP_COMPRESS:
738       src->compress = g_value_get_boolean (value);
739       break;
740     case PROP_KEEP_ALIVE:
741       src->keep_alive = g_value_get_boolean (value);
742       break;
743     case PROP_SSL_STRICT:
744       src->ssl_strict = g_value_get_boolean (value);
745       break;
746     case PROP_TLS_DATABASE:
747       g_clear_object (&src->tls_database);
748       src->tls_database = g_value_dup_object (value);
749       break;
750     case PROP_TLS_INTERACTION:
751       g_clear_object (&src->tls_interaction);
752       src->tls_interaction = g_value_dup_object (value);
753       break;
754     case PROP_RETRIES:
755       src->max_retries = g_value_get_int (value);
756       break;
757     case PROP_METHOD:
758       g_free (src->method);
759       src->method = g_value_dup_string (value);
760       break;
761     case PROP_SSL_CA_FILE:
762       if (gst_soup_loader_get_api_version () == 2) {
763         g_free (src->ssl_ca_file);
764         src->ssl_ca_file = g_value_dup_string (value);
765       }
766       break;
767     case PROP_SSL_USE_SYSTEM_CA_FILE:
768       if (gst_soup_loader_get_api_version () == 2) {
769         src->ssl_use_system_ca_file = g_value_get_boolean (value);
770       }
771       break;
772     default:
773       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
774       break;
775   }
776 done:
777   return;
778 }
779
780 static void
781 gst_soup_http_src_get_property (GObject * object, guint prop_id,
782     GValue * value, GParamSpec * pspec)
783 {
784   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (object);
785
786   switch (prop_id) {
787     case PROP_LOCATION:
788       g_value_set_string (value, src->location);
789       break;
790     case PROP_USER_AGENT:
791       g_value_set_string (value, src->user_agent);
792       break;
793     case PROP_AUTOMATIC_REDIRECT:
794       g_value_set_boolean (value, src->automatic_redirect);
795       break;
796     case PROP_PROXY:
797       if (src->proxy == NULL)
798         g_value_set_static_string (value, "");
799       else {
800         char *proxy = gst_soup_uri_to_string (src->proxy);
801         g_value_set_string (value, proxy);
802         g_free (proxy);
803       }
804       break;
805     case PROP_COOKIES:
806       g_value_set_boxed (value, g_strdupv (src->cookies));
807       break;
808     case PROP_IS_LIVE:
809       g_value_set_boolean (value, gst_base_src_is_live (GST_BASE_SRC (src)));
810       break;
811     case PROP_IRADIO_MODE:
812       g_value_set_boolean (value, src->iradio_mode);
813       break;
814     case PROP_USER_ID:
815       g_value_set_string (value, src->user_id);
816       break;
817     case PROP_USER_PW:
818       g_value_set_string (value, src->user_pw);
819       break;
820     case PROP_PROXY_ID:
821       g_value_set_string (value, src->proxy_id);
822       break;
823     case PROP_PROXY_PW:
824       g_value_set_string (value, src->proxy_pw);
825       break;
826     case PROP_TIMEOUT:
827       g_value_set_uint (value, src->timeout);
828       break;
829     case PROP_EXTRA_HEADERS:
830       gst_value_set_structure (value, src->extra_headers);
831       break;
832     case PROP_SOUP_LOG_LEVEL:
833       g_value_set_enum (value, src->log_level);
834       break;
835     case PROP_COMPRESS:
836       g_value_set_boolean (value, src->compress);
837       break;
838     case PROP_KEEP_ALIVE:
839       g_value_set_boolean (value, src->keep_alive);
840       break;
841     case PROP_SSL_STRICT:
842       g_value_set_boolean (value, src->ssl_strict);
843       break;
844     case PROP_TLS_DATABASE:
845       g_value_set_object (value, src->tls_database);
846       break;
847     case PROP_TLS_INTERACTION:
848       g_value_set_object (value, src->tls_interaction);
849       break;
850     case PROP_RETRIES:
851       g_value_set_int (value, src->max_retries);
852       break;
853     case PROP_METHOD:
854       g_value_set_string (value, src->method);
855       break;
856     case PROP_SSL_CA_FILE:
857       if (gst_soup_loader_get_api_version () == 2)
858         g_value_set_string (value, src->ssl_ca_file);
859       break;
860     case PROP_SSL_USE_SYSTEM_CA_FILE:
861       if (gst_soup_loader_get_api_version () == 2)
862         g_value_set_boolean (value, src->ssl_use_system_ca_file);
863       break;
864     default:
865       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
866       break;
867   }
868 }
869
870 static gchar *
871 gst_soup_http_src_unicodify (const gchar * str)
872 {
873   const gchar *env_vars[] = { "GST_ICY_TAG_ENCODING",
874     "GST_TAG_ENCODING", NULL
875   };
876
877   return gst_tag_freeform_string_to_utf8 (str, -1, env_vars);
878 }
879
880 static gboolean
881 gst_soup_http_src_add_range_header (GstSoupHTTPSrc * src, guint64 offset,
882     guint64 stop_offset)
883 {
884   gchar buf[64];
885   gint rc;
886   SoupMessageHeaders *request_headers =
887       _soup_message_get_request_headers (src->msg);
888
889   _soup_message_headers_remove (request_headers, "Range");
890   if (offset || stop_offset != -1) {
891     if (stop_offset != -1) {
892       g_assert (offset != stop_offset);
893
894       rc = g_snprintf (buf, sizeof (buf), "bytes=%" G_GUINT64_FORMAT "-%"
895           G_GUINT64_FORMAT, offset, (stop_offset > 0) ? stop_offset - 1 :
896           stop_offset);
897     } else {
898       rc = g_snprintf (buf, sizeof (buf), "bytes=%" G_GUINT64_FORMAT "-",
899           offset);
900     }
901     if (rc > sizeof (buf) || rc < 0)
902       return FALSE;
903     _soup_message_headers_append (request_headers, "Range", buf);
904   }
905   src->read_position = offset;
906   return TRUE;
907 }
908
909 static gboolean
910 _append_extra_header (GQuark field_id, const GValue * value, gpointer user_data)
911 {
912   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (user_data);
913   const gchar *field_name = g_quark_to_string (field_id);
914   gchar *field_content = NULL;
915   SoupMessageHeaders *request_headers =
916       _soup_message_get_request_headers (src->msg);
917
918   if (G_VALUE_TYPE (value) == G_TYPE_STRING) {
919     field_content = g_value_dup_string (value);
920   } else {
921     GValue dest = { 0, };
922
923     g_value_init (&dest, G_TYPE_STRING);
924     if (g_value_transform (value, &dest)) {
925       field_content = g_value_dup_string (&dest);
926     }
927   }
928
929   if (field_content == NULL) {
930     GST_ERROR_OBJECT (src, "extra-headers field '%s' contains no value "
931         "or can't be converted to a string", field_name);
932     return FALSE;
933   }
934
935   GST_DEBUG_OBJECT (src, "Appending extra header: \"%s: %s\"", field_name,
936       field_content);
937   _soup_message_headers_append (request_headers, field_name, field_content);
938
939   g_free (field_content);
940
941   return TRUE;
942 }
943
944 static gboolean
945 _append_extra_headers (GQuark field_id, const GValue * value,
946     gpointer user_data)
947 {
948   if (G_VALUE_TYPE (value) == GST_TYPE_ARRAY) {
949     guint n = gst_value_array_get_size (value);
950     guint i;
951
952     for (i = 0; i < n; i++) {
953       const GValue *v = gst_value_array_get_value (value, i);
954
955       if (!_append_extra_header (field_id, v, user_data))
956         return FALSE;
957     }
958   } else if (G_VALUE_TYPE (value) == GST_TYPE_LIST) {
959     guint n = gst_value_list_get_size (value);
960     guint i;
961
962     for (i = 0; i < n; i++) {
963       const GValue *v = gst_value_list_get_value (value, i);
964
965       if (!_append_extra_header (field_id, v, user_data))
966         return FALSE;
967     }
968   } else {
969     return _append_extra_header (field_id, value, user_data);
970   }
971
972   return TRUE;
973 }
974
975
976 static gboolean
977 gst_soup_http_src_add_extra_headers (GstSoupHTTPSrc * src)
978 {
979   if (!src->extra_headers)
980     return TRUE;
981
982   return gst_structure_foreach (src->extra_headers, _append_extra_headers, src);
983 }
984
985 static gpointer
986 thread_func (gpointer user_data)
987 {
988   GstSoupHTTPSrc *src = user_data;
989   GstSoupSession *session = src->session;
990   GMainContext *ctx;
991
992   GST_DEBUG_OBJECT (src, "thread start");
993
994   ctx = g_main_loop_get_context (session->loop);
995
996   g_main_context_push_thread_default (ctx);
997
998   /* We explicitly set User-Agent to NULL here and overwrite it per message
999    * to be able to have the same session with different User-Agents per
1000    * source */
1001   session->session =
1002       _soup_session_new_with_options ("user-agent", NULL,
1003       "timeout", src->timeout, "tls-interaction", src->tls_interaction,
1004       /* Unset the limit the number of maximum allowed connections */
1005       "max-conns", src->session_is_shared ? G_MAXINT : 10,
1006       "max-conns-per-host", src->session_is_shared ? G_MAXINT : 2, NULL);
1007   g_assert (session->session);
1008
1009   if (gst_soup_loader_get_api_version () == 3) {
1010     if (src->proxy != NULL) {
1011       GProxyResolver *proxy_resolver;
1012       char *proxy_string = gst_soup_uri_to_string (src->proxy);
1013       proxy_resolver = g_simple_proxy_resolver_new (proxy_string, NULL);
1014       g_free (proxy_string);
1015       g_object_set (src->session->session, "proxy-resolver", proxy_resolver,
1016           NULL);
1017       g_object_unref (proxy_resolver);
1018     }
1019 #if !defined(STATIC_SOUP) || STATIC_SOUP == 2
1020   } else {
1021     g_object_set (session->session, "ssl-strict", src->ssl_strict, NULL);
1022     if (src->proxy != NULL) {
1023       /* Need #if because there's no proxy->soup_uri when STATIC_SOUP == 3 */
1024       g_object_set (session->session, "proxy-uri", src->proxy->soup_uri, NULL);
1025     }
1026 #endif
1027   }
1028
1029   gst_soup_util_log_setup (session->session, src->log_level,
1030       G_OBJECT (session));
1031   if (gst_soup_loader_get_api_version () < 3) {
1032     _soup_session_add_feature_by_type (session->session,
1033         _soup_content_decoder_get_type ());
1034   }
1035   _soup_session_add_feature_by_type (session->session,
1036       _soup_cookie_jar_get_type ());
1037
1038   /* soup2: connect the authenticate handler for the src that spawned the
1039    * session (i.e. the first owner); other users of this session will connect
1040    * their own after fetching the external session; the callback will handle
1041    * this correctly (it checks if the message belongs to the current src
1042    * and exits early if it does not)
1043    */
1044   if (gst_soup_loader_get_api_version () < 3) {
1045     g_signal_connect (session->session, "authenticate",
1046         G_CALLBACK (gst_soup_http_src_authenticate_cb_2), src);
1047   }
1048
1049   if (!src->session_is_shared) {
1050     if (src->tls_database)
1051       g_object_set (src->session->session, "tls-database", src->tls_database,
1052           NULL);
1053     else if (gst_soup_loader_get_api_version () == 2) {
1054       if (src->ssl_ca_file)
1055         g_object_set (src->session->session, "ssl-ca-file", src->ssl_ca_file,
1056             NULL);
1057       else
1058         g_object_set (src->session->session, "ssl-use-system-ca-file",
1059             src->ssl_use_system_ca_file, NULL);
1060     }
1061   }
1062
1063   /* Once the main loop is running, the source element that created this
1064    * session might disappear if the session is shared with other source
1065    * elements.
1066    */
1067   src = NULL;
1068
1069   g_main_loop_run (session->loop);
1070
1071   /* Abort any pending operations on the session ... */
1072   _soup_session_abort (session->session);
1073   g_clear_object (&session->session);
1074
1075   /* ... and iterate the main context until nothing is pending anymore */
1076   while (g_main_context_iteration (ctx, FALSE));
1077
1078   g_main_context_pop_thread_default (ctx);
1079
1080   GST_DEBUG_OBJECT (session, "thread stop");
1081
1082   return NULL;
1083 }
1084
1085 static gboolean
1086 _session_ready_cb (gpointer user_data)
1087 {
1088   GstSoupHTTPSrc *src = user_data;
1089
1090   GST_DEBUG_OBJECT (src, "thread ready");
1091
1092   g_mutex_lock (&src->session_mutex);
1093   g_cond_signal (&src->session_cond);
1094   g_mutex_unlock (&src->session_mutex);
1095
1096   return FALSE;
1097 }
1098
1099 /* called with session_mutex taken */
1100 static gboolean
1101 gst_soup_http_src_session_open (GstSoupHTTPSrc * src)
1102 {
1103   GstQuery *query;
1104   gboolean can_share;
1105
1106   if (src->session) {
1107     GST_DEBUG_OBJECT (src, "Session is already open");
1108     return TRUE;
1109   }
1110
1111   if (!src->location) {
1112     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (_("No URL set.")),
1113         ("Missing location property"));
1114     return FALSE;
1115   }
1116
1117   can_share = (src->timeout == DEFAULT_TIMEOUT)
1118       && (src->cookies == NULL)
1119       && (src->ssl_strict == DEFAULT_SSL_STRICT)
1120       && (src->tls_interaction == NULL) && (src->proxy == NULL)
1121       && (src->tls_database == DEFAULT_TLS_DATABASE);
1122
1123   if (gst_soup_loader_get_api_version () == 2)
1124     can_share = can_share && (src->ssl_ca_file == DEFAULT_SSL_CA_FILE) &&
1125         (src->ssl_use_system_ca_file == DEFAULT_SSL_USE_SYSTEM_CA_FILE);
1126
1127   query = gst_query_new_context (GST_SOUP_SESSION_CONTEXT);
1128   if (gst_pad_peer_query (GST_BASE_SRC_PAD (src), query)) {
1129     GstContext *context;
1130
1131     gst_query_parse_context (query, &context);
1132     gst_element_set_context (GST_ELEMENT_CAST (src), context);
1133   } else {
1134     GstMessage *message;
1135
1136     message =
1137         gst_message_new_need_context (GST_OBJECT_CAST (src),
1138         GST_SOUP_SESSION_CONTEXT);
1139     gst_element_post_message (GST_ELEMENT_CAST (src), message);
1140   }
1141   gst_query_unref (query);
1142
1143   GST_OBJECT_LOCK (src);
1144
1145   src->session_is_shared = can_share;
1146
1147   if (src->external_session && can_share) {
1148     GST_DEBUG_OBJECT (src, "Using external session %p", src->external_session);
1149     src->session = g_object_ref (src->external_session);
1150     /* for soup2, connect another authenticate handler; see thread_func */
1151     if (gst_soup_loader_get_api_version () < 3) {
1152       g_signal_connect (src->session->session, "authenticate",
1153           G_CALLBACK (gst_soup_http_src_authenticate_cb_2), src);
1154     }
1155   } else {
1156     GMainContext *ctx;
1157     GSource *source;
1158
1159     GST_DEBUG_OBJECT (src, "Creating session (can share %d)", can_share);
1160
1161     src->session =
1162         GST_SOUP_SESSION (g_object_new (GST_TYPE_SOUP_SESSION, NULL));
1163
1164     GST_DEBUG_OBJECT (src, "Created session %p", src->session);
1165
1166     ctx = g_main_context_new ();
1167
1168     src->session->loop = g_main_loop_new (ctx, FALSE);
1169     /* now owned by the loop */
1170     g_main_context_unref (ctx);
1171
1172     src->session->thread = g_thread_try_new ("souphttpsrc-thread",
1173         thread_func, src, NULL);
1174
1175     if (!src->session->thread) {
1176       goto err;
1177     }
1178
1179     source = g_idle_source_new ();
1180     g_source_set_callback (source, _session_ready_cb, src, NULL);
1181     g_source_attach (source, ctx);
1182     g_source_unref (source);
1183
1184     GST_DEBUG_OBJECT (src, "Waiting for thread to start...");
1185     while (!g_main_loop_is_running (src->session->loop))
1186       g_cond_wait (&src->session_cond, &src->session_mutex);
1187     GST_DEBUG_OBJECT (src, "Soup thread started");
1188   }
1189
1190   GST_OBJECT_UNLOCK (src);
1191
1192   if (src->session_is_shared) {
1193     GstContext *context;
1194     GstMessage *message;
1195     GstStructure *s;
1196
1197     GST_DEBUG_OBJECT (src->session, "Sharing session %p", src->session);
1198
1199     context = gst_context_new (GST_SOUP_SESSION_CONTEXT, TRUE);
1200     s = gst_context_writable_structure (context);
1201     gst_structure_set (s, "session", GST_TYPE_SOUP_SESSION, src->session, NULL);
1202
1203     gst_element_set_context (GST_ELEMENT_CAST (src), context);
1204     message = gst_message_new_have_context (GST_OBJECT_CAST (src), context);
1205     gst_element_post_message (GST_ELEMENT_CAST (src), message);
1206   }
1207
1208   return TRUE;
1209
1210 err:
1211   g_clear_object (&src->session);
1212   GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL), ("Failed to create session"));
1213   GST_OBJECT_UNLOCK (src);
1214
1215   return FALSE;
1216 }
1217
1218 static gboolean
1219 _session_close_cb (gpointer user_data)
1220 {
1221   GstSoupHTTPSrc *src = user_data;
1222
1223   if (src->msg) {
1224     gst_soup_session_cancel_message (src->session->session, src->msg,
1225         src->cancellable);
1226     g_clear_object (&src->msg);
1227   }
1228
1229   /* there may be multiple of this callback attached to the session,
1230    * each with different data pointer; disconnect the one we are closing
1231    * the session for, leave the others alone
1232    */
1233   g_signal_handlers_disconnect_by_func (src->session->session,
1234       G_CALLBACK (gst_soup_http_src_authenticate_cb_2), src);
1235
1236   g_mutex_lock (&src->session_mutex);
1237   g_clear_object (&src->session);
1238   g_cond_signal (&src->session_cond);
1239   g_mutex_unlock (&src->session_mutex);
1240
1241   return FALSE;
1242 }
1243
1244 static void
1245 gst_soup_http_src_session_close (GstSoupHTTPSrc * src)
1246 {
1247   GSource *source;
1248   GstSoupSession *sess;
1249
1250   GST_DEBUG_OBJECT (src, "Closing session");
1251
1252   if (!src->session) {
1253     return;
1254   }
1255
1256   /* ensure _session_close_cb does not deadlock us */
1257   sess = g_object_ref (src->session);
1258
1259   source = g_idle_source_new ();
1260
1261   g_mutex_lock (&src->session_mutex);
1262
1263   g_source_set_callback (source, _session_close_cb, src, NULL);
1264   g_source_attach (source, g_main_loop_get_context (src->session->loop));
1265   g_source_unref (source);
1266
1267   while (src->session)
1268     g_cond_wait (&src->session_cond, &src->session_mutex);
1269
1270   g_mutex_unlock (&src->session_mutex);
1271
1272   /* finally dispose of our reference from the gst thread */
1273   g_object_unref (sess);
1274 }
1275
1276 static void
1277 gst_soup_http_src_authenticate_cb_2 (SoupSession * session, SoupMessage * msg,
1278     SoupAuth * auth, gboolean retrying, gpointer data)
1279 {
1280   gst_soup_http_src_authenticate_cb (msg, auth, retrying, data);
1281 }
1282
1283 static gboolean
1284 gst_soup_http_src_authenticate_cb (SoupMessage * msg, SoupAuth * auth,
1285     gboolean retrying, gpointer data)
1286 {
1287   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (data);
1288   SoupStatus status_code;
1289
1290   /* Might be from another user of the shared session */
1291   if (!GST_IS_SOUP_HTTP_SRC (src) || msg != src->msg)
1292     return FALSE;
1293
1294   status_code = _soup_message_get_status (msg);
1295
1296   if (!retrying) {
1297     /* First time authentication only, if we fail and are called again with
1298      * retry true fall through */
1299     if (status_code == SOUP_STATUS_UNAUTHORIZED) {
1300       if (src->user_id && src->user_pw) {
1301         _soup_auth_authenticate (auth, src->user_id, src->user_pw);
1302       }
1303     } else if (status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED) {
1304       if (src->proxy_id && src->proxy_pw) {
1305         _soup_auth_authenticate (auth, src->proxy_id, src->proxy_pw);
1306       }
1307     }
1308   }
1309
1310   return FALSE;
1311 }
1312
1313 static gboolean
1314 gst_soup_http_src_accept_certificate_cb (SoupMessage * msg,
1315     GTlsCertificate * tls_certificate, GTlsCertificateFlags tls_errors,
1316     gpointer user_data)
1317 {
1318   GstSoupHTTPSrc *src = user_data;
1319
1320   /* Might be from another user of the shared session */
1321   if (!GST_IS_SOUP_HTTP_SRC (src) || msg != src->msg)
1322     return FALSE;
1323
1324   /* Accept invalid certificates */
1325   if (!src->ssl_strict)
1326     return TRUE;
1327
1328   return FALSE;
1329 }
1330
1331 static void
1332 insert_http_header (const gchar * name, const gchar * value, gpointer user_data)
1333 {
1334   GstStructure *headers = user_data;
1335   const GValue *gv;
1336
1337   if (!g_utf8_validate (name, -1, NULL) || !g_utf8_validate (value, -1, NULL))
1338     return;
1339
1340   gv = gst_structure_get_value (headers, name);
1341   if (gv && GST_VALUE_HOLDS_ARRAY (gv)) {
1342     GValue v = G_VALUE_INIT;
1343
1344     g_value_init (&v, G_TYPE_STRING);
1345     g_value_set_string (&v, value);
1346     gst_value_array_append_value ((GValue *) gv, &v);
1347     g_value_unset (&v);
1348   } else if (gv && G_VALUE_HOLDS_STRING (gv)) {
1349     GValue arr = G_VALUE_INIT;
1350     GValue v = G_VALUE_INIT;
1351     const gchar *old_value = g_value_get_string (gv);
1352
1353     g_value_init (&arr, GST_TYPE_ARRAY);
1354     g_value_init (&v, G_TYPE_STRING);
1355     g_value_set_string (&v, old_value);
1356     gst_value_array_append_value (&arr, &v);
1357     g_value_set_string (&v, value);
1358     gst_value_array_append_value (&arr, &v);
1359
1360     gst_structure_set_value (headers, name, &arr);
1361     g_value_unset (&v);
1362     g_value_unset (&arr);
1363   } else {
1364     gst_structure_set (headers, name, G_TYPE_STRING, value, NULL);
1365   }
1366 }
1367
1368 static GstFlowReturn
1369 gst_soup_http_src_got_headers (GstSoupHTTPSrc * src, SoupMessage * msg)
1370 {
1371   const char *value;
1372   GstTagList *tag_list;
1373   GstBaseSrc *basesrc;
1374   guint64 newsize;
1375   GHashTable *params = NULL;
1376   GstEvent *http_headers_event;
1377   GstStructure *http_headers, *headers;
1378   const gchar *accept_ranges;
1379   SoupMessageHeaders *request_headers = _soup_message_get_request_headers (msg);
1380   SoupMessageHeaders *response_headers =
1381       _soup_message_get_response_headers (msg);
1382   SoupStatus status_code = _soup_message_get_status (msg);
1383
1384   GST_INFO_OBJECT (src, "got headers");
1385
1386   if (status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED &&
1387       src->proxy_id && src->proxy_pw) {
1388     /* wait for authenticate callback */
1389     return GST_FLOW_OK;
1390   }
1391
1392   http_headers = gst_structure_new_empty ("http-headers");
1393   gst_structure_set (http_headers, "uri", G_TYPE_STRING, src->location,
1394       "http-status-code", G_TYPE_UINT, status_code, NULL);
1395   if (src->redirection_uri)
1396     gst_structure_set (http_headers, "redirection-uri", G_TYPE_STRING,
1397         src->redirection_uri, NULL);
1398   headers = gst_structure_new_empty ("request-headers");
1399   _soup_message_headers_foreach (request_headers, insert_http_header, headers);
1400   gst_structure_set (http_headers, "request-headers", GST_TYPE_STRUCTURE,
1401       headers, NULL);
1402   gst_structure_free (headers);
1403   headers = gst_structure_new_empty ("response-headers");
1404   _soup_message_headers_foreach (response_headers, insert_http_header, headers);
1405   gst_structure_set (http_headers, "response-headers", GST_TYPE_STRUCTURE,
1406       headers, NULL);
1407   gst_structure_free (headers);
1408
1409   gst_element_post_message (GST_ELEMENT_CAST (src),
1410       gst_message_new_element (GST_OBJECT_CAST (src),
1411           gst_structure_copy (http_headers)));
1412
1413   if (status_code == SOUP_STATUS_UNAUTHORIZED) {
1414     /* force an error */
1415     gst_structure_free (http_headers);
1416     return gst_soup_http_src_parse_status (msg, src);
1417   }
1418
1419   src->got_headers = TRUE;
1420
1421   http_headers_event =
1422       gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM_STICKY, http_headers);
1423   gst_event_replace (&src->http_headers_event, http_headers_event);
1424   gst_event_unref (http_headers_event);
1425
1426   /* Parse Content-Length. */
1427   if (SOUP_STATUS_IS_SUCCESSFUL (status_code) &&
1428       (_soup_message_headers_get_encoding (response_headers) ==
1429           SOUP_ENCODING_CONTENT_LENGTH)) {
1430     newsize = src->request_position +
1431         _soup_message_headers_get_content_length (response_headers);
1432     if (!src->have_size || (src->content_size != newsize)) {
1433       src->content_size = newsize;
1434       src->have_size = TRUE;
1435       src->seekable = TRUE;
1436       GST_DEBUG_OBJECT (src, "size = %" G_GUINT64_FORMAT, src->content_size);
1437
1438       basesrc = GST_BASE_SRC_CAST (src);
1439       basesrc->segment.duration = src->content_size;
1440       gst_element_post_message (GST_ELEMENT (src),
1441           gst_message_new_duration_changed (GST_OBJECT (src)));
1442     }
1443   }
1444
1445   /* If the server reports Accept-Ranges: none we don't have to try
1446    * doing range requests at all
1447    */
1448   if ((accept_ranges =
1449           _soup_message_headers_get_one (response_headers, "Accept-Ranges"))) {
1450     if (g_ascii_strcasecmp (accept_ranges, "none") == 0)
1451       src->seekable = FALSE;
1452   }
1453
1454   /* Icecast stuff */
1455   tag_list = gst_tag_list_new_empty ();
1456
1457   if ((value =
1458           _soup_message_headers_get_one (response_headers,
1459               "icy-metaint")) != NULL) {
1460     gint icy_metaint;
1461
1462     if (g_utf8_validate (value, -1, NULL)) {
1463       icy_metaint = atoi (value);
1464
1465       GST_DEBUG_OBJECT (src, "icy-metaint: %s (parsed: %d)", value,
1466           icy_metaint);
1467       if (icy_metaint > 0) {
1468         if (src->src_caps)
1469           gst_caps_unref (src->src_caps);
1470
1471         src->src_caps = gst_caps_new_simple ("application/x-icy",
1472             "metadata-interval", G_TYPE_INT, icy_metaint, NULL);
1473
1474         gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps);
1475       }
1476     }
1477   }
1478   if ((value =
1479           _soup_message_headers_get_content_type (response_headers,
1480               &params)) != NULL) {
1481     if (!g_utf8_validate (value, -1, NULL)) {
1482       GST_WARNING_OBJECT (src, "Content-Type is invalid UTF-8");
1483     } else if (g_ascii_strcasecmp (value, "audio/L16") == 0) {
1484       gint channels = 2;
1485       gint rate = 44100;
1486       char *param;
1487
1488       GST_DEBUG_OBJECT (src, "Content-Type: %s", value);
1489
1490       if (src->src_caps) {
1491         gst_caps_unref (src->src_caps);
1492         src->src_caps = NULL;
1493       }
1494
1495       param = g_hash_table_lookup (params, "channels");
1496       if (param != NULL) {
1497         guint64 val = g_ascii_strtoull (param, NULL, 10);
1498         if (val < 64)
1499           channels = val;
1500         else
1501           channels = 0;
1502       }
1503
1504       param = g_hash_table_lookup (params, "rate");
1505       if (param != NULL) {
1506         guint64 val = g_ascii_strtoull (param, NULL, 10);
1507         if (val < G_MAXINT)
1508           rate = val;
1509         else
1510           rate = 0;
1511       }
1512
1513       if (rate > 0 && channels > 0) {
1514         src->src_caps = gst_caps_new_simple ("audio/x-unaligned-raw",
1515             "format", G_TYPE_STRING, "S16BE",
1516             "layout", G_TYPE_STRING, "interleaved",
1517             "channels", G_TYPE_INT, channels, "rate", G_TYPE_INT, rate, NULL);
1518
1519         gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps);
1520       }
1521     } else {
1522       GST_DEBUG_OBJECT (src, "Content-Type: %s", value);
1523
1524       /* Set the Content-Type field on the caps */
1525       if (src->src_caps) {
1526         src->src_caps = gst_caps_make_writable (src->src_caps);
1527         gst_caps_set_simple (src->src_caps, "content-type", G_TYPE_STRING,
1528             value, NULL);
1529         gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps);
1530       }
1531     }
1532   }
1533
1534   if (params != NULL)
1535     g_hash_table_destroy (params);
1536
1537   if ((value =
1538           _soup_message_headers_get_one (response_headers,
1539               "icy-name")) != NULL) {
1540     if (g_utf8_validate (value, -1, NULL)) {
1541       g_free (src->iradio_name);
1542       src->iradio_name = gst_soup_http_src_unicodify (value);
1543       if (src->iradio_name) {
1544         gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_ORGANIZATION,
1545             src->iradio_name, NULL);
1546       }
1547     }
1548   }
1549   if ((value =
1550           _soup_message_headers_get_one (response_headers,
1551               "icy-genre")) != NULL) {
1552     if (g_utf8_validate (value, -1, NULL)) {
1553       g_free (src->iradio_genre);
1554       src->iradio_genre = gst_soup_http_src_unicodify (value);
1555       if (src->iradio_genre) {
1556         gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_GENRE,
1557             src->iradio_genre, NULL);
1558       }
1559     }
1560   }
1561   if ((value = _soup_message_headers_get_one (response_headers, "icy-url"))
1562       != NULL) {
1563     if (g_utf8_validate (value, -1, NULL)) {
1564       g_free (src->iradio_url);
1565       src->iradio_url = gst_soup_http_src_unicodify (value);
1566       if (src->iradio_url) {
1567         gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_LOCATION,
1568             src->iradio_url, NULL);
1569       }
1570     }
1571   }
1572   if (!gst_tag_list_is_empty (tag_list)) {
1573     GST_DEBUG_OBJECT (src,
1574         "calling gst_element_found_tags with %" GST_PTR_FORMAT, tag_list);
1575     gst_pad_push_event (GST_BASE_SRC_PAD (src), gst_event_new_tag (tag_list));
1576   } else {
1577     gst_tag_list_unref (tag_list);
1578   }
1579
1580   /* Handle HTTP errors. */
1581   return gst_soup_http_src_parse_status (msg, src);
1582 }
1583
1584 static GstBuffer *
1585 gst_soup_http_src_alloc_buffer (GstSoupHTTPSrc * src)
1586 {
1587   GstBaseSrc *basesrc = GST_BASE_SRC_CAST (src);
1588   GstFlowReturn rc;
1589   GstBuffer *gstbuf;
1590
1591   rc = GST_BASE_SRC_CLASS (parent_class)->alloc (basesrc, -1,
1592       basesrc->blocksize, &gstbuf);
1593   if (G_UNLIKELY (rc != GST_FLOW_OK)) {
1594     return NULL;
1595   }
1596
1597   return gstbuf;
1598 }
1599
1600 #define SOUP_HTTP_SRC_ERROR(src,soup_msg,cat,code,error_message)     \
1601   do { \
1602     GST_ELEMENT_ERROR_WITH_DETAILS ((src), cat, code, ("%s", error_message), \
1603         ("%s (%d), URL: %s, Redirect to: %s", _soup_message_get_reason_phrase (soup_msg), \
1604             _soup_message_get_status (soup_msg), (src)->location, GST_STR_NULL ((src)->redirection_uri)), \
1605             ("http-status-code", G_TYPE_UINT, _soup_message_get_status (soup_msg), \
1606              "http-redirect-uri", G_TYPE_STRING, GST_STR_NULL ((src)->redirection_uri), NULL)); \
1607   } while(0)
1608
1609 static GstFlowReturn
1610 gst_soup_http_src_parse_status (SoupMessage * msg, GstSoupHTTPSrc * src)
1611 {
1612   SoupStatus status_code = _soup_message_get_status (msg);
1613   if (_soup_message_get_method (msg) == SOUP_METHOD_HEAD) {
1614     if (!SOUP_STATUS_IS_SUCCESSFUL (status_code))
1615       GST_DEBUG_OBJECT (src, "Ignoring error %d during HEAD request",
1616           status_code);
1617     return GST_FLOW_OK;
1618   }
1619
1620   /* SOUP_STATUS_IS_TRANSPORT_ERROR was replaced with GError in libsoup-3.0 */
1621 #if !defined(STATIC_SOUP) || STATIC_SOUP == 2
1622   if (SOUP_STATUS_IS_TRANSPORT_ERROR (status_code)) {
1623     switch (status_code) {
1624       case SOUP_STATUS_CANT_RESOLVE:
1625       case SOUP_STATUS_CANT_RESOLVE_PROXY:
1626         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, NOT_FOUND,
1627             _("Could not resolve server name."));
1628         return GST_FLOW_ERROR;
1629       case SOUP_STATUS_CANT_CONNECT:
1630       case SOUP_STATUS_CANT_CONNECT_PROXY:
1631         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, OPEN_READ,
1632             _("Could not establish connection to server."));
1633         return GST_FLOW_ERROR;
1634       case SOUP_STATUS_SSL_FAILED:
1635         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, OPEN_READ,
1636             _("Secure connection setup failed."));
1637         return GST_FLOW_ERROR;
1638       case SOUP_STATUS_IO_ERROR:
1639         if (src->max_retries == -1 || src->retry_count < src->max_retries)
1640           return GST_FLOW_CUSTOM_ERROR;
1641         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, READ,
1642             _("A network error occurred, or the server closed the connection "
1643                 "unexpectedly."));
1644         return GST_FLOW_ERROR;
1645       case SOUP_STATUS_MALFORMED:
1646         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, READ,
1647             _("Server sent bad data."));
1648         return GST_FLOW_ERROR;
1649       case SOUP_STATUS_CANCELLED:
1650         /* No error message when interrupted by program. */
1651         break;
1652       default:
1653         break;
1654     }
1655     return GST_FLOW_OK;
1656   }
1657 #endif
1658
1659   if (SOUP_STATUS_IS_CLIENT_ERROR (status_code) ||
1660       SOUP_STATUS_IS_REDIRECTION (status_code) ||
1661       SOUP_STATUS_IS_SERVER_ERROR (status_code)) {
1662     const gchar *reason_phrase;
1663
1664     reason_phrase = _soup_message_get_reason_phrase (msg);
1665     if (reason_phrase && !g_utf8_validate (reason_phrase, -1, NULL)) {
1666       GST_ERROR_OBJECT (src, "Invalid UTF-8 in reason");
1667       reason_phrase = "(invalid)";
1668     }
1669
1670     /* Report HTTP error. */
1671
1672     /* when content_size is unknown and we have just finished receiving
1673      * a body message, requests that go beyond the content limits will result
1674      * in an error. Here we convert those to EOS */
1675     if (status_code == SOUP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE &&
1676         src->have_body && (!src->have_size ||
1677             (src->request_position >= src->content_size))) {
1678       GST_DEBUG_OBJECT (src, "Requested range out of limits and received full "
1679           "body, returning EOS");
1680       return GST_FLOW_EOS;
1681     }
1682
1683     /* FIXME: reason_phrase is not translated and not suitable for user
1684      * error dialog according to libsoup documentation.
1685      */
1686     if (status_code == SOUP_STATUS_NOT_FOUND) {
1687       SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, NOT_FOUND, (reason_phrase));
1688     } else if (status_code == SOUP_STATUS_UNAUTHORIZED
1689         || status_code == SOUP_STATUS_PAYMENT_REQUIRED
1690         || status_code == SOUP_STATUS_FORBIDDEN
1691         || status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED) {
1692       SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, NOT_AUTHORIZED, (reason_phrase));
1693     } else {
1694       SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, OPEN_READ, (reason_phrase));
1695     }
1696     return GST_FLOW_ERROR;
1697   }
1698
1699   return GST_FLOW_OK;
1700 }
1701
1702 static void
1703 gst_soup_http_src_restarted_cb (SoupMessage * msg, GstSoupHTTPSrc * src)
1704 {
1705   SoupStatus status = _soup_message_get_status (msg);
1706
1707   if (!SOUP_STATUS_IS_REDIRECTION (status))
1708     return;
1709
1710   src->redirection_uri = gst_soup_message_uri_to_string (msg);
1711   src->redirection_permanent = (status == SOUP_STATUS_MOVED_PERMANENTLY);
1712
1713   GST_DEBUG_OBJECT (src, "%u redirect to \"%s\" (permanent %d)",
1714       status, src->redirection_uri, src->redirection_permanent);
1715 }
1716
1717 static gboolean
1718 gst_soup_http_src_build_message (GstSoupHTTPSrc * src, const gchar * method)
1719 {
1720   SoupMessageHeaders *request_headers;
1721
1722   g_return_val_if_fail (src->msg == NULL, FALSE);
1723
1724   src->msg = _soup_message_new (method, src->location);
1725   if (!src->msg) {
1726     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
1727         ("Error parsing URL."), ("URL: %s", src->location));
1728     return FALSE;
1729   }
1730
1731   request_headers = _soup_message_get_request_headers (src->msg);
1732
1733   /* Duplicating the defaults of libsoup here. We don't want to set a
1734    * User-Agent in the session as each source might have its own User-Agent
1735    * set */
1736   if (!src->user_agent || !*src->user_agent) {
1737     gchar *user_agent =
1738         g_strdup_printf ("libsoup/%u.%u.%u", _soup_get_major_version (),
1739         _soup_get_minor_version (), _soup_get_micro_version ());
1740     _soup_message_headers_append (request_headers, "User-Agent", user_agent);
1741     g_free (user_agent);
1742   } else if (g_str_has_suffix (src->user_agent, " ")) {
1743     gchar *user_agent = g_strdup_printf ("%slibsoup/%u.%u.%u", src->user_agent,
1744         _soup_get_major_version (),
1745         _soup_get_minor_version (), _soup_get_micro_version ());
1746     _soup_message_headers_append (request_headers, "User-Agent", user_agent);
1747     g_free (user_agent);
1748   } else {
1749     _soup_message_headers_append (request_headers, "User-Agent",
1750         src->user_agent);
1751   }
1752
1753   if (!src->keep_alive) {
1754     _soup_message_headers_append (request_headers, "Connection", "close");
1755   }
1756   if (src->iradio_mode) {
1757     _soup_message_headers_append (request_headers, "icy-metadata", "1");
1758   }
1759   if (src->cookies) {
1760     gchar **cookie;
1761
1762     for (cookie = src->cookies; *cookie != NULL; cookie++) {
1763       _soup_message_headers_append (request_headers, "Cookie", *cookie);
1764     }
1765
1766     _soup_message_disable_feature (src->msg, _soup_cookie_jar_get_type ());
1767   }
1768
1769   if (!src->compress) {
1770     _soup_message_headers_append (_soup_message_get_request_headers (src->msg),
1771         "Accept-Encoding", "identity");
1772   }
1773
1774   if (gst_soup_loader_get_api_version () == 3) {
1775     g_signal_connect (src->msg, "accept-certificate",
1776         G_CALLBACK (gst_soup_http_src_accept_certificate_cb), src);
1777     g_signal_connect (src->msg, "authenticate",
1778         G_CALLBACK (gst_soup_http_src_authenticate_cb), src);
1779   }
1780
1781   {
1782     SoupMessageFlags flags =
1783         src->automatic_redirect ? 0 : SOUP_MESSAGE_NO_REDIRECT;
1784
1785     /* SOUP_MESSAGE_OVERWRITE_CHUNKS is gone in libsoup-3.0, and
1786      * soup_message_body_set_accumulate() requires SoupMessageBody, which
1787      * can only be fetched from SoupServerMessage, not SoupMessage */
1788 #if !defined(STATIC_SOUP) || STATIC_SOUP == 2
1789     if (gst_soup_loader_get_api_version () == 2)
1790       flags |= SOUP_MESSAGE_OVERWRITE_CHUNKS;
1791 #endif
1792
1793     _soup_message_set_flags (src->msg, flags);
1794   }
1795
1796   if (src->automatic_redirect) {
1797     g_signal_connect (src->msg, "restarted",
1798         G_CALLBACK (gst_soup_http_src_restarted_cb), src);
1799   }
1800
1801   gst_soup_http_src_add_range_header (src, src->request_position,
1802       src->stop_position);
1803
1804   gst_soup_http_src_add_extra_headers (src);
1805
1806   return TRUE;
1807 }
1808
1809 struct GstSoupSendSrc
1810 {
1811   GstSoupHTTPSrc *src;
1812   GError *error;
1813 };
1814
1815 static void
1816 _session_send_cb (GObject * source, GAsyncResult * res, gpointer user_data)
1817 {
1818   struct GstSoupSendSrc *msrc = user_data;
1819   GstSoupHTTPSrc *src = msrc->src;
1820   GError *error = NULL;
1821
1822   g_mutex_lock (&src->session_mutex);
1823
1824   src->input_stream = _soup_session_send_finish (src->session->session,
1825       res, &error);
1826
1827   if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
1828     src->headers_ret = GST_FLOW_FLUSHING;
1829   } else {
1830     src->headers_ret = gst_soup_http_src_got_headers (src, src->msg);
1831   }
1832
1833   if (!src->input_stream) {
1834     GST_DEBUG_OBJECT (src, "Sending message failed: %s", error->message);
1835     msrc->error = error;
1836   }
1837
1838   g_cond_broadcast (&src->session_cond);
1839   g_mutex_unlock (&src->session_mutex);
1840 }
1841
1842 static gboolean
1843 _session_send_idle_cb (gpointer user_data)
1844 {
1845   struct GstSoupSendSrc *msrc = user_data;
1846   GstSoupHTTPSrc *src = msrc->src;
1847
1848   _soup_session_send_async (src->session->session, src->msg, src->cancellable,
1849       _session_send_cb, msrc);
1850
1851   return FALSE;
1852 }
1853
1854 /* called with session lock taken */
1855 static GstFlowReturn
1856 gst_soup_http_src_send_message (GstSoupHTTPSrc * src)
1857 {
1858   GstFlowReturn ret;
1859   GSource *source;
1860   struct GstSoupSendSrc msrc;
1861
1862   g_return_val_if_fail (src->msg != NULL, GST_FLOW_ERROR);
1863   g_assert (src->input_stream == NULL);
1864
1865   msrc.src = src;
1866   msrc.error = NULL;
1867
1868   source = g_idle_source_new ();
1869
1870   src->headers_ret = GST_FLOW_OK;
1871
1872   g_source_set_callback (source, _session_send_idle_cb, &msrc, NULL);
1873   g_source_attach (source, g_main_loop_get_context (src->session->loop));
1874   g_source_unref (source);
1875
1876   while (!src->input_stream && !msrc.error)
1877     g_cond_wait (&src->session_cond, &src->session_mutex);
1878
1879   ret = src->headers_ret;
1880
1881   if (ret != GST_FLOW_OK) {
1882     goto done;
1883   }
1884
1885   if (!src->input_stream) {
1886     GST_DEBUG_OBJECT (src, "Didn't get an input stream: %s",
1887         msrc.error->message);
1888     ret = GST_FLOW_ERROR;
1889     goto done;
1890   }
1891
1892   /* if an input stream exists, it was always successful */
1893   GST_DEBUG_OBJECT (src, "Successfully got a reply");
1894
1895 done:
1896   g_clear_error (&msrc.error);
1897   return ret;
1898 }
1899
1900 /* called with session lock taken */
1901 static GstFlowReturn
1902 gst_soup_http_src_do_request (GstSoupHTTPSrc * src, const gchar * method)
1903 {
1904   GstFlowReturn ret;
1905   SoupMessageHeaders *request_headers;
1906
1907   if (src->max_retries != -1 && src->retry_count > src->max_retries) {
1908     GST_DEBUG_OBJECT (src, "Max retries reached");
1909     return GST_FLOW_ERROR;
1910   }
1911
1912   src->retry_count++;
1913   /* EOS immediately if we have an empty segment */
1914   if (src->request_position == src->stop_position)
1915     return GST_FLOW_EOS;
1916
1917   GST_LOG_OBJECT (src, "Running request for method: %s", method);
1918
1919   if (src->msg)
1920     request_headers = _soup_message_get_request_headers (src->msg);
1921
1922   /* Update the position if we are retrying */
1923   if (src->msg && src->request_position > 0) {
1924     gst_soup_http_src_add_range_header (src, src->request_position,
1925         src->stop_position);
1926   } else if (src->msg && src->request_position == 0)
1927     _soup_message_headers_remove (request_headers, "Range");
1928
1929   /* add_range_header() has the side effect of setting read_position to
1930    * the requested position. This *needs* to be set regardless of having
1931    * a message or not. Failure to do so would result in calculation being
1932    * done with stale/wrong read position */
1933   src->read_position = src->request_position;
1934
1935   if (!src->msg) {
1936     if (!gst_soup_http_src_build_message (src, method)) {
1937       return GST_FLOW_ERROR;
1938     }
1939   }
1940
1941   if (g_cancellable_is_cancelled (src->cancellable)) {
1942     GST_INFO_OBJECT (src, "interrupted");
1943     return GST_FLOW_FLUSHING;
1944   }
1945
1946   ret = gst_soup_http_src_send_message (src);
1947
1948   /* Check if Range header was respected. */
1949   if (ret == GST_FLOW_OK && src->request_position > 0 &&
1950       _soup_message_get_status (src->msg) != SOUP_STATUS_PARTIAL_CONTENT) {
1951     src->seekable = FALSE;
1952     GST_ELEMENT_ERROR_WITH_DETAILS (src, RESOURCE, SEEK,
1953         (_("Server does not support seeking.")),
1954         ("Server does not accept Range HTTP header, URL: %s, Redirect to: %s",
1955             src->location, GST_STR_NULL (src->redirection_uri)),
1956         ("http-status-code", G_TYPE_UINT, _soup_message_get_status (src->msg),
1957             "http-redirection-uri", G_TYPE_STRING,
1958             GST_STR_NULL (src->redirection_uri), NULL));
1959     ret = GST_FLOW_ERROR;
1960   }
1961
1962   return ret;
1963 }
1964
1965 /*
1966  * Check if the bytes_read is above a certain threshold of the blocksize, if
1967  * that happens a few times in a row, increase the blocksize; Do the same in
1968  * the opposite direction to reduce the blocksize.
1969  */
1970 static void
1971 gst_soup_http_src_check_update_blocksize (GstSoupHTTPSrc * src,
1972     gint64 bytes_read)
1973 {
1974   guint blocksize = gst_base_src_get_blocksize (GST_BASE_SRC_CAST (src));
1975
1976   gint64 time_since_last_read =
1977       g_get_monotonic_time () * GST_USECOND - src->last_socket_read_time;
1978
1979   GST_LOG_OBJECT (src, "Checking to update blocksize. Read: %" G_GINT64_FORMAT
1980       " bytes, blocksize: %u bytes, time since last read: %" GST_TIME_FORMAT,
1981       bytes_read, blocksize, GST_TIME_ARGS (time_since_last_read));
1982
1983   if (bytes_read >= blocksize * GROW_BLOCKSIZE_LIMIT
1984       && time_since_last_read <= GROW_TIME_LIMIT) {
1985     src->reduce_blocksize_count = 0;
1986     src->increase_blocksize_count++;
1987
1988     if (src->increase_blocksize_count >= GROW_BLOCKSIZE_COUNT) {
1989       blocksize *= GROW_BLOCKSIZE_FACTOR;
1990       GST_DEBUG_OBJECT (src, "Increased blocksize to %u", blocksize);
1991       gst_base_src_set_blocksize (GST_BASE_SRC_CAST (src), blocksize);
1992       src->increase_blocksize_count = 0;
1993     }
1994   } else if (bytes_read < blocksize * REDUCE_BLOCKSIZE_LIMIT
1995       || time_since_last_read > GROW_TIME_LIMIT) {
1996     src->reduce_blocksize_count++;
1997     src->increase_blocksize_count = 0;
1998
1999     if (src->reduce_blocksize_count >= REDUCE_BLOCKSIZE_COUNT) {
2000       blocksize *= REDUCE_BLOCKSIZE_FACTOR;
2001       blocksize = MAX (blocksize, src->minimum_blocksize);
2002       GST_DEBUG_OBJECT (src, "Decreased blocksize to %u", blocksize);
2003       gst_base_src_set_blocksize (GST_BASE_SRC_CAST (src), blocksize);
2004       src->reduce_blocksize_count = 0;
2005     }
2006   } else {
2007     src->reduce_blocksize_count = src->increase_blocksize_count = 0;
2008   }
2009 }
2010
2011 static void
2012 gst_soup_http_src_update_position (GstSoupHTTPSrc * src, gint64 bytes_read)
2013 {
2014   GstBaseSrc *basesrc = GST_BASE_SRC_CAST (src);
2015   guint64 new_position;
2016
2017   new_position = src->read_position + bytes_read;
2018   if (G_LIKELY (src->request_position == src->read_position))
2019     src->request_position = new_position;
2020   src->read_position = new_position;
2021
2022   if (src->have_size) {
2023     if (new_position > src->content_size) {
2024       GST_DEBUG_OBJECT (src, "Got position previous estimated content size "
2025           "(%" G_GINT64_FORMAT " > %" G_GINT64_FORMAT ")", new_position,
2026           src->content_size);
2027       src->content_size = new_position;
2028       basesrc->segment.duration = src->content_size;
2029       gst_element_post_message (GST_ELEMENT (src),
2030           gst_message_new_duration_changed (GST_OBJECT (src)));
2031     } else if (new_position == src->content_size) {
2032       GST_DEBUG_OBJECT (src, "We're EOS now");
2033     }
2034   }
2035 }
2036
2037 struct GstSoupReadResult
2038 {
2039   GstSoupHTTPSrc *src;
2040   GError *error;
2041   void *buffer;
2042   gsize bufsize;
2043   gssize nbytes;
2044 };
2045
2046 static void
2047 _session_read_cb (GObject * source, GAsyncResult * ret, gpointer user_data)
2048 {
2049   struct GstSoupReadResult *res = user_data;
2050
2051   g_mutex_lock (&res->src->session_mutex);
2052
2053   res->nbytes = g_input_stream_read_finish (G_INPUT_STREAM (source),
2054       ret, &res->error);
2055
2056   g_cond_signal (&res->src->session_cond);
2057   g_mutex_unlock (&res->src->session_mutex);
2058 }
2059
2060 static gboolean
2061 _session_read_idle_cb (gpointer user_data)
2062 {
2063   struct GstSoupReadResult *res = user_data;
2064
2065   g_input_stream_read_async (res->src->input_stream, res->buffer,
2066       res->bufsize, G_PRIORITY_DEFAULT, res->src->cancellable,
2067       _session_read_cb, res);
2068
2069   return FALSE;
2070 }
2071
2072 static GstFlowReturn
2073 gst_soup_http_src_read_buffer (GstSoupHTTPSrc * src, GstBuffer ** outbuf)
2074 {
2075   struct GstSoupReadResult res;
2076   GstMapInfo mapinfo;
2077   GstBaseSrc *bsrc;
2078   GstFlowReturn ret;
2079   GSource *source;
2080
2081   bsrc = GST_BASE_SRC_CAST (src);
2082
2083   *outbuf = gst_soup_http_src_alloc_buffer (src);
2084   if (!*outbuf) {
2085     GST_WARNING_OBJECT (src, "Failed to allocate buffer");
2086     return GST_FLOW_ERROR;
2087   }
2088
2089   if (!gst_buffer_map (*outbuf, &mapinfo, GST_MAP_WRITE)) {
2090     GST_WARNING_OBJECT (src, "Failed to map buffer");
2091     return GST_FLOW_ERROR;
2092   }
2093
2094   res.src = src;
2095   res.buffer = mapinfo.data;
2096   res.bufsize = mapinfo.size;
2097   res.error = NULL;
2098   res.nbytes = -1;
2099
2100   source = g_idle_source_new ();
2101
2102   g_mutex_lock (&src->session_mutex);
2103
2104   g_source_set_callback (source, _session_read_idle_cb, &res, NULL);
2105   /* invoke on libsoup thread */
2106   g_source_attach (source, g_main_loop_get_context (src->session->loop));
2107   g_source_unref (source);
2108
2109   /* wait for it */
2110   while (!res.error && res.nbytes < 0)
2111     g_cond_wait (&src->session_cond, &src->session_mutex);
2112   g_mutex_unlock (&src->session_mutex);
2113
2114   GST_DEBUG_OBJECT (src, "Read %" G_GSSIZE_FORMAT " bytes from http input",
2115       res.nbytes);
2116
2117   if (res.error) {
2118     /* retry by default */
2119     GstFlowReturn ret = GST_FLOW_CUSTOM_ERROR;
2120     if (g_error_matches (res.error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
2121       ret = GST_FLOW_FLUSHING;
2122     } else {
2123       GST_ERROR_OBJECT (src, "Got error from libsoup: %s", res.error->message);
2124     }
2125     g_error_free (res.error);
2126     gst_buffer_unmap (*outbuf, &mapinfo);
2127     gst_buffer_unref (*outbuf);
2128     return ret;
2129   }
2130
2131   gst_buffer_unmap (*outbuf, &mapinfo);
2132   if (res.nbytes > 0) {
2133     gst_buffer_set_size (*outbuf, res.nbytes);
2134     GST_BUFFER_OFFSET (*outbuf) = bsrc->segment.position;
2135     ret = GST_FLOW_OK;
2136     gst_soup_http_src_update_position (src, res.nbytes);
2137
2138     /* Got some data, reset retry counter */
2139     src->retry_count = 0;
2140
2141     gst_soup_http_src_check_update_blocksize (src, res.nbytes);
2142
2143     src->last_socket_read_time = g_get_monotonic_time () * GST_USECOND;
2144
2145     /* If we're at the end of a range request, read again to let libsoup
2146      * finalize the request. This allows to reuse the connection again later,
2147      * otherwise we would have to cancel the message and close the connection
2148      */
2149     if (bsrc->segment.stop != -1
2150         && bsrc->segment.position + res.nbytes >= bsrc->segment.stop) {
2151       SoupMessage *msg = src->msg;
2152       guint8 tmp[128];
2153
2154       res.buffer = tmp;
2155       res.bufsize = sizeof (tmp);
2156       res.nbytes = -1;
2157
2158       src->msg = NULL;
2159       src->have_body = TRUE;
2160
2161       g_mutex_lock (&src->session_mutex);
2162
2163       source = g_idle_source_new ();
2164
2165       g_source_set_callback (source, _session_read_idle_cb, &res, NULL);
2166       /* This should return immediately as we're at the end of the range */
2167       g_source_attach (source, g_main_loop_get_context (src->session->loop));
2168       g_source_unref (source);
2169
2170       while (!res.error && res.nbytes < 0)
2171         g_cond_wait (&src->session_cond, &src->session_mutex);
2172       g_mutex_unlock (&src->session_mutex);
2173
2174       g_clear_error (&res.error);
2175       g_object_unref (msg);
2176
2177       if (res.nbytes > 0)
2178         GST_ERROR_OBJECT (src,
2179             "Read %" G_GSIZE_FORMAT " bytes after end of range", res.nbytes);
2180     }
2181   } else {
2182     gst_buffer_unref (*outbuf);
2183     if (src->have_size && src->read_position < src->content_size) {
2184       /* Maybe the server disconnected, retry */
2185       ret = GST_FLOW_CUSTOM_ERROR;
2186     } else {
2187       g_clear_object (&src->msg);
2188       src->msg = NULL;
2189       ret = GST_FLOW_EOS;
2190       src->have_body = TRUE;
2191     }
2192   }
2193
2194   g_clear_error (&res.error);
2195
2196   return ret;
2197 }
2198
2199 static gboolean
2200 _session_stream_clear_cb (gpointer user_data)
2201 {
2202   GstSoupHTTPSrc *src = user_data;
2203
2204   g_mutex_lock (&src->session_mutex);
2205
2206   g_clear_object (&src->input_stream);
2207
2208   g_cond_signal (&src->session_cond);
2209   g_mutex_unlock (&src->session_mutex);
2210
2211   return FALSE;
2212 }
2213
2214 static void
2215 gst_soup_http_src_stream_clear (GstSoupHTTPSrc * src)
2216 {
2217   GSource *source;
2218
2219   if (!src->input_stream)
2220     return;
2221
2222   g_mutex_lock (&src->session_mutex);
2223
2224   source = g_idle_source_new ();
2225
2226   g_source_set_callback (source, _session_stream_clear_cb, src, NULL);
2227   g_source_attach (source, g_main_loop_get_context (src->session->loop));
2228   g_source_unref (source);
2229
2230   while (src->input_stream)
2231     g_cond_wait (&src->session_cond, &src->session_mutex);
2232
2233   g_mutex_unlock (&src->session_mutex);
2234 }
2235
2236 static GstFlowReturn
2237 gst_soup_http_src_create (GstPushSrc * psrc, GstBuffer ** outbuf)
2238 {
2239   GstSoupHTTPSrc *src;
2240   GstFlowReturn ret = GST_FLOW_OK;
2241   GstEvent *http_headers_event = NULL;
2242
2243   src = GST_SOUP_HTTP_SRC (psrc);
2244
2245 retry:
2246
2247   /* Check for pending position change */
2248   if (src->request_position != src->read_position && src->input_stream) {
2249     gst_soup_http_src_stream_clear (src);
2250   }
2251
2252   if (g_cancellable_is_cancelled (src->cancellable)) {
2253     ret = GST_FLOW_FLUSHING;
2254     goto done;
2255   }
2256
2257   /* If we have no open connection to the server, start one */
2258   if (!src->input_stream) {
2259     *outbuf = NULL;
2260     g_mutex_lock (&src->session_mutex);
2261     ret =
2262         gst_soup_http_src_do_request (src,
2263         src->method ? src->method : SOUP_METHOD_GET);
2264     http_headers_event = src->http_headers_event;
2265     src->http_headers_event = NULL;
2266     g_mutex_unlock (&src->session_mutex);
2267   }
2268
2269   if (ret == GST_FLOW_OK || ret == GST_FLOW_CUSTOM_ERROR) {
2270     if (http_headers_event) {
2271       gst_pad_push_event (GST_BASE_SRC_PAD (src), http_headers_event);
2272       http_headers_event = NULL;
2273     }
2274   }
2275
2276   if (ret == GST_FLOW_OK)
2277     ret = gst_soup_http_src_read_buffer (src, outbuf);
2278
2279 done:
2280   GST_DEBUG_OBJECT (src, "Returning %d %s", ret, gst_flow_get_name (ret));
2281   if (ret != GST_FLOW_OK) {
2282     if (http_headers_event)
2283       gst_event_unref (http_headers_event);
2284
2285     if (src->input_stream) {
2286       gst_soup_http_src_stream_clear (src);
2287     }
2288     if (ret == GST_FLOW_CUSTOM_ERROR) {
2289       ret = GST_FLOW_OK;
2290       goto retry;
2291     }
2292   }
2293
2294   if (ret == GST_FLOW_FLUSHING) {
2295     src->retry_count = 0;
2296   }
2297
2298   return ret;
2299 }
2300
2301 static gboolean
2302 gst_soup_http_src_start (GstBaseSrc * bsrc)
2303 {
2304   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
2305   gboolean ret;
2306
2307   GST_DEBUG_OBJECT (src, "start(\"%s\")", src->location);
2308
2309   g_mutex_lock (&src->session_mutex);
2310   ret = gst_soup_http_src_session_open (src);
2311   g_mutex_unlock (&src->session_mutex);
2312   return ret;
2313 }
2314
2315 static gboolean
2316 gst_soup_http_src_stop (GstBaseSrc * bsrc)
2317 {
2318   GstSoupHTTPSrc *src;
2319
2320   src = GST_SOUP_HTTP_SRC (bsrc);
2321   GST_DEBUG_OBJECT (src, "stop()");
2322
2323   gst_soup_http_src_stream_clear (src);
2324
2325   if (src->keep_alive && !src->msg && !src->session_is_shared)
2326     g_cancellable_cancel (src->cancellable);
2327   else
2328     gst_soup_http_src_session_close (src);
2329
2330   gst_soup_http_src_reset (src);
2331   return TRUE;
2332 }
2333
2334 static GstStateChangeReturn
2335 gst_soup_http_src_change_state (GstElement * element, GstStateChange transition)
2336 {
2337   GstStateChangeReturn ret;
2338   GstSoupHTTPSrc *src;
2339
2340   src = GST_SOUP_HTTP_SRC (element);
2341
2342   switch (transition) {
2343     case GST_STATE_CHANGE_READY_TO_NULL:
2344       gst_soup_http_src_session_close (src);
2345       break;
2346     default:
2347       break;
2348   }
2349
2350   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2351
2352   return ret;
2353 }
2354
2355 static void
2356 gst_soup_http_src_set_context (GstElement * element, GstContext * context)
2357 {
2358   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (element);
2359
2360   if (g_strcmp0 (gst_context_get_context_type (context),
2361           GST_SOUP_SESSION_CONTEXT) == 0) {
2362     const GstStructure *s = gst_context_get_structure (context);
2363
2364     GST_OBJECT_LOCK (src);
2365
2366     g_clear_object (&src->external_session);
2367     gst_structure_get (s, "session", GST_TYPE_SOUP_SESSION,
2368         &src->external_session, NULL);
2369
2370     GST_DEBUG_OBJECT (src, "Setting external session %p",
2371         src->external_session);
2372     GST_OBJECT_UNLOCK (src);
2373   }
2374
2375   GST_ELEMENT_CLASS (parent_class)->set_context (element, context);
2376 }
2377
2378 /* Interrupt a blocking request. */
2379 static gboolean
2380 gst_soup_http_src_unlock (GstBaseSrc * bsrc)
2381 {
2382   GstSoupHTTPSrc *src;
2383
2384   src = GST_SOUP_HTTP_SRC (bsrc);
2385   GST_DEBUG_OBJECT (src, "unlock()");
2386
2387   g_cancellable_cancel (src->cancellable);
2388   return TRUE;
2389 }
2390
2391 /* Interrupt interrupt. */
2392 static gboolean
2393 gst_soup_http_src_unlock_stop (GstBaseSrc * bsrc)
2394 {
2395   GstSoupHTTPSrc *src;
2396
2397   src = GST_SOUP_HTTP_SRC (bsrc);
2398   GST_DEBUG_OBJECT (src, "unlock_stop()");
2399
2400   g_cancellable_reset (src->cancellable);
2401   return TRUE;
2402 }
2403
2404 static gboolean
2405 gst_soup_http_src_get_size (GstBaseSrc * bsrc, guint64 * size)
2406 {
2407   GstSoupHTTPSrc *src;
2408
2409   src = GST_SOUP_HTTP_SRC (bsrc);
2410
2411   if (src->have_size) {
2412     GST_DEBUG_OBJECT (src, "get_size() = %" G_GUINT64_FORMAT,
2413         src->content_size);
2414     *size = src->content_size;
2415     return TRUE;
2416   }
2417   GST_DEBUG_OBJECT (src, "get_size() = FALSE");
2418   return FALSE;
2419 }
2420
2421 static void
2422 gst_soup_http_src_check_seekable (GstSoupHTTPSrc * src)
2423 {
2424   GstFlowReturn ret = GST_FLOW_OK;
2425
2426   /* Special case to check if the server allows range requests
2427    * before really starting to get data in the buffer creation
2428    * loops.
2429    */
2430   if (!src->got_headers && GST_STATE (src) >= GST_STATE_PAUSED) {
2431     g_mutex_lock (&src->session_mutex);
2432     while (!src->got_headers && !g_cancellable_is_cancelled (src->cancellable)
2433         && ret == GST_FLOW_OK) {
2434       if ((src->msg && _soup_message_get_method (src->msg) != SOUP_METHOD_HEAD)) {
2435         /* wait for the current request to finish */
2436         g_cond_wait (&src->session_cond, &src->session_mutex);
2437         ret = src->headers_ret;
2438       } else {
2439         if (gst_soup_http_src_session_open (src)) {
2440           ret = gst_soup_http_src_do_request (src, SOUP_METHOD_HEAD);
2441         }
2442       }
2443     }
2444     g_mutex_unlock (&src->session_mutex);
2445   }
2446 }
2447
2448 static gboolean
2449 gst_soup_http_src_is_seekable (GstBaseSrc * bsrc)
2450 {
2451   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
2452
2453   gst_soup_http_src_check_seekable (src);
2454
2455   return src->seekable;
2456 }
2457
2458 static gboolean
2459 gst_soup_http_src_do_seek (GstBaseSrc * bsrc, GstSegment * segment)
2460 {
2461   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
2462
2463   GST_DEBUG_OBJECT (src, "do_seek(%" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT
2464       ")", segment->start, segment->stop);
2465   if (src->read_position == segment->start &&
2466       src->request_position == src->read_position &&
2467       src->stop_position == segment->stop) {
2468     GST_DEBUG_OBJECT (src,
2469         "Seek to current read/end position and no seek pending");
2470     return TRUE;
2471   }
2472
2473   gst_soup_http_src_check_seekable (src);
2474
2475   /* If we have no headers we don't know yet if it is seekable or not.
2476    * Store the start position and error out later if it isn't */
2477   if (src->got_headers && !src->seekable) {
2478     GST_WARNING_OBJECT (src, "Not seekable");
2479     return FALSE;
2480   }
2481
2482   if (segment->rate < 0.0 || segment->format != GST_FORMAT_BYTES) {
2483     GST_WARNING_OBJECT (src, "Invalid seek segment");
2484     return FALSE;
2485   }
2486
2487   if (src->have_size && segment->start >= src->content_size) {
2488     GST_WARNING_OBJECT (src,
2489         "Potentially seeking behind end of file, might EOS immediately");
2490   }
2491
2492   /* Wait for create() to handle the jump in offset. */
2493   src->request_position = segment->start;
2494   src->stop_position = segment->stop;
2495
2496   return TRUE;
2497 }
2498
2499 static gboolean
2500 gst_soup_http_src_query (GstBaseSrc * bsrc, GstQuery * query)
2501 {
2502   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
2503   gboolean ret;
2504   GstSchedulingFlags flags;
2505   gint minsize, maxsize, align;
2506
2507   switch (GST_QUERY_TYPE (query)) {
2508     case GST_QUERY_URI:
2509       gst_query_set_uri (query, src->location);
2510       if (src->redirection_uri != NULL) {
2511         gst_query_set_uri_redirection (query, src->redirection_uri);
2512         gst_query_set_uri_redirection_permanent (query,
2513             src->redirection_permanent);
2514       }
2515       ret = TRUE;
2516       break;
2517     default:
2518       ret = FALSE;
2519       break;
2520   }
2521
2522   if (!ret)
2523     ret = GST_BASE_SRC_CLASS (parent_class)->query (bsrc, query);
2524
2525   switch (GST_QUERY_TYPE (query)) {
2526     case GST_QUERY_SCHEDULING:
2527       gst_query_parse_scheduling (query, &flags, &minsize, &maxsize, &align);
2528       flags |= GST_SCHEDULING_FLAG_BANDWIDTH_LIMITED;
2529       gst_query_set_scheduling (query, flags, minsize, maxsize, align);
2530       break;
2531     default:
2532       break;
2533   }
2534
2535   return ret;
2536 }
2537
2538 static gboolean
2539 gst_soup_http_src_set_location (GstSoupHTTPSrc * src, const gchar * uri,
2540     GError ** error)
2541 {
2542   const char *alt_schemes[] = { "icy://", "icyx://" };
2543   guint i;
2544
2545   if (src->location) {
2546     g_free (src->location);
2547     src->location = NULL;
2548   }
2549
2550   if (uri == NULL)
2551     return FALSE;
2552
2553   for (i = 0; i < G_N_ELEMENTS (alt_schemes); i++) {
2554     if (g_str_has_prefix (uri, alt_schemes[i])) {
2555       src->location =
2556           g_strdup_printf ("http://%s", uri + strlen (alt_schemes[i]));
2557       return TRUE;
2558     }
2559   }
2560
2561   if (src->redirection_uri) {
2562     g_free (src->redirection_uri);
2563     src->redirection_uri = NULL;
2564   }
2565
2566   src->location = g_strdup (uri);
2567
2568   return TRUE;
2569 }
2570
2571 static gboolean
2572 gst_soup_http_src_set_proxy (GstSoupHTTPSrc * src, const gchar * uri)
2573 {
2574   if (src->proxy) {
2575     gst_soup_uri_free (src->proxy);
2576     src->proxy = NULL;
2577   }
2578
2579   if (uri == NULL || *uri == '\0')
2580     return TRUE;
2581
2582   if (g_strstr_len (uri, -1, "://")) {
2583     src->proxy = gst_soup_uri_new (uri);
2584   } else {
2585     gchar *new_uri = g_strconcat ("http://", uri, NULL);
2586
2587     src->proxy = gst_soup_uri_new (new_uri);
2588     g_free (new_uri);
2589   }
2590
2591   return (src->proxy != NULL);
2592 }
2593
2594 static GstURIType
2595 gst_soup_http_src_uri_get_type (GType type)
2596 {
2597   return GST_URI_SRC;
2598 }
2599
2600 static const gchar *const *
2601 gst_soup_http_src_uri_get_protocols (GType type)
2602 {
2603   static const gchar *protocols[] = { "http", "https", "icy", "icyx", NULL };
2604
2605   return protocols;
2606 }
2607
2608 static gchar *
2609 gst_soup_http_src_uri_get_uri (GstURIHandler * handler)
2610 {
2611   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (handler);
2612
2613   /* FIXME: make thread-safe */
2614   return g_strdup (src->location);
2615 }
2616
2617 static gboolean
2618 gst_soup_http_src_uri_set_uri (GstURIHandler * handler, const gchar * uri,
2619     GError ** error)
2620 {
2621   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (handler);
2622
2623   return gst_soup_http_src_set_location (src, uri, error);
2624 }
2625
2626 static void
2627 gst_soup_http_src_uri_handler_init (gpointer g_iface, gpointer iface_data)
2628 {
2629   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
2630
2631   iface->get_type = gst_soup_http_src_uri_get_type;
2632   iface->get_protocols = gst_soup_http_src_uri_get_protocols;
2633   iface->get_uri = gst_soup_http_src_uri_get_uri;
2634   iface->set_uri = gst_soup_http_src_uri_set_uri;
2635 }
2636
2637 static gboolean
2638 souphttpsrc_element_init (GstPlugin * plugin)
2639 {
2640   gboolean ret = TRUE;
2641
2642   GST_DEBUG_CATEGORY_INIT (souphttpsrc_debug, "souphttpsrc", 0,
2643       "SOUP HTTP src");
2644
2645   if (!soup_element_init (plugin))
2646     return TRUE;
2647
2648   ret = gst_element_register (plugin, "souphttpsrc",
2649       GST_RANK_PRIMARY, GST_TYPE_SOUP_HTTP_SRC);
2650
2651   return ret;
2652 }