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