Merge branch 'plugin-move-rtp-opus'
[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_pad_template (gstelement_class,
425       gst_static_pad_template_get (&srctemplate));
426
427   gst_element_class_set_static_metadata (gstelement_class, "HTTP client source",
428       "Source/Network",
429       "Receive data as a client over the network via HTTP using SOUP",
430       "Wouter Cloetens <wouter@mind.be>");
431   gstelement_class->change_state =
432       GST_DEBUG_FUNCPTR (gst_soup_http_src_change_state);
433
434   gstbasesrc_class->start = GST_DEBUG_FUNCPTR (gst_soup_http_src_start);
435   gstbasesrc_class->stop = GST_DEBUG_FUNCPTR (gst_soup_http_src_stop);
436   gstbasesrc_class->unlock = GST_DEBUG_FUNCPTR (gst_soup_http_src_unlock);
437   gstbasesrc_class->unlock_stop =
438       GST_DEBUG_FUNCPTR (gst_soup_http_src_unlock_stop);
439   gstbasesrc_class->get_size = GST_DEBUG_FUNCPTR (gst_soup_http_src_get_size);
440   gstbasesrc_class->is_seekable =
441       GST_DEBUG_FUNCPTR (gst_soup_http_src_is_seekable);
442   gstbasesrc_class->do_seek = GST_DEBUG_FUNCPTR (gst_soup_http_src_do_seek);
443   gstbasesrc_class->query = GST_DEBUG_FUNCPTR (gst_soup_http_src_query);
444
445   gstpushsrc_class->create = GST_DEBUG_FUNCPTR (gst_soup_http_src_create);
446
447   GST_DEBUG_CATEGORY_INIT (souphttpsrc_debug, "souphttpsrc", 0,
448       "SOUP HTTP src");
449 }
450
451 static void
452 gst_soup_http_src_reset (GstSoupHTTPSrc * src)
453 {
454   src->interrupted = FALSE;
455   src->retry = FALSE;
456   src->retry_count = 0;
457   src->have_size = FALSE;
458   src->got_headers = FALSE;
459   src->seekable = FALSE;
460   src->read_position = 0;
461   src->request_position = 0;
462   src->stop_position = -1;
463   src->content_size = 0;
464   src->have_body = FALSE;
465
466   src->ret = GST_FLOW_OK;
467
468   gst_caps_replace (&src->src_caps, NULL);
469   g_free (src->iradio_name);
470   src->iradio_name = NULL;
471   g_free (src->iradio_genre);
472   src->iradio_genre = NULL;
473   g_free (src->iradio_url);
474   src->iradio_url = NULL;
475 }
476
477 static void
478 gst_soup_http_src_init (GstSoupHTTPSrc * src)
479 {
480   const gchar *proxy;
481
482   g_mutex_init (&src->mutex);
483   g_cond_init (&src->request_finished_cond);
484   src->location = NULL;
485   src->redirection_uri = NULL;
486   src->automatic_redirect = TRUE;
487   src->user_agent = g_strdup (DEFAULT_USER_AGENT);
488   src->user_id = NULL;
489   src->user_pw = NULL;
490   src->proxy_id = NULL;
491   src->proxy_pw = NULL;
492   src->cookies = NULL;
493   src->iradio_mode = DEFAULT_IRADIO_MODE;
494   src->loop = NULL;
495   src->context = NULL;
496   src->session = NULL;
497   src->msg = NULL;
498   src->timeout = DEFAULT_TIMEOUT;
499   src->log_level = DEFAULT_SOUP_LOG_LEVEL;
500   src->ssl_strict = DEFAULT_SSL_STRICT;
501   src->ssl_use_system_ca_file = DEFAULT_SSL_USE_SYSTEM_CA_FILE;
502   src->tls_database = DEFAULT_TLS_DATABASE;
503   src->tls_interaction = DEFAULT_TLS_INTERACTION;
504   src->max_retries = DEFAULT_RETRIES;
505   src->method = DEFAULT_SOUP_METHOD;
506   proxy = g_getenv ("http_proxy");
507   if (!gst_soup_http_src_set_proxy (src, proxy)) {
508     GST_WARNING_OBJECT (src,
509         "The proxy in the http_proxy env var (\"%s\") cannot be parsed.",
510         proxy);
511   }
512
513   gst_base_src_set_automatic_eos (GST_BASE_SRC (src), FALSE);
514
515   gst_soup_http_src_reset (src);
516 }
517
518 static void
519 gst_soup_http_src_dispose (GObject * gobject)
520 {
521   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (gobject);
522
523   GST_DEBUG_OBJECT (src, "dispose");
524
525   gst_soup_http_src_session_close (src);
526
527   G_OBJECT_CLASS (parent_class)->dispose (gobject);
528 }
529
530 static void
531 gst_soup_http_src_finalize (GObject * gobject)
532 {
533   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (gobject);
534
535   GST_DEBUG_OBJECT (src, "finalize");
536
537   g_mutex_clear (&src->mutex);
538   g_cond_clear (&src->request_finished_cond);
539   g_free (src->location);
540   g_free (src->redirection_uri);
541   g_free (src->user_agent);
542   if (src->proxy != NULL) {
543     soup_uri_free (src->proxy);
544   }
545   g_free (src->user_id);
546   g_free (src->user_pw);
547   g_free (src->proxy_id);
548   g_free (src->proxy_pw);
549   g_strfreev (src->cookies);
550
551   if (src->extra_headers) {
552     gst_structure_free (src->extra_headers);
553     src->extra_headers = NULL;
554   }
555
556   g_free (src->ssl_ca_file);
557
558   if (src->tls_database)
559     g_object_unref (src->tls_database);
560   g_free (src->method);
561
562   if (src->tls_interaction)
563     g_object_unref (src->tls_interaction);
564
565   G_OBJECT_CLASS (parent_class)->finalize (gobject);
566 }
567
568 static void
569 gst_soup_http_src_set_property (GObject * object, guint prop_id,
570     const GValue * value, GParamSpec * pspec)
571 {
572   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (object);
573
574   switch (prop_id) {
575     case PROP_LOCATION:
576     {
577       const gchar *location;
578
579       location = g_value_get_string (value);
580
581       if (location == NULL) {
582         GST_WARNING ("location property cannot be NULL");
583         goto done;
584       }
585       if (!gst_soup_http_src_set_location (src, location, NULL)) {
586         GST_WARNING ("badly formatted location");
587         goto done;
588       }
589       break;
590     }
591     case PROP_USER_AGENT:
592       g_free (src->user_agent);
593       src->user_agent = g_value_dup_string (value);
594       break;
595     case PROP_IRADIO_MODE:
596       src->iradio_mode = g_value_get_boolean (value);
597       break;
598     case PROP_AUTOMATIC_REDIRECT:
599       src->automatic_redirect = g_value_get_boolean (value);
600       break;
601     case PROP_PROXY:
602     {
603       const gchar *proxy;
604
605       proxy = g_value_get_string (value);
606       if (!gst_soup_http_src_set_proxy (src, proxy)) {
607         GST_WARNING ("badly formatted proxy URI");
608         goto done;
609       }
610       break;
611     }
612     case PROP_COOKIES:
613       g_strfreev (src->cookies);
614       src->cookies = g_strdupv (g_value_get_boxed (value));
615       break;
616     case PROP_IS_LIVE:
617       gst_base_src_set_live (GST_BASE_SRC (src), g_value_get_boolean (value));
618       break;
619     case PROP_USER_ID:
620       g_free (src->user_id);
621       src->user_id = g_value_dup_string (value);
622       break;
623     case PROP_USER_PW:
624       g_free (src->user_pw);
625       src->user_pw = g_value_dup_string (value);
626       break;
627     case PROP_PROXY_ID:
628       g_free (src->proxy_id);
629       src->proxy_id = g_value_dup_string (value);
630       break;
631     case PROP_PROXY_PW:
632       g_free (src->proxy_pw);
633       src->proxy_pw = g_value_dup_string (value);
634       break;
635     case PROP_TIMEOUT:
636       src->timeout = g_value_get_uint (value);
637       break;
638     case PROP_EXTRA_HEADERS:{
639       const GstStructure *s = gst_value_get_structure (value);
640
641       if (src->extra_headers)
642         gst_structure_free (src->extra_headers);
643
644       src->extra_headers = s ? gst_structure_copy (s) : NULL;
645       break;
646     }
647     case PROP_SOUP_LOG_LEVEL:
648       src->log_level = g_value_get_enum (value);
649       break;
650     case PROP_COMPRESS:
651       src->compress = g_value_get_boolean (value);
652       break;
653     case PROP_KEEP_ALIVE:
654       src->keep_alive = g_value_get_boolean (value);
655       break;
656     case PROP_SSL_STRICT:
657       src->ssl_strict = g_value_get_boolean (value);
658       break;
659     case PROP_SSL_CA_FILE:
660       g_free (src->ssl_ca_file);
661       src->ssl_ca_file = g_value_dup_string (value);
662       break;
663     case PROP_SSL_USE_SYSTEM_CA_FILE:
664       src->ssl_use_system_ca_file = g_value_get_boolean (value);
665       break;
666     case PROP_TLS_DATABASE:
667       g_clear_object (&src->tls_database);
668       src->tls_database = g_value_dup_object (value);
669       break;
670     case PROP_TLS_INTERACTION:
671       g_clear_object (&src->tls_interaction);
672       src->tls_interaction = g_value_dup_object (value);
673       break;
674     case PROP_RETRIES:
675       src->max_retries = g_value_get_int (value);
676       break;
677     case PROP_METHOD:
678       g_free (src->method);
679       src->method = g_value_dup_string (value);
680       break;
681     default:
682       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
683       break;
684   }
685 done:
686   return;
687 }
688
689 static void
690 gst_soup_http_src_get_property (GObject * object, guint prop_id,
691     GValue * value, GParamSpec * pspec)
692 {
693   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (object);
694
695   switch (prop_id) {
696     case PROP_LOCATION:
697       g_value_set_string (value, src->location);
698       break;
699     case PROP_USER_AGENT:
700       g_value_set_string (value, src->user_agent);
701       break;
702     case PROP_AUTOMATIC_REDIRECT:
703       g_value_set_boolean (value, src->automatic_redirect);
704       break;
705     case PROP_PROXY:
706       if (src->proxy == NULL)
707         g_value_set_static_string (value, "");
708       else {
709         char *proxy = soup_uri_to_string (src->proxy, FALSE);
710
711         g_value_set_string (value, proxy);
712         g_free (proxy);
713       }
714       break;
715     case PROP_COOKIES:
716       g_value_set_boxed (value, g_strdupv (src->cookies));
717       break;
718     case PROP_IS_LIVE:
719       g_value_set_boolean (value, gst_base_src_is_live (GST_BASE_SRC (src)));
720       break;
721     case PROP_IRADIO_MODE:
722       g_value_set_boolean (value, src->iradio_mode);
723       break;
724     case PROP_USER_ID:
725       g_value_set_string (value, src->user_id);
726       break;
727     case PROP_USER_PW:
728       g_value_set_string (value, src->user_pw);
729       break;
730     case PROP_PROXY_ID:
731       g_value_set_string (value, src->proxy_id);
732       break;
733     case PROP_PROXY_PW:
734       g_value_set_string (value, src->proxy_pw);
735       break;
736     case PROP_TIMEOUT:
737       g_value_set_uint (value, src->timeout);
738       break;
739     case PROP_EXTRA_HEADERS:
740       gst_value_set_structure (value, src->extra_headers);
741       break;
742     case PROP_SOUP_LOG_LEVEL:
743       g_value_set_enum (value, src->log_level);
744       break;
745     case PROP_COMPRESS:
746       g_value_set_boolean (value, src->compress);
747       break;
748     case PROP_KEEP_ALIVE:
749       g_value_set_boolean (value, src->keep_alive);
750       break;
751     case PROP_SSL_STRICT:
752       g_value_set_boolean (value, src->ssl_strict);
753       break;
754     case PROP_SSL_CA_FILE:
755       g_value_set_string (value, src->ssl_ca_file);
756       break;
757     case PROP_SSL_USE_SYSTEM_CA_FILE:
758       g_value_set_boolean (value, src->ssl_use_system_ca_file);
759       break;
760     case PROP_TLS_DATABASE:
761       g_value_set_object (value, src->tls_database);
762       break;
763     case PROP_TLS_INTERACTION:
764       g_value_set_object (value, src->tls_interaction);
765       break;
766     case PROP_RETRIES:
767       g_value_set_int (value, src->max_retries);
768       break;
769     case PROP_METHOD:
770       g_value_set_string (value, src->method);
771       break;
772     default:
773       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
774       break;
775   }
776 }
777
778 static gchar *
779 gst_soup_http_src_unicodify (const gchar * str)
780 {
781   const gchar *env_vars[] = { "GST_ICY_TAG_ENCODING",
782     "GST_TAG_ENCODING", NULL
783   };
784
785   return gst_tag_freeform_string_to_utf8 (str, -1, env_vars);
786 }
787
788 static void
789 gst_soup_http_src_cancel_message (GstSoupHTTPSrc * src)
790 {
791   if (src->msg != NULL) {
792     GST_INFO_OBJECT (src, "Cancelling message");
793     src->session_io_status = GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_CANCELLED;
794     soup_session_cancel_message (src->session, src->msg, SOUP_STATUS_CANCELLED);
795   }
796   src->session_io_status = GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_IDLE;
797   src->msg = NULL;
798 }
799
800 static void
801 gst_soup_http_src_queue_message (GstSoupHTTPSrc * src)
802 {
803   soup_session_queue_message (src->session, src->msg,
804       (SoupSessionCallback) gst_soup_http_src_response_cb, src);
805   src->session_io_status = GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_QUEUED;
806 }
807
808 static gboolean
809 gst_soup_http_src_add_range_header (GstSoupHTTPSrc * src, guint64 offset,
810     guint64 stop_offset)
811 {
812   gchar buf[64];
813   gint rc;
814
815   soup_message_headers_remove (src->msg->request_headers, "Range");
816   if (offset || stop_offset != -1) {
817     if (stop_offset != -1) {
818       g_assert (offset != stop_offset);
819
820       rc = g_snprintf (buf, sizeof (buf), "bytes=%" G_GUINT64_FORMAT "-%"
821           G_GUINT64_FORMAT, offset, (stop_offset > 0) ? stop_offset - 1 :
822           stop_offset);
823     } else {
824       rc = g_snprintf (buf, sizeof (buf), "bytes=%" G_GUINT64_FORMAT "-",
825           offset);
826     }
827     if (rc > sizeof (buf) || rc < 0)
828       return FALSE;
829     soup_message_headers_append (src->msg->request_headers, "Range", buf);
830   }
831   src->read_position = offset;
832   return TRUE;
833 }
834
835 static gboolean
836 _append_extra_header (GQuark field_id, const GValue * value, gpointer user_data)
837 {
838   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (user_data);
839   const gchar *field_name = g_quark_to_string (field_id);
840   gchar *field_content = NULL;
841
842   if (G_VALUE_TYPE (value) == G_TYPE_STRING) {
843     field_content = g_value_dup_string (value);
844   } else {
845     GValue dest = { 0, };
846
847     g_value_init (&dest, G_TYPE_STRING);
848     if (g_value_transform (value, &dest)) {
849       field_content = g_value_dup_string (&dest);
850     }
851   }
852
853   if (field_content == NULL) {
854     GST_ERROR_OBJECT (src, "extra-headers field '%s' contains no value "
855         "or can't be converted to a string", field_name);
856     return FALSE;
857   }
858
859   GST_DEBUG_OBJECT (src, "Appending extra header: \"%s: %s\"", field_name,
860       field_content);
861   soup_message_headers_append (src->msg->request_headers, field_name,
862       field_content);
863
864   g_free (field_content);
865
866   return TRUE;
867 }
868
869 static gboolean
870 _append_extra_headers (GQuark field_id, const GValue * value,
871     gpointer user_data)
872 {
873   if (G_VALUE_TYPE (value) == GST_TYPE_ARRAY) {
874     guint n = gst_value_array_get_size (value);
875     guint i;
876
877     for (i = 0; i < n; i++) {
878       const GValue *v = gst_value_array_get_value (value, i);
879
880       if (!_append_extra_header (field_id, v, user_data))
881         return FALSE;
882     }
883   } else if (G_VALUE_TYPE (value) == GST_TYPE_LIST) {
884     guint n = gst_value_list_get_size (value);
885     guint i;
886
887     for (i = 0; i < n; i++) {
888       const GValue *v = gst_value_list_get_value (value, i);
889
890       if (!_append_extra_header (field_id, v, user_data))
891         return FALSE;
892     }
893   } else {
894     return _append_extra_header (field_id, value, user_data);
895   }
896
897   return TRUE;
898 }
899
900
901 static gboolean
902 gst_soup_http_src_add_extra_headers (GstSoupHTTPSrc * src)
903 {
904   if (!src->extra_headers)
905     return TRUE;
906
907   return gst_structure_foreach (src->extra_headers, _append_extra_headers, src);
908 }
909
910
911 static void
912 gst_soup_http_src_session_unpause_message (GstSoupHTTPSrc * src)
913 {
914   soup_session_unpause_message (src->session, src->msg);
915 }
916
917 static void
918 gst_soup_http_src_session_pause_message (GstSoupHTTPSrc * src)
919 {
920   soup_session_pause_message (src->session, src->msg);
921 }
922
923 static gboolean
924 gst_soup_http_src_session_open (GstSoupHTTPSrc * src)
925 {
926   if (src->session) {
927     GST_DEBUG_OBJECT (src, "Session is already open");
928     return TRUE;
929   }
930
931   if (!src->location) {
932     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (_("No URL set.")),
933         ("Missing location property"));
934     return FALSE;
935   }
936
937   if (!src->context)
938     src->context = g_main_context_new ();
939
940   if (!src->loop)
941     src->loop = g_main_loop_new (src->context, TRUE);
942   if (!src->loop) {
943     GST_ELEMENT_ERROR (src, LIBRARY, INIT,
944         (NULL), ("Failed to start GMainLoop"));
945     g_main_context_unref (src->context);
946     return FALSE;
947   }
948
949   if (!src->session) {
950     GST_DEBUG_OBJECT (src, "Creating session");
951     if (src->proxy == NULL) {
952       src->session =
953           soup_session_async_new_with_options (SOUP_SESSION_ASYNC_CONTEXT,
954           src->context, SOUP_SESSION_USER_AGENT, src->user_agent,
955           SOUP_SESSION_TIMEOUT, src->timeout,
956           SOUP_SESSION_SSL_STRICT, src->ssl_strict,
957           SOUP_SESSION_ADD_FEATURE_BY_TYPE, SOUP_TYPE_PROXY_RESOLVER_DEFAULT,
958           SOUP_SESSION_TLS_INTERACTION, src->tls_interaction, NULL);
959     } else {
960       src->session =
961           soup_session_async_new_with_options (SOUP_SESSION_ASYNC_CONTEXT,
962           src->context, SOUP_SESSION_PROXY_URI, src->proxy,
963           SOUP_SESSION_TIMEOUT, src->timeout,
964           SOUP_SESSION_SSL_STRICT, src->ssl_strict,
965           SOUP_SESSION_USER_AGENT, src->user_agent,
966           SOUP_SESSION_TLS_INTERACTION, src->tls_interaction, NULL);
967     }
968
969     if (!src->session) {
970       GST_ELEMENT_ERROR (src, LIBRARY, INIT,
971           (NULL), ("Failed to create async session"));
972       return FALSE;
973     }
974
975     g_signal_connect (src->session, "authenticate",
976         G_CALLBACK (gst_soup_http_src_authenticate_cb), src);
977
978     /* Set up logging */
979     gst_soup_util_log_setup (src->session, src->log_level, GST_ELEMENT (src));
980     if (src->tls_database)
981       g_object_set (src->session, "tls-database", src->tls_database, NULL);
982     else if (src->ssl_ca_file)
983       g_object_set (src->session, "ssl-ca-file", src->ssl_ca_file, NULL);
984     else
985       g_object_set (src->session, "ssl-use-system-ca-file",
986           src->ssl_use_system_ca_file, NULL);
987   } else {
988     GST_DEBUG_OBJECT (src, "Re-using session");
989   }
990
991   if (src->compress)
992     soup_session_add_feature_by_type (src->session, SOUP_TYPE_CONTENT_DECODER);
993   else
994     soup_session_remove_feature_by_type (src->session,
995         SOUP_TYPE_CONTENT_DECODER);
996
997   return TRUE;
998 }
999
1000 #ifdef LIBSOUP_DOES_NOT_STEAL_OUR_CONTEXT
1001 static gboolean
1002 dummy_idle_cb (gpointer data)
1003 {
1004   return FALSE /* Idle source is removed */ ;
1005 }
1006 #endif
1007
1008 static void
1009 gst_soup_http_src_session_close (GstSoupHTTPSrc * src)
1010 {
1011   GST_DEBUG_OBJECT (src, "Closing session");
1012
1013   if (src->loop)
1014     g_main_loop_quit (src->loop);
1015
1016   g_mutex_lock (&src->mutex);
1017   if (src->session) {
1018     soup_session_abort (src->session);  /* This unrefs the message. */
1019     g_object_unref (src->session);
1020     src->session = NULL;
1021     src->msg = NULL;
1022   }
1023   if (src->loop) {
1024 #ifdef LIBSOUP_DOES_NOT_STEAL_OUR_CONTEXT
1025     GSource *idle_source;
1026
1027     /* Iterating the main context to give GIO cancellables a chance
1028      * to initiate cleanups. Wihout this, resources allocated by
1029      * libsoup for the connection are not released and socket fd is
1030      * leaked. */
1031     idle_source = g_idle_source_new ();
1032     /* Suppressing "idle souce without callback" warning */
1033     g_source_set_callback (idle_source, dummy_idle_cb, NULL, NULL);
1034     g_source_set_priority (idle_source, G_PRIORITY_LOW);
1035     g_source_attach (idle_source, src->context);
1036     /* Acquiring the context. Idle source guarantees that we'll not block. */
1037     g_main_context_push_thread_default (src->context);
1038     g_main_context_iteration (src->context, TRUE);
1039     /* Ensuring that there's no unhandled pending events left. */
1040     while (g_main_context_iteration (src->context, FALSE));
1041     g_main_context_pop_thread_default (src->context);
1042     g_source_unref (idle_source);
1043 #endif
1044
1045     g_main_loop_unref (src->loop);
1046     g_main_context_unref (src->context);
1047     src->loop = NULL;
1048     src->context = NULL;
1049   }
1050   g_mutex_unlock (&src->mutex);
1051 }
1052
1053 static void
1054 gst_soup_http_src_authenticate_cb (SoupSession * session, SoupMessage * msg,
1055     SoupAuth * auth, gboolean retrying, GstSoupHTTPSrc * src)
1056 {
1057   if (!retrying) {
1058     /* First time authentication only, if we fail and are called again with retry true fall through */
1059     if (msg->status_code == SOUP_STATUS_UNAUTHORIZED) {
1060       if (src->user_id && src->user_pw)
1061         soup_auth_authenticate (auth, src->user_id, src->user_pw);
1062     } else if (msg->status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED) {
1063       if (src->proxy_id && src->proxy_pw)
1064         soup_auth_authenticate (auth, src->proxy_id, src->proxy_pw);
1065     }
1066   }
1067 }
1068
1069 static void
1070 insert_http_header (const gchar * name, const gchar * value, gpointer user_data)
1071 {
1072   GstStructure *headers = user_data;
1073   const GValue *gv;
1074
1075   gv = gst_structure_get_value (headers, name);
1076   if (gv && GST_VALUE_HOLDS_ARRAY (gv)) {
1077     GValue v = G_VALUE_INIT;
1078
1079     g_value_init (&v, G_TYPE_STRING);
1080     g_value_set_string (&v, value);
1081     gst_value_array_append_value ((GValue *) gv, &v);
1082     g_value_unset (&v);
1083   } else if (gv && G_VALUE_HOLDS_STRING (gv)) {
1084     GValue arr = G_VALUE_INIT;
1085     GValue v = G_VALUE_INIT;
1086     const gchar *old_value = g_value_get_string (gv);
1087
1088     g_value_init (&arr, GST_TYPE_ARRAY);
1089     g_value_init (&v, G_TYPE_STRING);
1090     g_value_set_string (&v, old_value);
1091     gst_value_array_append_value (&arr, &v);
1092     g_value_set_string (&v, value);
1093     gst_value_array_append_value (&arr, &v);
1094
1095     gst_structure_set_value (headers, name, &arr);
1096     g_value_unset (&v);
1097     g_value_unset (&arr);
1098   } else {
1099     gst_structure_set (headers, name, G_TYPE_STRING, value, NULL);
1100   }
1101 }
1102
1103 static void
1104 gst_soup_http_src_got_headers_cb (SoupMessage * msg, GstSoupHTTPSrc * src)
1105 {
1106   const char *value;
1107   GstTagList *tag_list;
1108   GstBaseSrc *basesrc;
1109   guint64 newsize;
1110   GHashTable *params = NULL;
1111   GstEvent *http_headers_event;
1112   GstStructure *http_headers, *headers;
1113   const gchar *accept_ranges;
1114
1115   GST_INFO_OBJECT (src, "got headers");
1116
1117   if (msg->status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED &&
1118       src->proxy_id && src->proxy_pw)
1119     return;
1120
1121   if (src->automatic_redirect && SOUP_STATUS_IS_REDIRECTION (msg->status_code)) {
1122     src->redirection_uri = g_strdup (soup_message_headers_get_one
1123         (msg->response_headers, "Location"));
1124     src->redirection_permanent =
1125         (msg->status_code == SOUP_STATUS_MOVED_PERMANENTLY);
1126     GST_DEBUG_OBJECT (src, "%u redirect to \"%s\" (permanent %d)",
1127         msg->status_code, src->redirection_uri, src->redirection_permanent);
1128     return;
1129   }
1130
1131   if (msg->status_code == SOUP_STATUS_UNAUTHORIZED)
1132     return;
1133
1134   src->session_io_status = GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING;
1135   src->got_headers = TRUE;
1136
1137   http_headers = gst_structure_new_empty ("http-headers");
1138   gst_structure_set (http_headers, "uri", G_TYPE_STRING, src->location, NULL);
1139   if (src->redirection_uri)
1140     gst_structure_set (http_headers, "redirection-uri", G_TYPE_STRING,
1141         src->redirection_uri, NULL);
1142   headers = gst_structure_new_empty ("request-headers");
1143   soup_message_headers_foreach (msg->request_headers, insert_http_header,
1144       headers);
1145   gst_structure_set (http_headers, "request-headers", GST_TYPE_STRUCTURE,
1146       headers, NULL);
1147   gst_structure_free (headers);
1148   headers = gst_structure_new_empty ("response-headers");
1149   soup_message_headers_foreach (msg->response_headers, insert_http_header,
1150       headers);
1151   gst_structure_set (http_headers, "response-headers", GST_TYPE_STRUCTURE,
1152       headers, NULL);
1153   gst_structure_free (headers);
1154
1155   http_headers_event =
1156       gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM_STICKY, http_headers);
1157   gst_event_replace (&src->http_headers_event, http_headers_event);
1158   gst_event_unref (http_headers_event);
1159
1160   /* Parse Content-Length. */
1161   if (soup_message_headers_get_encoding (msg->response_headers) ==
1162       SOUP_ENCODING_CONTENT_LENGTH) {
1163     newsize = src->request_position +
1164         soup_message_headers_get_content_length (msg->response_headers);
1165     if (!src->have_size || (src->content_size != newsize)) {
1166       src->content_size = newsize;
1167       src->have_size = TRUE;
1168       src->seekable = TRUE;
1169       GST_DEBUG_OBJECT (src, "size = %" G_GUINT64_FORMAT, src->content_size);
1170
1171       basesrc = GST_BASE_SRC_CAST (src);
1172       basesrc->segment.duration = src->content_size;
1173       gst_element_post_message (GST_ELEMENT (src),
1174           gst_message_new_duration_changed (GST_OBJECT (src)));
1175     }
1176   }
1177
1178   /* If the server reports Accept-Ranges: none we don't have to try
1179    * doing range requests at all
1180    */
1181   if ((accept_ranges =
1182           soup_message_headers_get_one (msg->response_headers,
1183               "Accept-Ranges"))) {
1184     if (g_ascii_strcasecmp (accept_ranges, "none") == 0)
1185       src->seekable = FALSE;
1186   }
1187
1188   /* Icecast stuff */
1189   tag_list = gst_tag_list_new_empty ();
1190
1191   if ((value =
1192           soup_message_headers_get_one (msg->response_headers,
1193               "icy-metaint")) != NULL) {
1194     gint icy_metaint = atoi (value);
1195
1196     GST_DEBUG_OBJECT (src, "icy-metaint: %s (parsed: %d)", value, icy_metaint);
1197     if (icy_metaint > 0) {
1198       if (src->src_caps)
1199         gst_caps_unref (src->src_caps);
1200
1201       src->src_caps = gst_caps_new_simple ("application/x-icy",
1202           "metadata-interval", G_TYPE_INT, icy_metaint, NULL);
1203
1204       gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps);
1205     }
1206   }
1207   if ((value =
1208           soup_message_headers_get_content_type (msg->response_headers,
1209               &params)) != NULL) {
1210     GST_DEBUG_OBJECT (src, "Content-Type: %s", value);
1211     if (g_ascii_strcasecmp (value, "audio/L16") == 0) {
1212       gint channels = 2;
1213       gint rate = 44100;
1214       char *param;
1215
1216       if (src->src_caps)
1217         gst_caps_unref (src->src_caps);
1218
1219       param = g_hash_table_lookup (params, "channels");
1220       if (param != NULL)
1221         channels = atol (param);
1222
1223       param = g_hash_table_lookup (params, "rate");
1224       if (param != NULL)
1225         rate = atol (param);
1226
1227       src->src_caps = gst_caps_new_simple ("audio/x-raw",
1228           "format", G_TYPE_STRING, "S16BE",
1229           "layout", G_TYPE_STRING, "interleaved",
1230           "channels", G_TYPE_INT, channels, "rate", G_TYPE_INT, rate, NULL);
1231
1232       gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps);
1233     } else {
1234       /* Set the Content-Type field on the caps */
1235       if (src->src_caps) {
1236         src->src_caps = gst_caps_make_writable (src->src_caps);
1237         gst_caps_set_simple (src->src_caps, "content-type", G_TYPE_STRING,
1238             value, NULL);
1239         gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps);
1240       }
1241     }
1242   }
1243
1244   if (params != NULL)
1245     g_hash_table_destroy (params);
1246
1247   if ((value =
1248           soup_message_headers_get_one (msg->response_headers,
1249               "icy-name")) != NULL) {
1250     g_free (src->iradio_name);
1251     src->iradio_name = gst_soup_http_src_unicodify (value);
1252     if (src->iradio_name) {
1253       gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_ORGANIZATION,
1254           src->iradio_name, NULL);
1255     }
1256   }
1257   if ((value =
1258           soup_message_headers_get_one (msg->response_headers,
1259               "icy-genre")) != NULL) {
1260     g_free (src->iradio_genre);
1261     src->iradio_genre = gst_soup_http_src_unicodify (value);
1262     if (src->iradio_genre) {
1263       gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_GENRE,
1264           src->iradio_genre, NULL);
1265     }
1266   }
1267   if ((value = soup_message_headers_get_one (msg->response_headers, "icy-url"))
1268       != NULL) {
1269     g_free (src->iradio_url);
1270     src->iradio_url = gst_soup_http_src_unicodify (value);
1271     if (src->iradio_url) {
1272       gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_LOCATION,
1273           src->iradio_url, NULL);
1274     }
1275   }
1276   if (!gst_tag_list_is_empty (tag_list)) {
1277     GST_DEBUG_OBJECT (src,
1278         "calling gst_element_found_tags with %" GST_PTR_FORMAT, tag_list);
1279     gst_pad_push_event (GST_BASE_SRC_PAD (src), gst_event_new_tag (tag_list));
1280   } else {
1281     gst_tag_list_unref (tag_list);
1282   }
1283
1284   /* Handle HTTP errors. */
1285   gst_soup_http_src_parse_status (msg, src);
1286
1287   /* Check if Range header was respected. */
1288   if (src->ret == GST_FLOW_CUSTOM_ERROR &&
1289       src->read_position && msg->status_code != SOUP_STATUS_PARTIAL_CONTENT) {
1290     src->seekable = FALSE;
1291     GST_ELEMENT_ERROR (src, RESOURCE, SEEK,
1292         (_("Server does not support seeking.")),
1293         ("Server does not accept Range HTTP header, URL: %s, Redirect to: %s",
1294             src->location, GST_STR_NULL (src->redirection_uri)));
1295     src->ret = GST_FLOW_ERROR;
1296   }
1297
1298   /* If we are going to error out, stop all processing right here, so we
1299    * don't output any data (such as an error html page), and return
1300    * GST_FLOW_ERROR from the create function instead of having
1301    * got_chunk_cb overwrite src->ret with FLOW_OK again. */
1302   if (src->ret == GST_FLOW_ERROR || src->ret == GST_FLOW_EOS) {
1303     gst_soup_http_src_session_pause_message (src);
1304
1305     if (src->loop)
1306       g_main_loop_quit (src->loop);
1307   }
1308   g_cond_signal (&src->request_finished_cond);
1309 }
1310
1311 /* Have body. Signal EOS. */
1312 static void
1313 gst_soup_http_src_got_body_cb (SoupMessage * msg, GstSoupHTTPSrc * src)
1314 {
1315   if (G_UNLIKELY (msg != src->msg)) {
1316     GST_DEBUG_OBJECT (src, "got body, but not for current message");
1317     return;
1318   }
1319   if (G_UNLIKELY (src->session_io_status !=
1320           GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING)) {
1321     /* Probably a redirect. */
1322     return;
1323   }
1324   GST_DEBUG_OBJECT (src, "got body");
1325   src->ret = GST_FLOW_EOS;
1326   src->have_body = TRUE;
1327
1328   /* no need to interrupt the message here, we do it on the
1329    * finished_cb anyway if needed. And getting the body might mean
1330    * that the connection was hang up before finished. This happens when
1331    * the pipeline is stalled for too long (long pauses during playback).
1332    * Best to let it continue from here and pause because it reached the
1333    * final bytes based on content_size or received an out of range error */
1334 }
1335
1336 /* Finished. Signal EOS. */
1337 static void
1338 gst_soup_http_src_finished_cb (SoupMessage * msg, GstSoupHTTPSrc * src)
1339 {
1340   if (G_UNLIKELY (msg != src->msg)) {
1341     GST_DEBUG_OBJECT (src, "finished, but not for current message");
1342     return;
1343   }
1344   GST_INFO_OBJECT (src, "finished, io status: %d", src->session_io_status);
1345   src->ret = GST_FLOW_EOS;
1346   if (src->session_io_status == GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_CANCELLED) {
1347     /* gst_soup_http_src_cancel_message() triggered this; probably a seek
1348      * that occurred in the QUEUEING state; i.e. before the connection setup
1349      * was complete. Do nothing */
1350     GST_DEBUG_OBJECT (src, "cancelled");
1351   } else if (src->session_io_status ==
1352       GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING && src->read_position > 0 &&
1353       (src->have_size && src->read_position < src->content_size) &&
1354       (src->max_retries == -1 || src->retry_count < src->max_retries)) {
1355     /* The server disconnected while streaming. Reconnect and seeking to the
1356      * last location. */
1357     src->retry = TRUE;
1358     src->retry_count++;
1359     src->ret = GST_FLOW_CUSTOM_ERROR;
1360   } else if (G_UNLIKELY (src->session_io_status !=
1361           GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING)) {
1362     if (msg->method == SOUP_METHOD_HEAD) {
1363       GST_DEBUG_OBJECT (src, "Ignoring error %d:%s during HEAD request",
1364           msg->status_code, msg->reason_phrase);
1365     } else {
1366       gst_soup_http_src_parse_status (msg, src);
1367     }
1368   }
1369   if (src->loop)
1370     g_main_loop_quit (src->loop);
1371   g_cond_signal (&src->request_finished_cond);
1372 }
1373
1374 /* Buffer lifecycle management.
1375  *
1376  * gst_soup_http_src_create() runs the GMainLoop for this element, to let
1377  * Soup take control.
1378  * A GstBuffer is allocated in gst_soup_http_src_chunk_allocator() and
1379  * associated with a SoupBuffer.
1380  * Soup reads HTTP data in the GstBuffer's data buffer.
1381  * The gst_soup_http_src_got_chunk_cb() is then called with the SoupBuffer.
1382  * That sets gst_soup_http_src_create()'s return argument to the GstBuffer,
1383  * increments its refcount (to 2), pauses the flow of data from the HTTP
1384  * source to prevent gst_soup_http_src_got_chunk_cb() from being called
1385  * again and breaks out of the GMainLoop.
1386  * Because the SOUP_MESSAGE_OVERWRITE_CHUNKS flag is set, Soup frees the
1387  * SoupBuffer and calls gst_soup_http_src_chunk_free(), which decrements the
1388  * refcount (to 1).
1389  * gst_soup_http_src_create() returns the GstBuffer. It will be freed by a
1390  * downstream element.
1391  * If Soup fails to read HTTP data, it does not call
1392  * gst_soup_http_src_got_chunk_cb(), but still frees the SoupBuffer and
1393  * calls gst_soup_http_src_chunk_free(), which decrements the GstBuffer's
1394  * refcount to 0, freeing it.
1395  */
1396
1397 typedef struct
1398 {
1399   GstBuffer *buffer;
1400   GstMapInfo map;
1401 } SoupGstChunk;
1402
1403 static void
1404 gst_soup_http_src_chunk_free (gpointer user_data)
1405 {
1406   SoupGstChunk *chunk = (SoupGstChunk *) user_data;
1407
1408   gst_buffer_unmap (chunk->buffer, &chunk->map);
1409   gst_buffer_unref (chunk->buffer);
1410   g_slice_free (SoupGstChunk, chunk);
1411 }
1412
1413 static SoupBuffer *
1414 gst_soup_http_src_chunk_allocator (SoupMessage * msg, gsize max_len,
1415     gpointer user_data)
1416 {
1417   GstSoupHTTPSrc *src = (GstSoupHTTPSrc *) user_data;
1418   GstBaseSrc *basesrc = GST_BASE_SRC_CAST (src);
1419   GstBuffer *gstbuf;
1420   SoupBuffer *soupbuf;
1421   gsize length;
1422   GstFlowReturn rc;
1423   SoupGstChunk *chunk;
1424
1425   if (max_len)
1426     length = MIN (basesrc->blocksize, max_len);
1427   else
1428     length = basesrc->blocksize;
1429   GST_DEBUG_OBJECT (src, "alloc %" G_GSIZE_FORMAT " bytes <= %" G_GSIZE_FORMAT,
1430       length, max_len);
1431
1432   rc = GST_BASE_SRC_CLASS (parent_class)->alloc (basesrc, -1, length, &gstbuf);
1433   if (G_UNLIKELY (rc != GST_FLOW_OK)) {
1434     /* Failed to allocate buffer. Stall SoupSession and return error code
1435      * to create(). */
1436     src->ret = rc;
1437     g_main_loop_quit (src->loop);
1438     return NULL;
1439   }
1440
1441   chunk = g_slice_new0 (SoupGstChunk);
1442   chunk->buffer = gstbuf;
1443   gst_buffer_map (gstbuf, &chunk->map, GST_MAP_READWRITE);
1444
1445   soupbuf = soup_buffer_new_with_owner (chunk->map.data, chunk->map.size,
1446       chunk, gst_soup_http_src_chunk_free);
1447
1448   return soupbuf;
1449 }
1450
1451 static void
1452 gst_soup_http_src_got_chunk_cb (SoupMessage * msg, SoupBuffer * chunk,
1453     GstSoupHTTPSrc * src)
1454 {
1455   GstBaseSrc *basesrc;
1456   guint64 new_position;
1457   SoupGstChunk *gchunk;
1458
1459   if (G_UNLIKELY (msg != src->msg)) {
1460     GST_DEBUG_OBJECT (src, "got chunk, but not for current message");
1461     return;
1462   }
1463   if (G_UNLIKELY (!src->outbuf)) {
1464     GST_DEBUG_OBJECT (src, "got chunk but we're not expecting one");
1465     src->ret = GST_FLOW_OK;
1466     gst_soup_http_src_cancel_message (src);
1467     g_main_loop_quit (src->loop);
1468     return;
1469   }
1470
1471   /* We got data, reset the retry counter */
1472   src->retry_count = 0;
1473
1474   src->have_body = FALSE;
1475   if (G_UNLIKELY (src->session_io_status !=
1476           GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING)) {
1477     /* Probably a redirect. */
1478     return;
1479   }
1480   basesrc = GST_BASE_SRC_CAST (src);
1481   GST_DEBUG_OBJECT (src, "got chunk of %" G_GSIZE_FORMAT " bytes",
1482       chunk->length);
1483
1484   /* Extract the GstBuffer from the SoupBuffer and set its fields. */
1485   gchunk = (SoupGstChunk *) soup_buffer_get_owner (chunk);
1486   *src->outbuf = gchunk->buffer;
1487
1488   gst_buffer_resize (*src->outbuf, 0, chunk->length);
1489   GST_BUFFER_OFFSET (*src->outbuf) = basesrc->segment.position;
1490
1491   gst_buffer_ref (*src->outbuf);
1492
1493   new_position = src->read_position + chunk->length;
1494   if (G_LIKELY (src->request_position == src->read_position))
1495     src->request_position = new_position;
1496   src->read_position = new_position;
1497
1498   if (src->have_size) {
1499     if (new_position > src->content_size) {
1500       GST_DEBUG_OBJECT (src, "Got position previous estimated content size "
1501           "(%" G_GINT64_FORMAT " > %" G_GINT64_FORMAT ")", new_position,
1502           src->content_size);
1503       src->content_size = new_position;
1504       basesrc->segment.duration = src->content_size;
1505       gst_element_post_message (GST_ELEMENT (src),
1506           gst_message_new_duration_changed (GST_OBJECT (src)));
1507     } else if (new_position == src->content_size) {
1508       GST_DEBUG_OBJECT (src, "We're EOS now");
1509     }
1510   }
1511
1512   src->ret = GST_FLOW_OK;
1513   g_main_loop_quit (src->loop);
1514   gst_soup_http_src_session_pause_message (src);
1515 }
1516
1517 static void
1518 gst_soup_http_src_response_cb (SoupSession * session, SoupMessage * msg,
1519     GstSoupHTTPSrc * src)
1520 {
1521   if (G_UNLIKELY (msg != src->msg)) {
1522     GST_DEBUG_OBJECT (src, "got response %d: %s, but not for current message",
1523         msg->status_code, msg->reason_phrase);
1524     return;
1525   }
1526   if (G_UNLIKELY (src->session_io_status !=
1527           GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING)
1528       && SOUP_STATUS_IS_REDIRECTION (msg->status_code)) {
1529     /* Ignore redirections. */
1530     return;
1531   }
1532   GST_INFO_OBJECT (src, "got response %d: %s", msg->status_code,
1533       msg->reason_phrase);
1534   if (src->session_io_status == GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING &&
1535       src->read_position > 0 && (src->have_size
1536           && src->read_position < src->content_size) &&
1537       (src->max_retries == -1 || src->retry_count < src->max_retries)) {
1538     /* The server disconnected while streaming. Reconnect and seeking to the
1539      * last location. */
1540     src->retry = TRUE;
1541     src->retry_count++;
1542   } else {
1543     gst_soup_http_src_parse_status (msg, src);
1544   }
1545   /* The session's SoupMessage object expires after this callback returns. */
1546   src->msg = NULL;
1547   g_main_loop_quit (src->loop);
1548 }
1549
1550 #define SOUP_HTTP_SRC_ERROR(src,soup_msg,cat,code,error_message)     \
1551   GST_ELEMENT_ERROR ((src), cat, code, ("%s", error_message),        \
1552       ("%s (%d), URL: %s, Redirect to: %s", (soup_msg)->reason_phrase,                \
1553           (soup_msg)->status_code, (src)->location, GST_STR_NULL ((src)->redirection_uri)));
1554
1555 static void
1556 gst_soup_http_src_parse_status (SoupMessage * msg, GstSoupHTTPSrc * src)
1557 {
1558   if (msg->method == SOUP_METHOD_HEAD) {
1559     if (!SOUP_STATUS_IS_SUCCESSFUL (msg->status_code))
1560       GST_DEBUG_OBJECT (src, "Ignoring error %d during HEAD request",
1561           msg->status_code);
1562   } else if (SOUP_STATUS_IS_TRANSPORT_ERROR (msg->status_code)) {
1563     switch (msg->status_code) {
1564       case SOUP_STATUS_CANT_RESOLVE:
1565       case SOUP_STATUS_CANT_RESOLVE_PROXY:
1566         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, NOT_FOUND,
1567             _("Could not resolve server name."));
1568         src->ret = GST_FLOW_ERROR;
1569         break;
1570       case SOUP_STATUS_CANT_CONNECT:
1571       case SOUP_STATUS_CANT_CONNECT_PROXY:
1572         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, OPEN_READ,
1573             _("Could not establish connection to server."));
1574         src->ret = GST_FLOW_ERROR;
1575         break;
1576       case SOUP_STATUS_SSL_FAILED:
1577         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, OPEN_READ,
1578             _("Secure connection setup failed."));
1579         src->ret = GST_FLOW_ERROR;
1580         break;
1581       case SOUP_STATUS_IO_ERROR:
1582         if (src->max_retries == -1 || src->retry_count < src->max_retries) {
1583           src->retry = TRUE;
1584           src->retry_count++;
1585           src->ret = GST_FLOW_CUSTOM_ERROR;
1586         } else {
1587           SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, READ,
1588               _("A network error occurred, or the server closed the connection "
1589                   "unexpectedly."));
1590           src->ret = GST_FLOW_ERROR;
1591         }
1592         break;
1593       case SOUP_STATUS_MALFORMED:
1594         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, READ,
1595             _("Server sent bad data."));
1596         src->ret = GST_FLOW_ERROR;
1597         break;
1598       case SOUP_STATUS_CANCELLED:
1599         /* No error message when interrupted by program. */
1600         break;
1601     }
1602   } else if (SOUP_STATUS_IS_CLIENT_ERROR (msg->status_code) ||
1603       SOUP_STATUS_IS_REDIRECTION (msg->status_code) ||
1604       SOUP_STATUS_IS_SERVER_ERROR (msg->status_code)) {
1605     /* Report HTTP error. */
1606
1607     /* when content_size is unknown and we have just finished receiving
1608      * a body message, requests that go beyond the content limits will result
1609      * in an error. Here we convert those to EOS */
1610     if (msg->status_code == SOUP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE &&
1611         src->have_body && !src->have_size) {
1612       GST_DEBUG_OBJECT (src, "Requested range out of limits and received full "
1613           "body, returning EOS");
1614       src->ret = GST_FLOW_EOS;
1615       return;
1616     }
1617
1618     /* FIXME: reason_phrase is not translated and not suitable for user
1619      * error dialog according to libsoup documentation.
1620      */
1621     if (msg->status_code == SOUP_STATUS_NOT_FOUND) {
1622       GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND,
1623           ("%s", msg->reason_phrase),
1624           ("%s (%d), URL: %s, Redirect to: %s", msg->reason_phrase,
1625               msg->status_code, src->location,
1626               GST_STR_NULL (src->redirection_uri)));
1627     } else if (msg->status_code == SOUP_STATUS_UNAUTHORIZED
1628         || msg->status_code == SOUP_STATUS_PAYMENT_REQUIRED
1629         || msg->status_code == SOUP_STATUS_FORBIDDEN
1630         || msg->status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED) {
1631       GST_ELEMENT_ERROR (src, RESOURCE, NOT_AUTHORIZED, ("%s",
1632               msg->reason_phrase), ("%s (%d), URL: %s, Redirect to: %s",
1633               msg->reason_phrase, msg->status_code, src->location,
1634               GST_STR_NULL (src->redirection_uri)));
1635     } else {
1636       GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
1637           ("%s", msg->reason_phrase),
1638           ("%s (%d), URL: %s, Redirect to: %s", msg->reason_phrase,
1639               msg->status_code, src->location,
1640               GST_STR_NULL (src->redirection_uri)));
1641     }
1642     src->ret = GST_FLOW_ERROR;
1643   }
1644 }
1645
1646 static gboolean
1647 gst_soup_http_src_build_message (GstSoupHTTPSrc * src, const gchar * method)
1648 {
1649   g_return_val_if_fail (src->msg == NULL, FALSE);
1650
1651   src->msg = soup_message_new (method, src->location);
1652   if (!src->msg) {
1653     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
1654         ("Error parsing URL."), ("URL: %s", src->location));
1655     return FALSE;
1656   }
1657   src->session_io_status = GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_IDLE;
1658   if (!src->keep_alive) {
1659     soup_message_headers_append (src->msg->request_headers, "Connection",
1660         "close");
1661   }
1662   if (src->iradio_mode) {
1663     soup_message_headers_append (src->msg->request_headers, "icy-metadata",
1664         "1");
1665   }
1666   if (src->cookies) {
1667     gchar **cookie;
1668
1669     for (cookie = src->cookies; *cookie != NULL; cookie++) {
1670       soup_message_headers_append (src->msg->request_headers, "Cookie",
1671           *cookie);
1672     }
1673   }
1674   src->retry = FALSE;
1675
1676   g_signal_connect (src->msg, "got_headers",
1677       G_CALLBACK (gst_soup_http_src_got_headers_cb), src);
1678   g_signal_connect (src->msg, "got_body",
1679       G_CALLBACK (gst_soup_http_src_got_body_cb), src);
1680   g_signal_connect (src->msg, "finished",
1681       G_CALLBACK (gst_soup_http_src_finished_cb), src);
1682   g_signal_connect (src->msg, "got_chunk",
1683       G_CALLBACK (gst_soup_http_src_got_chunk_cb), src);
1684   soup_message_set_flags (src->msg, SOUP_MESSAGE_OVERWRITE_CHUNKS |
1685       (src->automatic_redirect ? 0 : SOUP_MESSAGE_NO_REDIRECT));
1686   soup_message_set_chunk_allocator (src->msg,
1687       gst_soup_http_src_chunk_allocator, src, NULL);
1688   gst_soup_http_src_add_range_header (src, src->request_position,
1689       src->stop_position);
1690
1691   gst_soup_http_src_add_extra_headers (src);
1692
1693   return TRUE;
1694 }
1695
1696 static GstFlowReturn
1697 gst_soup_http_src_do_request (GstSoupHTTPSrc * src, const gchar * method,
1698     GstBuffer ** outbuf)
1699 {
1700   /* If we're not OK, just go out of here */
1701   if (src->ret != GST_FLOW_OK) {
1702     GST_DEBUG_OBJECT (src, "Previous flow return not OK: %s",
1703         gst_flow_get_name (src->ret));
1704     return src->ret;
1705   }
1706
1707   GST_LOG_OBJECT (src, "Running request for method: %s", method);
1708   if (src->msg && (src->request_position != src->read_position)) {
1709     if (src->session_io_status == GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_IDLE) {
1710       /* EOS immediately if we have an empty segment */
1711       if (src->request_position == src->stop_position)
1712         return GST_FLOW_EOS;
1713
1714       gst_soup_http_src_add_range_header (src, src->request_position,
1715           src->stop_position);
1716     } else {
1717       GST_DEBUG_OBJECT (src, "Seek from position %" G_GUINT64_FORMAT
1718           " to %" G_GUINT64_FORMAT ": requeueing connection request",
1719           src->read_position, src->request_position);
1720       gst_soup_http_src_cancel_message (src);
1721     }
1722   }
1723   if (!src->msg) {
1724     /* EOS immediately if we have an empty segment */
1725     if (src->request_position == src->stop_position)
1726       return GST_FLOW_EOS;
1727
1728     if (!gst_soup_http_src_build_message (src, method))
1729       return GST_FLOW_ERROR;
1730   }
1731
1732   src->ret = GST_FLOW_CUSTOM_ERROR;
1733   src->outbuf = outbuf;
1734   do {
1735     if (src->interrupted) {
1736       GST_INFO_OBJECT (src, "interrupted");
1737       src->ret = GST_FLOW_FLUSHING;
1738       break;
1739     }
1740     if (src->retry) {
1741       GST_INFO_OBJECT (src, "Reconnecting");
1742
1743       /* EOS immediately if we have an empty segment */
1744       if (src->request_position == src->stop_position)
1745         return GST_FLOW_EOS;
1746
1747       if (!gst_soup_http_src_build_message (src, method))
1748         return GST_FLOW_ERROR;
1749       src->retry = FALSE;
1750       continue;
1751     }
1752     if (!src->msg) {
1753       GST_DEBUG_OBJECT (src, "EOS reached");
1754       break;
1755     }
1756
1757     switch (src->session_io_status) {
1758       case GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_IDLE:
1759         GST_INFO_OBJECT (src, "Queueing connection request");
1760         gst_soup_http_src_queue_message (src);
1761         break;
1762       case GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_QUEUED:
1763         break;
1764       case GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING:
1765         gst_soup_http_src_session_unpause_message (src);
1766         break;
1767       case GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_CANCELLED:
1768         /* Impossible. */
1769         break;
1770     }
1771
1772     if (src->ret == GST_FLOW_CUSTOM_ERROR) {
1773       g_main_context_push_thread_default (src->context);
1774       g_main_loop_run (src->loop);
1775       g_main_context_pop_thread_default (src->context);
1776     }
1777
1778   } while (src->ret == GST_FLOW_CUSTOM_ERROR);
1779
1780   /* Let the request finish if we had a stop position and are there */
1781   if (src->ret == GST_FLOW_OK && src->stop_position != -1
1782       && src->read_position >= src->stop_position) {
1783     src->outbuf = NULL;
1784     gst_soup_http_src_session_unpause_message (src);
1785     g_main_context_push_thread_default (src->context);
1786     g_main_loop_run (src->loop);
1787     g_main_context_pop_thread_default (src->context);
1788
1789     g_cond_signal (&src->request_finished_cond);
1790     /* Return OK unconditionally here, src->ret will
1791      * be most likely be EOS now but we want to
1792      * consume the buffer we got above */
1793     return GST_FLOW_OK;
1794   }
1795
1796   if (src->ret == GST_FLOW_CUSTOM_ERROR)
1797     src->ret = GST_FLOW_EOS;
1798   g_cond_signal (&src->request_finished_cond);
1799
1800   /* basesrc assumes that we don't return a buffer if
1801    * something else than OK is returned. It will just
1802    * leak any buffer we might accidentially provide
1803    * here.
1804    *
1805    * This can potentially happen during flushing.
1806    */
1807   if (src->ret != GST_FLOW_OK && outbuf && *outbuf) {
1808     gst_buffer_unref (*outbuf);
1809     *outbuf = NULL;
1810   }
1811
1812   return src->ret;
1813 }
1814
1815 static GstFlowReturn
1816 gst_soup_http_src_create (GstPushSrc * psrc, GstBuffer ** outbuf)
1817 {
1818   GstSoupHTTPSrc *src;
1819   GstFlowReturn ret;
1820   GstEvent *http_headers_event;
1821
1822   src = GST_SOUP_HTTP_SRC (psrc);
1823
1824   g_mutex_lock (&src->mutex);
1825   *outbuf = NULL;
1826   ret =
1827       gst_soup_http_src_do_request (src,
1828       src->method ? src->method : SOUP_METHOD_GET, outbuf);
1829   http_headers_event = src->http_headers_event;
1830   src->http_headers_event = NULL;
1831   g_mutex_unlock (&src->mutex);
1832
1833   if (http_headers_event)
1834     gst_pad_push_event (GST_BASE_SRC_PAD (src), http_headers_event);
1835
1836   return ret;
1837 }
1838
1839 static gboolean
1840 gst_soup_http_src_start (GstBaseSrc * bsrc)
1841 {
1842   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
1843
1844   GST_DEBUG_OBJECT (src, "start(\"%s\")", src->location);
1845
1846   return gst_soup_http_src_session_open (src);
1847 }
1848
1849 static gboolean
1850 gst_soup_http_src_stop (GstBaseSrc * bsrc)
1851 {
1852   GstSoupHTTPSrc *src;
1853
1854   src = GST_SOUP_HTTP_SRC (bsrc);
1855   GST_DEBUG_OBJECT (src, "stop()");
1856   if (src->keep_alive && !src->msg)
1857     gst_soup_http_src_cancel_message (src);
1858   else
1859     gst_soup_http_src_session_close (src);
1860
1861   gst_soup_http_src_reset (src);
1862   return TRUE;
1863 }
1864
1865 static GstStateChangeReturn
1866 gst_soup_http_src_change_state (GstElement * element, GstStateChange transition)
1867 {
1868   GstStateChangeReturn ret;
1869   GstSoupHTTPSrc *src;
1870
1871   src = GST_SOUP_HTTP_SRC (element);
1872
1873   switch (transition) {
1874     case GST_STATE_CHANGE_READY_TO_NULL:
1875       gst_soup_http_src_session_close (src);
1876       break;
1877     default:
1878       break;
1879   }
1880
1881   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1882
1883   return ret;
1884 }
1885
1886 /* Interrupt a blocking request. */
1887 static gboolean
1888 gst_soup_http_src_unlock (GstBaseSrc * bsrc)
1889 {
1890   GstSoupHTTPSrc *src;
1891
1892   src = GST_SOUP_HTTP_SRC (bsrc);
1893   GST_DEBUG_OBJECT (src, "unlock()");
1894
1895   src->interrupted = TRUE;
1896   src->ret = GST_FLOW_FLUSHING;
1897   if (src->loop)
1898     g_main_loop_quit (src->loop);
1899   g_cond_signal (&src->request_finished_cond);
1900   return TRUE;
1901 }
1902
1903 /* Interrupt interrupt. */
1904 static gboolean
1905 gst_soup_http_src_unlock_stop (GstBaseSrc * bsrc)
1906 {
1907   GstSoupHTTPSrc *src;
1908
1909   src = GST_SOUP_HTTP_SRC (bsrc);
1910   GST_DEBUG_OBJECT (src, "unlock_stop()");
1911
1912   src->interrupted = FALSE;
1913   src->ret = GST_FLOW_OK;
1914   return TRUE;
1915 }
1916
1917 static gboolean
1918 gst_soup_http_src_get_size (GstBaseSrc * bsrc, guint64 * size)
1919 {
1920   GstSoupHTTPSrc *src;
1921
1922   src = GST_SOUP_HTTP_SRC (bsrc);
1923
1924   if (src->have_size) {
1925     GST_DEBUG_OBJECT (src, "get_size() = %" G_GUINT64_FORMAT,
1926         src->content_size);
1927     *size = src->content_size;
1928     return TRUE;
1929   }
1930   GST_DEBUG_OBJECT (src, "get_size() = FALSE");
1931   return FALSE;
1932 }
1933
1934 static void
1935 gst_soup_http_src_check_seekable (GstSoupHTTPSrc * src)
1936 {
1937   GstFlowReturn ret = GST_FLOW_OK;
1938
1939   /* Special case to check if the server allows range requests
1940    * before really starting to get data in the buffer creation
1941    * loops.
1942    */
1943   if (!src->got_headers && GST_STATE (src) >= GST_STATE_PAUSED) {
1944     g_mutex_lock (&src->mutex);
1945     while (!src->got_headers && !src->interrupted && ret == GST_FLOW_OK) {
1946       if ((src->msg && src->msg->method != SOUP_METHOD_HEAD) &&
1947           src->session_io_status != GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_IDLE) {
1948         /* wait for the current request to finish */
1949         g_cond_wait (&src->request_finished_cond, &src->mutex);
1950       } else {
1951         if (gst_soup_http_src_session_open (src)) {
1952           ret = gst_soup_http_src_do_request (src, SOUP_METHOD_HEAD, NULL);
1953         }
1954       }
1955     }
1956     if (src->ret == GST_FLOW_EOS) {
1957       /* A HEAD request shouldn't lead to EOS */
1958       src->ret = GST_FLOW_OK;
1959     }
1960     /* resets status to idle */
1961     gst_soup_http_src_cancel_message (src);
1962     g_mutex_unlock (&src->mutex);
1963   }
1964 }
1965
1966 static gboolean
1967 gst_soup_http_src_is_seekable (GstBaseSrc * bsrc)
1968 {
1969   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
1970
1971   gst_soup_http_src_check_seekable (src);
1972
1973   return src->seekable;
1974 }
1975
1976 static gboolean
1977 gst_soup_http_src_do_seek (GstBaseSrc * bsrc, GstSegment * segment)
1978 {
1979   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
1980
1981   GST_DEBUG_OBJECT (src, "do_seek(%" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT
1982       ")", segment->start, segment->stop);
1983   if (src->read_position == segment->start &&
1984       src->request_position == src->read_position &&
1985       src->stop_position == segment->stop) {
1986     GST_DEBUG_OBJECT (src,
1987         "Seek to current read/end position and no seek pending");
1988     return TRUE;
1989   }
1990
1991   gst_soup_http_src_check_seekable (src);
1992
1993   /* If we have no headers we don't know yet if it is seekable or not.
1994    * Store the start position and error out later if it isn't */
1995   if (src->got_headers && !src->seekable) {
1996     GST_WARNING_OBJECT (src, "Not seekable");
1997     return FALSE;
1998   }
1999
2000   if (segment->rate < 0.0 || segment->format != GST_FORMAT_BYTES) {
2001     GST_WARNING_OBJECT (src, "Invalid seek segment");
2002     return FALSE;
2003   }
2004
2005   if (src->have_size && segment->start >= src->content_size) {
2006     GST_WARNING_OBJECT (src,
2007         "Potentially seeking behind end of file, might EOS immediately");
2008   }
2009
2010   /* Wait for create() to handle the jump in offset. */
2011   src->request_position = segment->start;
2012   src->stop_position = segment->stop;
2013
2014   return TRUE;
2015 }
2016
2017 static gboolean
2018 gst_soup_http_src_query (GstBaseSrc * bsrc, GstQuery * query)
2019 {
2020   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
2021   gboolean ret;
2022   GstSchedulingFlags flags;
2023   gint minsize, maxsize, align;
2024
2025   switch (GST_QUERY_TYPE (query)) {
2026     case GST_QUERY_URI:
2027       gst_query_set_uri (query, src->location);
2028       if (src->redirection_uri != NULL) {
2029         gst_query_set_uri_redirection (query, src->redirection_uri);
2030         gst_query_set_uri_redirection_permanent (query,
2031             src->redirection_permanent);
2032       }
2033       ret = TRUE;
2034       break;
2035     default:
2036       ret = FALSE;
2037       break;
2038   }
2039
2040   if (!ret)
2041     ret = GST_BASE_SRC_CLASS (parent_class)->query (bsrc, query);
2042
2043   switch (GST_QUERY_TYPE (query)) {
2044     case GST_QUERY_SCHEDULING:
2045       gst_query_parse_scheduling (query, &flags, &minsize, &maxsize, &align);
2046       flags |= GST_SCHEDULING_FLAG_BANDWIDTH_LIMITED;
2047       gst_query_set_scheduling (query, flags, minsize, maxsize, align);
2048       break;
2049     default:
2050       break;
2051   }
2052
2053   return ret;
2054 }
2055
2056 static gboolean
2057 gst_soup_http_src_set_location (GstSoupHTTPSrc * src, const gchar * uri,
2058     GError ** error)
2059 {
2060   const char *alt_schemes[] = { "icy://", "icyx://" };
2061   guint i;
2062
2063   if (src->location) {
2064     g_free (src->location);
2065     src->location = NULL;
2066   }
2067
2068   if (uri == NULL)
2069     return FALSE;
2070
2071   for (i = 0; i < G_N_ELEMENTS (alt_schemes); i++) {
2072     if (g_str_has_prefix (uri, alt_schemes[i])) {
2073       src->location =
2074           g_strdup_printf ("http://%s", uri + strlen (alt_schemes[i]));
2075       return TRUE;
2076     }
2077   }
2078
2079   if (src->redirection_uri) {
2080     g_free (src->redirection_uri);
2081     src->redirection_uri = NULL;
2082   }
2083
2084   src->location = g_strdup (uri);
2085
2086   return TRUE;
2087 }
2088
2089 static gboolean
2090 gst_soup_http_src_set_proxy (GstSoupHTTPSrc * src, const gchar * uri)
2091 {
2092   if (src->proxy) {
2093     soup_uri_free (src->proxy);
2094     src->proxy = NULL;
2095   }
2096
2097   if (uri == NULL || *uri == '\0')
2098     return TRUE;
2099
2100   if (g_str_has_prefix (uri, "http://")) {
2101     src->proxy = soup_uri_new (uri);
2102   } else {
2103     gchar *new_uri = g_strconcat ("http://", uri, NULL);
2104
2105     src->proxy = soup_uri_new (new_uri);
2106     g_free (new_uri);
2107   }
2108
2109   return (src->proxy != NULL);
2110 }
2111
2112 static guint
2113 gst_soup_http_src_uri_get_type (GType type)
2114 {
2115   return GST_URI_SRC;
2116 }
2117
2118 static const gchar *const *
2119 gst_soup_http_src_uri_get_protocols (GType type)
2120 {
2121   static const gchar *protocols[] = { "http", "https", "icy", "icyx", NULL };
2122
2123   return protocols;
2124 }
2125
2126 static gchar *
2127 gst_soup_http_src_uri_get_uri (GstURIHandler * handler)
2128 {
2129   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (handler);
2130
2131   /* FIXME: make thread-safe */
2132   return g_strdup (src->location);
2133 }
2134
2135 static gboolean
2136 gst_soup_http_src_uri_set_uri (GstURIHandler * handler, const gchar * uri,
2137     GError ** error)
2138 {
2139   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (handler);
2140
2141   return gst_soup_http_src_set_location (src, uri, error);
2142 }
2143
2144 static void
2145 gst_soup_http_src_uri_handler_init (gpointer g_iface, gpointer iface_data)
2146 {
2147   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
2148
2149   iface->get_type = gst_soup_http_src_uri_get_type;
2150   iface->get_protocols = gst_soup_http_src_uri_get_protocols;
2151   iface->get_uri = gst_soup_http_src_uri_get_uri;
2152   iface->set_uri = gst_soup_http_src_uri_set_uri;
2153 }