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