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