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