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