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