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