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