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