souphttpsrc: fix coverity issue
[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 ! 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 static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src",
90     GST_PAD_SRC,
91     GST_PAD_ALWAYS,
92     GST_STATIC_CAPS_ANY);
93
94 enum
95 {
96   PROP_0,
97   PROP_LOCATION,
98   PROP_IS_LIVE,
99   PROP_USER_AGENT,
100   PROP_AUTOMATIC_REDIRECT,
101   PROP_PROXY,
102   PROP_USER_ID,
103   PROP_USER_PW,
104   PROP_PROXY_ID,
105   PROP_PROXY_PW,
106   PROP_COOKIES,
107   PROP_IRADIO_MODE,
108   PROP_TIMEOUT,
109   PROP_EXTRA_HEADERS,
110   PROP_SOUP_LOG_LEVEL,
111   PROP_COMPRESS,
112   PROP_KEEP_ALIVE,
113   PROP_SSL_STRICT,
114   PROP_SSL_CA_FILE,
115   PROP_SSL_USE_SYSTEM_CA_FILE,
116   PROP_TLS_DATABASE,
117   PROP_RETRIES,
118   PROP_METHOD,
119   PROP_TLS_INTERACTION,
120 };
121
122 #define DEFAULT_USER_AGENT           "GStreamer souphttpsrc " PACKAGE_VERSION " "
123 #define DEFAULT_IRADIO_MODE          TRUE
124 #define DEFAULT_SOUP_LOG_LEVEL       SOUP_LOGGER_LOG_HEADERS
125 #define DEFAULT_COMPRESS             FALSE
126 #define DEFAULT_KEEP_ALIVE           FALSE
127 #define DEFAULT_SSL_STRICT           TRUE
128 #define DEFAULT_SSL_CA_FILE          NULL
129 #define DEFAULT_SSL_USE_SYSTEM_CA_FILE TRUE
130 #define DEFAULT_TLS_DATABASE         NULL
131 #define DEFAULT_TLS_INTERACTION      NULL
132 #define DEFAULT_TIMEOUT              15
133 #define DEFAULT_RETRIES              3
134 #define DEFAULT_SOUP_METHOD          NULL
135
136 #define GROW_BLOCKSIZE_LIMIT 1
137 #define GROW_BLOCKSIZE_COUNT 1
138 #define GROW_BLOCKSIZE_FACTOR 2
139 #define REDUCE_BLOCKSIZE_LIMIT 0.20
140 #define REDUCE_BLOCKSIZE_COUNT 2
141 #define REDUCE_BLOCKSIZE_FACTOR 0.5
142
143 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
144 #define DLNA_OP_TIMED_SEEK  0x02
145 #define DLNA_OP_BYTE_SEEK   0x01
146 #endif
147
148 static void gst_soup_http_src_uri_handler_init (gpointer g_iface,
149     gpointer iface_data);
150 static void gst_soup_http_src_finalize (GObject * gobject);
151 static void gst_soup_http_src_dispose (GObject * gobject);
152
153 static void gst_soup_http_src_set_property (GObject * object, guint prop_id,
154     const GValue * value, GParamSpec * pspec);
155 static void gst_soup_http_src_get_property (GObject * object, guint prop_id,
156     GValue * value, GParamSpec * pspec);
157
158 static GstStateChangeReturn gst_soup_http_src_change_state (GstElement *
159     element, GstStateChange transition);
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
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
422   gstbasesrc_class->start = GST_DEBUG_FUNCPTR (gst_soup_http_src_start);
423   gstbasesrc_class->stop = GST_DEBUG_FUNCPTR (gst_soup_http_src_stop);
424   gstbasesrc_class->unlock = GST_DEBUG_FUNCPTR (gst_soup_http_src_unlock);
425   gstbasesrc_class->unlock_stop =
426       GST_DEBUG_FUNCPTR (gst_soup_http_src_unlock_stop);
427   gstbasesrc_class->get_size = GST_DEBUG_FUNCPTR (gst_soup_http_src_get_size);
428   gstbasesrc_class->is_seekable =
429       GST_DEBUG_FUNCPTR (gst_soup_http_src_is_seekable);
430   gstbasesrc_class->do_seek = GST_DEBUG_FUNCPTR (gst_soup_http_src_do_seek);
431   gstbasesrc_class->query = GST_DEBUG_FUNCPTR (gst_soup_http_src_query);
432
433   gstpushsrc_class->create = GST_DEBUG_FUNCPTR (gst_soup_http_src_create);
434
435   GST_DEBUG_CATEGORY_INIT (souphttpsrc_debug, "souphttpsrc", 0,
436       "SOUP HTTP src");
437 }
438
439 static void
440 gst_soup_http_src_reset (GstSoupHTTPSrc * src)
441 {
442   src->retry_count = 0;
443   src->have_size = FALSE;
444   src->got_headers = FALSE;
445   src->seekable = FALSE;
446   src->read_position = 0;
447   src->request_position = 0;
448   src->stop_position = -1;
449   src->content_size = 0;
450   src->have_body = FALSE;
451
452   src->reduce_blocksize_count = 0;
453   src->increase_blocksize_count = 0;
454
455 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
456   if (src->dash_oldest_segment) {
457     g_free (src->dash_oldest_segment);
458     src->dash_oldest_segment = NULL;
459   }
460   if (src->dash_newest_segment) {
461     g_free (src->dash_newest_segment);
462     src->dash_newest_segment = NULL;
463   }
464   src->dlna_opt = 0;
465 #endif
466
467   g_cancellable_reset (src->cancellable);
468   if (src->input_stream) {
469     g_object_unref (src->input_stream);
470     src->input_stream = NULL;
471   }
472
473   gst_caps_replace (&src->src_caps, NULL);
474   g_free (src->iradio_name);
475   src->iradio_name = NULL;
476   g_free (src->iradio_genre);
477   src->iradio_genre = NULL;
478   g_free (src->iradio_url);
479   src->iradio_url = NULL;
480 }
481
482 static void
483 gst_soup_http_src_init (GstSoupHTTPSrc * src)
484 {
485   const gchar *proxy;
486
487   g_mutex_init (&src->mutex);
488   g_cond_init (&src->have_headers_cond);
489   src->cancellable = g_cancellable_new ();
490   src->location = NULL;
491   src->redirection_uri = NULL;
492   src->automatic_redirect = TRUE;
493   src->user_agent = g_strdup (DEFAULT_USER_AGENT);
494   src->user_id = NULL;
495   src->user_pw = NULL;
496   src->proxy_id = NULL;
497   src->proxy_pw = NULL;
498   src->cookies = NULL;
499   src->iradio_mode = DEFAULT_IRADIO_MODE;
500   src->session = NULL;
501   src->msg = NULL;
502   src->timeout = DEFAULT_TIMEOUT;
503   src->log_level = DEFAULT_SOUP_LOG_LEVEL;
504   src->ssl_strict = DEFAULT_SSL_STRICT;
505   src->ssl_use_system_ca_file = DEFAULT_SSL_USE_SYSTEM_CA_FILE;
506   src->tls_database = DEFAULT_TLS_DATABASE;
507   src->tls_interaction = DEFAULT_TLS_INTERACTION;
508   src->max_retries = DEFAULT_RETRIES;
509   src->method = DEFAULT_SOUP_METHOD;
510   src->minimum_blocksize = gst_base_src_get_blocksize (GST_BASE_SRC_CAST (src));
511 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
512   src->dash_oldest_segment = NULL;
513   src->dash_newest_segment = NULL;
514   src->received_total = 0;
515   src->dlna_opt = 0;
516 #endif
517   proxy = g_getenv ("http_proxy");
518   if (!gst_soup_http_src_set_proxy (src, proxy)) {
519     GST_WARNING_OBJECT (src,
520         "The proxy in the http_proxy env var (\"%s\") cannot be parsed.",
521         proxy);
522   }
523 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
524   src->cookie_jar  = NULL;
525 #endif
526   gst_base_src_set_automatic_eos (GST_BASE_SRC (src), FALSE);
527
528   gst_soup_http_src_reset (src);
529 }
530
531 static void
532 gst_soup_http_src_dispose (GObject * gobject)
533 {
534   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (gobject);
535
536   GST_DEBUG_OBJECT (src, "dispose");
537
538   gst_soup_http_src_session_close (src);
539
540   G_OBJECT_CLASS (parent_class)->dispose (gobject);
541 }
542
543 static void
544 gst_soup_http_src_finalize (GObject * gobject)
545 {
546   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (gobject);
547
548   GST_DEBUG_OBJECT (src, "finalize");
549
550   g_mutex_clear (&src->mutex);
551   g_cond_clear (&src->have_headers_cond);
552   g_object_unref (src->cancellable);
553   g_free (src->location);
554   g_free (src->redirection_uri);
555   g_free (src->user_agent);
556   if (src->proxy != NULL) {
557     soup_uri_free (src->proxy);
558   }
559   g_free (src->user_id);
560   g_free (src->user_pw);
561   g_free (src->proxy_id);
562   g_free (src->proxy_pw);
563   g_strfreev (src->cookies);
564
565   if (src->extra_headers) {
566     gst_structure_free (src->extra_headers);
567     src->extra_headers = NULL;
568   }
569
570   g_free (src->ssl_ca_file);
571
572   if (src->tls_database)
573     g_object_unref (src->tls_database);
574   g_free (src->method);
575
576   if (src->tls_interaction)
577     g_object_unref (src->tls_interaction);
578
579   G_OBJECT_CLASS (parent_class)->finalize (gobject);
580 }
581
582 static void
583 gst_soup_http_src_set_property (GObject * object, guint prop_id,
584     const GValue * value, GParamSpec * pspec)
585 {
586   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (object);
587
588   switch (prop_id) {
589     case PROP_LOCATION:
590     {
591       const gchar *location;
592
593       location = g_value_get_string (value);
594
595       if (location == NULL) {
596         GST_WARNING ("location property cannot be NULL");
597         goto done;
598       }
599       if (!gst_soup_http_src_set_location (src, location, NULL)) {
600         GST_WARNING ("badly formatted location");
601         goto done;
602       }
603       break;
604     }
605     case PROP_USER_AGENT:
606       g_free (src->user_agent);
607       src->user_agent = g_value_dup_string (value);
608       break;
609     case PROP_IRADIO_MODE:
610       src->iradio_mode = g_value_get_boolean (value);
611       break;
612     case PROP_AUTOMATIC_REDIRECT:
613       src->automatic_redirect = g_value_get_boolean (value);
614       break;
615     case PROP_PROXY:
616     {
617       const gchar *proxy;
618
619       proxy = g_value_get_string (value);
620       if (!gst_soup_http_src_set_proxy (src, proxy)) {
621         GST_WARNING ("badly formatted proxy URI");
622         goto done;
623       }
624       break;
625     }
626     case PROP_COOKIES:
627 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
628     {
629       char **array;
630       SoupURI *base_uri;
631       SoupCookie *cookie_parsed = NULL;
632
633       g_strfreev (src->cookies);
634       src->cookies = g_strdupv (g_value_get_boxed (value));
635
636       if (src->cookie_jar && ((array = src->cookies) != NULL)) {
637         base_uri = soup_uri_new (src->location);
638         GST_INFO_OBJECT (src, "request to set cookies...");
639         while (*array != NULL) {
640           cookie_parsed = soup_cookie_parse (*array++, base_uri);
641           if (cookie_parsed && cookie_parsed->domain)
642             soup_cookie_jar_add_cookie (src->cookie_jar, cookie_parsed);
643         }
644         soup_uri_free (base_uri);
645       } else {
646         GST_INFO_OBJECT (src, "set cookies after session creation");
647       }
648     }
649 #else
650       g_strfreev (src->cookies);
651       src->cookies = g_strdupv (g_value_get_boxed (value));
652 #endif
653       break;
654     case PROP_IS_LIVE:
655       gst_base_src_set_live (GST_BASE_SRC (src), g_value_get_boolean (value));
656       break;
657     case PROP_USER_ID:
658       g_free (src->user_id);
659       src->user_id = g_value_dup_string (value);
660       break;
661     case PROP_USER_PW:
662       g_free (src->user_pw);
663       src->user_pw = g_value_dup_string (value);
664       break;
665     case PROP_PROXY_ID:
666       g_free (src->proxy_id);
667       src->proxy_id = g_value_dup_string (value);
668       break;
669     case PROP_PROXY_PW:
670       g_free (src->proxy_pw);
671       src->proxy_pw = g_value_dup_string (value);
672       break;
673     case PROP_TIMEOUT:
674       src->timeout = g_value_get_uint (value);
675       break;
676     case PROP_EXTRA_HEADERS:{
677       const GstStructure *s = gst_value_get_structure (value);
678
679       if (src->extra_headers)
680         gst_structure_free (src->extra_headers);
681
682       src->extra_headers = s ? gst_structure_copy (s) : NULL;
683       break;
684     }
685     case PROP_SOUP_LOG_LEVEL:
686       src->log_level = g_value_get_enum (value);
687       break;
688     case PROP_COMPRESS:
689       src->compress = g_value_get_boolean (value);
690       break;
691     case PROP_KEEP_ALIVE:
692       src->keep_alive = g_value_get_boolean (value);
693       break;
694     case PROP_SSL_STRICT:
695       src->ssl_strict = g_value_get_boolean (value);
696       break;
697     case PROP_SSL_CA_FILE:
698       g_free (src->ssl_ca_file);
699       src->ssl_ca_file = g_value_dup_string (value);
700       break;
701     case PROP_SSL_USE_SYSTEM_CA_FILE:
702       src->ssl_use_system_ca_file = g_value_get_boolean (value);
703       break;
704     case PROP_TLS_DATABASE:
705       g_clear_object (&src->tls_database);
706       src->tls_database = g_value_dup_object (value);
707       break;
708     case PROP_TLS_INTERACTION:
709       g_clear_object (&src->tls_interaction);
710       src->tls_interaction = g_value_dup_object (value);
711       break;
712     case PROP_RETRIES:
713       src->max_retries = g_value_get_int (value);
714       break;
715     case PROP_METHOD:
716       g_free (src->method);
717       src->method = g_value_dup_string (value);
718       break;
719     default:
720       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
721       break;
722   }
723 done:
724   return;
725 }
726
727 static void
728 gst_soup_http_src_get_property (GObject * object, guint prop_id,
729     GValue * value, GParamSpec * pspec)
730 {
731   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (object);
732
733   switch (prop_id) {
734     case PROP_LOCATION:
735       g_value_set_string (value, src->location);
736       break;
737     case PROP_USER_AGENT:
738       g_value_set_string (value, src->user_agent);
739       break;
740     case PROP_AUTOMATIC_REDIRECT:
741       g_value_set_boolean (value, src->automatic_redirect);
742       break;
743     case PROP_PROXY:
744       if (src->proxy == NULL)
745         g_value_set_static_string (value, "");
746       else {
747         char *proxy = soup_uri_to_string (src->proxy, FALSE);
748
749         g_value_set_string (value, proxy);
750         g_free (proxy);
751       }
752       break;
753     case PROP_COOKIES:
754 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
755     {
756         GSList *cookie_list, *c;
757         gchar **cookies, **array;
758
759         cookies = NULL;
760         if ((src->cookie_jar) &&
761             ((cookie_list = soup_cookie_jar_all_cookies (src->cookie_jar)) != NULL)) {
762           cookies = g_new0 (gchar *, g_slist_length(cookie_list) + 1);
763           array = cookies;
764           for (c = cookie_list; c; c = c->next) {
765             *array++ = soup_cookie_to_set_cookie_header ((SoupCookie *)(c->data));
766           }
767           soup_cookies_free (cookie_list);
768         }
769         g_value_set_boxed (value, cookies);
770     }
771 #else
772         g_value_set_boxed (value, g_strdupv (src->cookies));
773 #endif
774       break;
775     case PROP_IS_LIVE:
776       g_value_set_boolean (value, gst_base_src_is_live (GST_BASE_SRC (src)));
777       break;
778     case PROP_IRADIO_MODE:
779       g_value_set_boolean (value, src->iradio_mode);
780       break;
781     case PROP_USER_ID:
782       g_value_set_string (value, src->user_id);
783       break;
784     case PROP_USER_PW:
785       g_value_set_string (value, src->user_pw);
786       break;
787     case PROP_PROXY_ID:
788       g_value_set_string (value, src->proxy_id);
789       break;
790     case PROP_PROXY_PW:
791       g_value_set_string (value, src->proxy_pw);
792       break;
793     case PROP_TIMEOUT:
794       g_value_set_uint (value, src->timeout);
795       break;
796     case PROP_EXTRA_HEADERS:
797       gst_value_set_structure (value, src->extra_headers);
798       break;
799     case PROP_SOUP_LOG_LEVEL:
800       g_value_set_enum (value, src->log_level);
801       break;
802     case PROP_COMPRESS:
803       g_value_set_boolean (value, src->compress);
804       break;
805     case PROP_KEEP_ALIVE:
806       g_value_set_boolean (value, src->keep_alive);
807       break;
808     case PROP_SSL_STRICT:
809       g_value_set_boolean (value, src->ssl_strict);
810       break;
811     case PROP_SSL_CA_FILE:
812       g_value_set_string (value, src->ssl_ca_file);
813       break;
814     case PROP_SSL_USE_SYSTEM_CA_FILE:
815       g_value_set_boolean (value, src->ssl_use_system_ca_file);
816       break;
817     case PROP_TLS_DATABASE:
818       g_value_set_object (value, src->tls_database);
819       break;
820     case PROP_TLS_INTERACTION:
821       g_value_set_object (value, src->tls_interaction);
822       break;
823     case PROP_RETRIES:
824       g_value_set_int (value, src->max_retries);
825       break;
826     case PROP_METHOD:
827       g_value_set_string (value, src->method);
828       break;
829     default:
830       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
831       break;
832   }
833 }
834
835 static gchar *
836 gst_soup_http_src_unicodify (const gchar * str)
837 {
838   const gchar *env_vars[] = { "GST_ICY_TAG_ENCODING",
839     "GST_TAG_ENCODING", NULL
840   };
841
842   return gst_tag_freeform_string_to_utf8 (str, -1, env_vars);
843 }
844
845 static void
846 gst_soup_http_src_cancel_message (GstSoupHTTPSrc * src)
847 {
848   g_cancellable_cancel (src->cancellable);
849   g_cond_signal (&src->have_headers_cond);
850 }
851
852 static gboolean
853 gst_soup_http_src_add_range_header (GstSoupHTTPSrc * src, guint64 offset,
854     guint64 stop_offset)
855 {
856   gchar buf[64];
857   gint rc;
858
859   soup_message_headers_remove (src->msg->request_headers, "Range");
860
861 /* This changes are needed to enable Seekable Contents from server.
862    We have observed that , for few specific networks ( VODAFONE ) , without theabove headers ,
863    Youtube is sending non-seekable contents to the Client. */
864 #ifndef TIZEN_FEATURE_SOUP_MODIFICATION
865   if (offset || stop_offset != -1)
866 #endif
867   {
868     if (stop_offset != -1) {
869       g_assert (offset != stop_offset);
870
871       rc = g_snprintf (buf, sizeof (buf), "bytes=%" G_GUINT64_FORMAT "-%"
872           G_GUINT64_FORMAT, offset, (stop_offset > 0) ? stop_offset - 1 :
873           stop_offset);
874     } else {
875       rc = g_snprintf (buf, sizeof (buf), "bytes=%" G_GUINT64_FORMAT "-",
876                 offset);
877     }
878     if (rc > sizeof (buf) || rc < 0)
879       return FALSE;
880     soup_message_headers_append (src->msg->request_headers, "Range", buf);
881   }
882
883   src->read_position = offset;
884   return TRUE;
885 }
886
887 static gboolean
888 _append_extra_header (GQuark field_id, const GValue * value, gpointer user_data)
889 {
890   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (user_data);
891   const gchar *field_name = g_quark_to_string (field_id);
892   gchar *field_content = NULL;
893
894   if (G_VALUE_TYPE (value) == G_TYPE_STRING) {
895     field_content = g_value_dup_string (value);
896   } else {
897     GValue dest = { 0, };
898
899     g_value_init (&dest, G_TYPE_STRING);
900     if (g_value_transform (value, &dest)) {
901       field_content = g_value_dup_string (&dest);
902     }
903   }
904
905   if (field_content == NULL) {
906     GST_ERROR_OBJECT (src, "extra-headers field '%s' contains no value "
907         "or can't be converted to a string", field_name);
908     return FALSE;
909   }
910
911   GST_DEBUG_OBJECT (src, "Appending extra header: \"%s: %s\"", field_name,
912       field_content);
913   soup_message_headers_append (src->msg->request_headers, field_name,
914       field_content);
915
916 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
917   if (!g_ascii_strcasecmp(field_name, "Cookie")) {
918     SoupURI *uri = NULL;
919     SoupCookie *cookie_parsed = NULL;
920     gchar *saveptr = NULL;
921
922     if (strlen(field_content) > 0) {
923       gchar *tmp_field = NULL;
924
925       uri = soup_uri_new (src->location);
926
927       tmp_field = strtok_r (field_content, ";", &saveptr);
928
929       while (tmp_field != NULL) {
930         GST_DEBUG_OBJECT (src, "field_content = %s", tmp_field);
931
932         cookie_parsed = soup_cookie_parse(tmp_field, uri);
933         GST_DEBUG_OBJECT (src, "cookie parsed = %p", cookie_parsed);
934
935         if (src->cookie_jar && cookie_parsed && cookie_parsed->domain)
936           soup_cookie_jar_add_cookie (src->cookie_jar, cookie_parsed);
937
938         tmp_field = strtok_r (NULL, ";", &saveptr);
939       }
940       soup_uri_free (uri);
941     }
942   }
943 #endif
944
945   g_free (field_content);
946
947   return TRUE;
948 }
949
950 static gboolean
951 _append_extra_headers (GQuark field_id, const GValue * value,
952     gpointer user_data)
953 {
954   if (G_VALUE_TYPE (value) == GST_TYPE_ARRAY) {
955     guint n = gst_value_array_get_size (value);
956     guint i;
957
958     for (i = 0; i < n; i++) {
959       const GValue *v = gst_value_array_get_value (value, i);
960
961       if (!_append_extra_header (field_id, v, user_data))
962         return FALSE;
963     }
964   } else if (G_VALUE_TYPE (value) == GST_TYPE_LIST) {
965     guint n = gst_value_list_get_size (value);
966     guint i;
967
968     for (i = 0; i < n; i++) {
969       const GValue *v = gst_value_list_get_value (value, i);
970
971       if (!_append_extra_header (field_id, v, user_data))
972         return FALSE;
973     }
974   } else {
975     return _append_extra_header (field_id, value, user_data);
976   }
977
978   return TRUE;
979 }
980
981
982 static gboolean
983 gst_soup_http_src_add_extra_headers (GstSoupHTTPSrc * src)
984 {
985   if (!src->extra_headers)
986     return TRUE;
987
988   return gst_structure_foreach (src->extra_headers, _append_extra_headers, src);
989 }
990
991 static gboolean
992 gst_soup_http_src_session_open (GstSoupHTTPSrc * src)
993 {
994   if (src->session) {
995     GST_DEBUG_OBJECT (src, "Session is already open");
996     return TRUE;
997   }
998
999   if (!src->location) {
1000     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (_("No URL set.")),
1001         ("Missing location property"));
1002     return FALSE;
1003   }
1004
1005   if (!src->session) {
1006     GST_DEBUG_OBJECT (src, "Creating session");
1007     if (src->proxy == NULL) {
1008       src->session =
1009           soup_session_new_with_options (SOUP_SESSION_USER_AGENT,
1010           src->user_agent, SOUP_SESSION_TIMEOUT, src->timeout,
1011           SOUP_SESSION_SSL_STRICT, src->ssl_strict, NULL);
1012 //          SOUP_SESSION_TLS_INTERACTION, src->tls_interaction, NULL);
1013     } else {
1014       src->session =
1015           soup_session_new_with_options (SOUP_SESSION_PROXY_URI, src->proxy,
1016           SOUP_SESSION_TIMEOUT, src->timeout,
1017           SOUP_SESSION_SSL_STRICT, src->ssl_strict,
1018           SOUP_SESSION_USER_AGENT, src->user_agent, NULL);
1019 //          SOUP_SESSION_TLS_INTERACTION, src->tls_interaction, NULL);
1020     }
1021
1022     if (!src->session) {
1023       GST_ELEMENT_ERROR (src, LIBRARY, INIT,
1024           (NULL), ("Failed to create async session"));
1025       return FALSE;
1026     }
1027
1028 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
1029     {
1030       char **array = NULL;
1031       SoupURI *base_uri;
1032       SoupCookie *soup_cookie = NULL;
1033
1034       soup_session_add_feature_by_type (src->session, SOUP_TYPE_COOKIE_JAR);
1035       src->cookie_jar = SOUP_COOKIE_JAR (soup_session_get_feature (src->session, SOUP_TYPE_COOKIE_JAR));
1036       if ((array = src->cookies) != NULL) {
1037         base_uri = soup_uri_new (src->location);
1038         while (*array != NULL) {
1039           soup_cookie = soup_cookie_parse (*array++, base_uri);
1040           if (soup_cookie && soup_cookie->domain) {
1041             GST_INFO_OBJECT (src, "adding cookies..");
1042             soup_cookie_jar_add_cookie (src->cookie_jar, soup_cookie);
1043           }
1044         }
1045         soup_uri_free (base_uri);
1046       }
1047     }
1048 #endif
1049
1050     g_signal_connect (src->session, "authenticate",
1051         G_CALLBACK (gst_soup_http_src_authenticate_cb), src);
1052
1053     /* Set up logging */
1054     gst_soup_util_log_setup (src->session, src->log_level, GST_ELEMENT (src));
1055     if (src->tls_database)
1056       g_object_set (src->session, "tls-database", src->tls_database, NULL);
1057     else if (src->ssl_ca_file)
1058       g_object_set (src->session, "ssl-ca-file", src->ssl_ca_file, NULL);
1059     else
1060       g_object_set (src->session, "ssl-use-system-ca-file",
1061           src->ssl_use_system_ca_file, NULL);
1062   } else {
1063     GST_DEBUG_OBJECT (src, "Re-using session");
1064   }
1065
1066   if (src->compress)
1067     soup_session_add_feature_by_type (src->session, SOUP_TYPE_CONTENT_DECODER);
1068   else
1069     soup_session_remove_feature_by_type (src->session,
1070         SOUP_TYPE_CONTENT_DECODER);
1071
1072   return TRUE;
1073 }
1074
1075 static void
1076 gst_soup_http_src_session_close (GstSoupHTTPSrc * src)
1077 {
1078   GST_DEBUG_OBJECT (src, "Closing session");
1079
1080   g_mutex_lock (&src->mutex);
1081   if (src->msg) {
1082     soup_session_cancel_message (src->session, src->msg, SOUP_STATUS_CANCELLED);
1083     g_object_unref (src->msg);
1084     src->msg = NULL;
1085   }
1086
1087   if (src->session) {
1088 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
1089 /* When Playback is ongoing and Browser is moved to background ( Pressing Menu or Home Key ), The Session gets destroyed.
1090    But the cookie_jar property remains unfreed. This results in garbage pointer and causes crash.
1091    Removing the cookie_jar feature during close session of browser to handle the issue. */
1092     GST_DEBUG_OBJECT (src, "Removing Cookie Jar instance");
1093     soup_session_remove_feature_by_type(src->session, SOUP_TYPE_COOKIE_JAR);
1094     src->cookie_jar = NULL;
1095 #endif
1096     soup_session_abort (src->session);
1097     g_object_unref (src->session);
1098     src->session = NULL;
1099   }
1100   g_mutex_unlock (&src->mutex);
1101 }
1102
1103 static void
1104 gst_soup_http_src_authenticate_cb (SoupSession * session, SoupMessage * msg,
1105     SoupAuth * auth, gboolean retrying, GstSoupHTTPSrc * src)
1106 {
1107   if (!retrying) {
1108     /* First time authentication only, if we fail and are called again with retry true fall through */
1109     if (msg->status_code == SOUP_STATUS_UNAUTHORIZED) {
1110       if (src->user_id && src->user_pw)
1111         soup_auth_authenticate (auth, src->user_id, src->user_pw);
1112     } else if (msg->status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED) {
1113       if (src->proxy_id && src->proxy_pw)
1114         soup_auth_authenticate (auth, src->proxy_id, src->proxy_pw);
1115     }
1116   }
1117 }
1118
1119 static void
1120 insert_http_header (const gchar * name, const gchar * value, gpointer user_data)
1121 {
1122   GstStructure *headers = user_data;
1123   const GValue *gv;
1124
1125   if (!g_utf8_validate (name, -1, NULL) || !g_utf8_validate (value, -1, NULL))
1126     return;
1127
1128   gv = gst_structure_get_value (headers, name);
1129   if (gv && GST_VALUE_HOLDS_ARRAY (gv)) {
1130     GValue v = G_VALUE_INIT;
1131
1132     g_value_init (&v, G_TYPE_STRING);
1133     g_value_set_string (&v, value);
1134     gst_value_array_append_value ((GValue *) gv, &v);
1135     g_value_unset (&v);
1136   } else if (gv && G_VALUE_HOLDS_STRING (gv)) {
1137     GValue arr = G_VALUE_INIT;
1138     GValue v = G_VALUE_INIT;
1139     const gchar *old_value = g_value_get_string (gv);
1140
1141     g_value_init (&arr, GST_TYPE_ARRAY);
1142     g_value_init (&v, G_TYPE_STRING);
1143     g_value_set_string (&v, old_value);
1144     gst_value_array_append_value (&arr, &v);
1145     g_value_set_string (&v, value);
1146     gst_value_array_append_value (&arr, &v);
1147
1148     gst_structure_set_value (headers, name, &arr);
1149     g_value_unset (&v);
1150     g_value_unset (&arr);
1151   } else {
1152     gst_structure_set (headers, name, G_TYPE_STRING, value, NULL);
1153   }
1154 }
1155
1156 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
1157 static void
1158 gst_soup_http_src_headers_foreach (const gchar * name, const gchar * val,
1159     gpointer src)
1160 {
1161   GST_INFO_OBJECT (src, " %s: %s", name, val);
1162
1163   if (g_ascii_strcasecmp (name, "Set-Cookie") == 0)
1164   {
1165     if (val)
1166     {
1167       gboolean bret = FALSE;
1168       GstStructure *s = NULL;
1169       GstSoupHTTPSrc * tmp = src;
1170       SoupURI *uri;
1171
1172       uri =  soup_uri_new (tmp->location);
1173
1174       /* post current bandwith & uri to application */
1175       s = gst_structure_new ("cookies",
1176             "updated-cookie", G_TYPE_STRING, val,
1177             "updated-url", G_TYPE_STRING, tmp->location, NULL);
1178       bret = gst_element_post_message (GST_ELEMENT_CAST (src), gst_message_new_element (GST_OBJECT_CAST (src), s));
1179       soup_cookie_jar_set_cookie (tmp->cookie_jar,  uri, val);
1180       soup_uri_free (uri);
1181
1182       GST_INFO_OBJECT (src, "request url [%s], posted cookies [%s] msg and returned = %d", tmp->location, val, bret);
1183     }
1184   }
1185   else if (g_ascii_strcasecmp (name, "Dash-Oldest-Segment") == 0)
1186   {
1187     if (val)
1188     {
1189       GstSoupHTTPSrc * tmp = src;
1190       tmp->dash_oldest_segment = g_strdup (val);
1191       GST_INFO_OBJECT (src, "Dash-Oldest-Segment set as %s ", tmp->dash_oldest_segment);
1192     }
1193   }
1194   else if (g_ascii_strcasecmp (name, "Dash-Newest-Segment") == 0)
1195   {
1196     if (val)
1197     {
1198       GstSoupHTTPSrc * tmp = src;
1199       tmp->dash_newest_segment = g_strdup (val);
1200       GST_INFO_OBJECT (src, "Dash-Newest-Segment set as %s ", tmp->dash_newest_segment);
1201     }
1202   }
1203 }
1204 #endif
1205
1206 static GstFlowReturn
1207 gst_soup_http_src_got_headers (GstSoupHTTPSrc * src, SoupMessage * msg)
1208 {
1209   const char *value;
1210   GstTagList *tag_list;
1211   GstBaseSrc *basesrc;
1212   guint64 newsize;
1213   GHashTable *params = NULL;
1214   GstEvent *http_headers_event;
1215   GstStructure *http_headers, *headers;
1216   const gchar *accept_ranges;
1217 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
1218   gint64 start = 0, stop = 0, total = 0;
1219 #endif
1220
1221   GST_INFO_OBJECT (src, "got headers : %d", msg->status_code);
1222 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
1223   soup_message_headers_foreach (msg->response_headers,
1224       gst_soup_http_src_headers_foreach, src);
1225 #endif
1226   if (msg->status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED &&
1227       src->proxy_id && src->proxy_pw) {
1228     /* wait for authenticate callback */
1229     return GST_FLOW_OK;
1230   }
1231
1232   if (msg->status_code == SOUP_STATUS_UNAUTHORIZED) {
1233     /* force an error */
1234     return gst_soup_http_src_parse_status (msg, src);
1235   }
1236
1237   src->got_headers = TRUE;
1238   g_cond_broadcast (&src->have_headers_cond);
1239
1240   http_headers = gst_structure_new_empty ("http-headers");
1241   gst_structure_set (http_headers, "uri", G_TYPE_STRING, src->location, NULL);
1242   if (src->redirection_uri)
1243     gst_structure_set (http_headers, "redirection-uri", G_TYPE_STRING,
1244         src->redirection_uri, NULL);
1245   headers = gst_structure_new_empty ("request-headers");
1246   soup_message_headers_foreach (msg->request_headers, insert_http_header,
1247       headers);
1248   gst_structure_set (http_headers, "request-headers", GST_TYPE_STRUCTURE,
1249       headers, NULL);
1250   gst_structure_free (headers);
1251   headers = gst_structure_new_empty ("response-headers");
1252   soup_message_headers_foreach (msg->response_headers, insert_http_header,
1253       headers);
1254   gst_structure_set (http_headers, "response-headers", GST_TYPE_STRUCTURE,
1255       headers, NULL);
1256   gst_structure_free (headers);
1257
1258   http_headers_event =
1259       gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM_STICKY, http_headers);
1260   gst_event_replace (&src->http_headers_event, http_headers_event);
1261   gst_event_unref (http_headers_event);
1262
1263 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
1264   /* Parse DLNA OP CODE */
1265   if ((value = soup_message_headers_get_one
1266         (msg->response_headers, "contentFeatures.dlna.org")) != NULL) {
1267     gchar **token = NULL;
1268     gchar **ptr = NULL;
1269
1270     GST_DEBUG_OBJECT (src, "DLNA server response");
1271
1272     token = g_strsplit (value, ";", 0);
1273     for (ptr = token ; *ptr ; ptr++) {
1274       gchar *tmp = NULL;
1275       gchar *op_code = NULL;
1276
1277       if (!strlen (*ptr))
1278         continue;
1279
1280       tmp = g_ascii_strup (*ptr, strlen (*ptr));
1281       if (!strstr (tmp, "DLNA.ORG_OP")) {
1282         g_free (tmp);
1283         continue;
1284       }
1285
1286       g_free (tmp);
1287
1288       op_code = strchr (*ptr, '=');
1289       if (op_code) {
1290         op_code++;
1291
1292         src->dlna_opt = (atoi (op_code) / 10 << 1) | (atoi (op_code) % 10);
1293         GST_DEBUG_OBJECT (src, "dlna op code: %s (0x%X)", op_code, src->dlna_opt);
1294         break;
1295       }
1296     }
1297     g_strfreev (token);
1298   }
1299 #endif
1300
1301   /* Parse Content-Length. */
1302   if (soup_message_headers_get_encoding (msg->response_headers) ==
1303       SOUP_ENCODING_CONTENT_LENGTH) {
1304 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
1305       if (msg->status_code == SOUP_STATUS_PARTIAL_CONTENT) {
1306         newsize = src->request_position +
1307             soup_message_headers_get_content_length (msg->response_headers);
1308       } else {
1309         if (soup_message_headers_get_content_range(msg->response_headers, &start, &stop, &total) && (total > 0)) {
1310           GST_DEBUG_OBJECT (src, "get range header : %" G_GINT64_FORMAT
1311                                   "~%" G_GINT64_FORMAT"/%"G_GINT64_FORMAT, start, stop, total);
1312           newsize = (guint64)total;
1313         } else {
1314           if ((src->have_size) && (src->content_size <= src->request_position)) {
1315             newsize = src->content_size;
1316           } else {
1317             newsize = soup_message_headers_get_content_length (msg->response_headers);
1318           }
1319         }
1320       }
1321 #else
1322       newsize = src->request_position +
1323           soup_message_headers_get_content_length (msg->response_headers);
1324 #endif
1325     if (!src->have_size || (src->content_size != newsize)) {
1326       src->content_size = newsize;
1327       src->have_size = TRUE;
1328       src->seekable = TRUE;
1329       GST_DEBUG_OBJECT (src, "size = %" G_GUINT64_FORMAT, src->content_size);
1330
1331       basesrc = GST_BASE_SRC_CAST (src);
1332       basesrc->segment.duration = src->content_size;
1333       gst_element_post_message (GST_ELEMENT (src),
1334           gst_message_new_duration_changed (GST_OBJECT (src)));
1335     }
1336   }
1337
1338   /* If the server reports Accept-Ranges: none we don't have to try
1339    * doing range requests at all
1340    */
1341   if ((accept_ranges =
1342           soup_message_headers_get_one (msg->response_headers,
1343               "Accept-Ranges"))) {
1344     if (g_ascii_strcasecmp (accept_ranges, "none") == 0)
1345       src->seekable = FALSE;
1346   }
1347 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
1348   else if (src->dlna_opt & DLNA_OP_BYTE_SEEK) {
1349     if (src->have_size) {
1350       GST_DEBUG_OBJECT (src, "DLNA server is seekable");
1351       src->seekable = TRUE;
1352     }
1353   }
1354   /* The Range request header is always included.
1355    * @ref gst_soup_http_src_add_range_header() */
1356   else if ((msg->status_code == SOUP_STATUS_OK) &&
1357     (soup_message_headers_get_content_range (msg->response_headers, &start, &stop, &total) == FALSE)) {
1358     GST_DEBUG_OBJECT (src, "there is no accept range header");
1359     src->seekable = FALSE;
1360   }
1361 #endif
1362
1363   /* Icecast stuff */
1364   tag_list = gst_tag_list_new_empty ();
1365
1366   if ((value =
1367           soup_message_headers_get_one (msg->response_headers,
1368               "icy-metaint")) != NULL) {
1369     gint icy_metaint;
1370
1371     if (g_utf8_validate (value, -1, NULL)) {
1372       icy_metaint = atoi (value);
1373
1374       GST_DEBUG_OBJECT (src, "icy-metaint: %s (parsed: %d)", value,
1375           icy_metaint);
1376       if (icy_metaint > 0) {
1377         if (src->src_caps)
1378           gst_caps_unref (src->src_caps);
1379
1380         src->src_caps = gst_caps_new_simple ("application/x-icy",
1381             "metadata-interval", G_TYPE_INT, icy_metaint, NULL);
1382
1383         gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps);
1384       }
1385     }
1386   }
1387   if ((value =
1388           soup_message_headers_get_content_type (msg->response_headers,
1389               &params)) != NULL) {
1390     if (!g_utf8_validate (value, -1, NULL)) {
1391       GST_WARNING_OBJECT (src, "Content-Type is invalid UTF-8");
1392     } else if (g_ascii_strcasecmp (value, "audio/L16") == 0) {
1393       gint channels = 2;
1394       gint rate = 44100;
1395       char *param;
1396
1397       GST_DEBUG_OBJECT (src, "Content-Type: %s", value);
1398
1399       if (src->src_caps) {
1400         gst_caps_unref (src->src_caps);
1401         src->src_caps = NULL;
1402       }
1403
1404       param = g_hash_table_lookup (params, "channels");
1405       if (param != NULL) {
1406         guint64 val = g_ascii_strtoull (param, NULL, 10);
1407         if (val < 64)
1408           channels = val;
1409         else
1410           channels = 0;
1411       }
1412
1413       param = g_hash_table_lookup (params, "rate");
1414       if (param != NULL) {
1415         guint64 val = g_ascii_strtoull (param, NULL, 10);
1416         if (val < G_MAXINT)
1417           rate = val;
1418         else
1419           rate = 0;
1420       }
1421
1422       if (rate > 0 && channels > 0) {
1423         src->src_caps = gst_caps_new_simple ("audio/x-unaligned-raw",
1424             "format", G_TYPE_STRING, "S16BE",
1425             "layout", G_TYPE_STRING, "interleaved",
1426             "channels", G_TYPE_INT, channels, "rate", G_TYPE_INT, rate, NULL);
1427
1428         gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps);
1429       }
1430     } else {
1431       GST_DEBUG_OBJECT (src, "Content-Type: %s", value);
1432
1433       /* Set the Content-Type field on the caps */
1434       if (src->src_caps) {
1435         src->src_caps = gst_caps_make_writable (src->src_caps);
1436         gst_caps_set_simple (src->src_caps, "content-type", G_TYPE_STRING,
1437             value, NULL);
1438         gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps);
1439       }
1440     }
1441   }
1442
1443   if (params != NULL)
1444     g_hash_table_destroy (params);
1445
1446   if ((value =
1447           soup_message_headers_get_one (msg->response_headers,
1448               "icy-name")) != NULL) {
1449     if (g_utf8_validate (value, -1, NULL)) {
1450       g_free (src->iradio_name);
1451       src->iradio_name = gst_soup_http_src_unicodify (value);
1452       if (src->iradio_name) {
1453         gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_ORGANIZATION,
1454             src->iradio_name, NULL);
1455       }
1456     }
1457   }
1458   if ((value =
1459           soup_message_headers_get_one (msg->response_headers,
1460               "icy-genre")) != NULL) {
1461     if (g_utf8_validate (value, -1, NULL)) {
1462       g_free (src->iradio_genre);
1463       src->iradio_genre = gst_soup_http_src_unicodify (value);
1464       if (src->iradio_genre) {
1465         gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_GENRE,
1466             src->iradio_genre, NULL);
1467       }
1468     }
1469   }
1470   if ((value = soup_message_headers_get_one (msg->response_headers, "icy-url"))
1471       != NULL) {
1472     if (g_utf8_validate (value, -1, NULL)) {
1473       g_free (src->iradio_url);
1474       src->iradio_url = gst_soup_http_src_unicodify (value);
1475       if (src->iradio_url) {
1476         gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_LOCATION,
1477             src->iradio_url, NULL);
1478       }
1479     }
1480   }
1481   if (!gst_tag_list_is_empty (tag_list)) {
1482     GST_DEBUG_OBJECT (src,
1483         "calling gst_element_found_tags with %" GST_PTR_FORMAT, tag_list);
1484     gst_pad_push_event (GST_BASE_SRC_PAD (src), gst_event_new_tag (tag_list));
1485   } else {
1486     gst_tag_list_unref (tag_list);
1487   }
1488
1489   /* Handle HTTP errors. */
1490   return gst_soup_http_src_parse_status (msg, src);
1491 }
1492
1493 static GstBuffer *
1494 gst_soup_http_src_alloc_buffer (GstSoupHTTPSrc * src)
1495 {
1496   GstBaseSrc *basesrc = GST_BASE_SRC_CAST (src);
1497   GstFlowReturn rc;
1498   GstBuffer *gstbuf;
1499
1500   rc = GST_BASE_SRC_CLASS (parent_class)->alloc (basesrc, -1,
1501       basesrc->blocksize, &gstbuf);
1502   if (G_UNLIKELY (rc != GST_FLOW_OK)) {
1503     return NULL;
1504   }
1505
1506   return gstbuf;
1507 }
1508
1509 #define SOUP_HTTP_SRC_ERROR(src,soup_msg,cat,code,error_message)     \
1510   do { \
1511     GST_ELEMENT_ERROR_WITH_DETAILS ((src), cat, code, ("%s", error_message), \
1512         ("%s (%d), URL: %s, Redirect to: %s", (soup_msg)->reason_phrase, \
1513             (soup_msg)->status_code, (src)->location, GST_STR_NULL ((src)->redirection_uri)), \
1514             ("http-status-code", G_TYPE_UINT, (soup_msg)->status_code, \
1515              "http-redirect-uri", G_TYPE_STRING, GST_STR_NULL ((src)->redirection_uri), NULL)); \
1516   } while(0)
1517
1518 static GstFlowReturn
1519 gst_soup_http_src_parse_status (SoupMessage * msg, GstSoupHTTPSrc * src)
1520 {
1521   if (msg->method == SOUP_METHOD_HEAD) {
1522     if (!SOUP_STATUS_IS_SUCCESSFUL (msg->status_code))
1523       GST_DEBUG_OBJECT (src, "Ignoring error %d during HEAD request",
1524           msg->status_code);
1525     return GST_FLOW_OK;
1526   }
1527
1528   if (SOUP_STATUS_IS_TRANSPORT_ERROR (msg->status_code)) {
1529     switch (msg->status_code) {
1530       case SOUP_STATUS_CANT_RESOLVE:
1531       case SOUP_STATUS_CANT_RESOLVE_PROXY:
1532         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, NOT_FOUND,
1533             _("Could not resolve server name."));
1534         return GST_FLOW_ERROR;
1535       case SOUP_STATUS_CANT_CONNECT:
1536       case SOUP_STATUS_CANT_CONNECT_PROXY:
1537         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, OPEN_READ,
1538             _("Could not establish connection to server."));
1539         return GST_FLOW_ERROR;
1540       case SOUP_STATUS_SSL_FAILED:
1541         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, OPEN_READ,
1542             _("Secure connection setup failed."));
1543         return GST_FLOW_ERROR;
1544       case SOUP_STATUS_IO_ERROR:
1545         if (src->max_retries == -1 || src->retry_count < src->max_retries)
1546           return GST_FLOW_CUSTOM_ERROR;
1547         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, READ,
1548             _("A network error occurred, or the server closed the connection "
1549                 "unexpectedly."));
1550         return GST_FLOW_ERROR;
1551       case SOUP_STATUS_MALFORMED:
1552         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, READ,
1553             _("Server sent bad data."));
1554         return GST_FLOW_ERROR;
1555       case SOUP_STATUS_CANCELLED:
1556         /* No error message when interrupted by program. */
1557         break;
1558     }
1559     return GST_FLOW_OK;
1560   }
1561
1562   if (SOUP_STATUS_IS_CLIENT_ERROR (msg->status_code) ||
1563       SOUP_STATUS_IS_REDIRECTION (msg->status_code) ||
1564       SOUP_STATUS_IS_SERVER_ERROR (msg->status_code)) {
1565     const gchar *reason_phrase;
1566
1567     reason_phrase = msg->reason_phrase;
1568     if (reason_phrase && !g_utf8_validate (reason_phrase, -1, NULL)) {
1569       GST_ERROR_OBJECT (src, "Invalid UTF-8 in reason");
1570       reason_phrase = "(invalid)";
1571     }
1572
1573     /* Report HTTP error. */
1574
1575     /* when content_size is unknown and we have just finished receiving
1576      * a body message, requests that go beyond the content limits will result
1577      * in an error. Here we convert those to EOS */
1578 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
1579     if (msg->status_code == SOUP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE &&
1580         ((src->have_body && !src->have_size) ||
1581          (src->have_size && src->request_position >= src->content_size))) {
1582       GST_DEBUG_OBJECT (src, "Requested range out of limits and received full "
1583           "body, returning EOS");
1584       return GST_FLOW_EOS;
1585     }
1586 #else
1587     if (msg->status_code == SOUP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE &&
1588         src->have_body && !src->have_size) {
1589       GST_DEBUG_OBJECT (src, "Requested range out of limits and received full "
1590           "body, returning EOS");
1591       return GST_FLOW_EOS;
1592     }
1593 #endif
1594
1595     /* FIXME: reason_phrase is not translated and not suitable for user
1596      * error dialog according to libsoup documentation.
1597      */
1598     if (msg->status_code == SOUP_STATUS_NOT_FOUND) {
1599       SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, NOT_FOUND, (reason_phrase));
1600     } else if (msg->status_code == SOUP_STATUS_UNAUTHORIZED
1601         || msg->status_code == SOUP_STATUS_PAYMENT_REQUIRED
1602         || msg->status_code == SOUP_STATUS_FORBIDDEN
1603         || msg->status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED) {
1604       SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, NOT_AUTHORIZED, (reason_phrase));
1605     } else {
1606       SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, OPEN_READ, (reason_phrase));
1607     }
1608     return GST_FLOW_ERROR;
1609   }
1610
1611   return GST_FLOW_OK;
1612 }
1613
1614 static void
1615 gst_soup_http_src_restarted_cb (SoupMessage * msg, GstSoupHTTPSrc * src)
1616 {
1617   if (soup_session_would_redirect (src->session, msg)) {
1618     src->redirection_uri =
1619         soup_uri_to_string (soup_message_get_uri (msg), FALSE);
1620     src->redirection_permanent =
1621         (msg->status_code == SOUP_STATUS_MOVED_PERMANENTLY);
1622     GST_DEBUG_OBJECT (src, "%u redirect to \"%s\" (permanent %d)",
1623         msg->status_code, src->redirection_uri, src->redirection_permanent);
1624   }
1625 }
1626
1627 static gboolean
1628 gst_soup_http_src_build_message (GstSoupHTTPSrc * src, const gchar * method)
1629 {
1630   g_return_val_if_fail (src->msg == NULL, FALSE);
1631
1632   src->msg = soup_message_new (method, src->location);
1633   if (!src->msg) {
1634     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
1635         ("Error parsing URL."), ("URL: %s", src->location));
1636     return FALSE;
1637   }
1638   if (!src->keep_alive) {
1639     soup_message_headers_append (src->msg->request_headers, "Connection",
1640         "close");
1641   }
1642   if (src->iradio_mode) {
1643     soup_message_headers_append (src->msg->request_headers, "icy-metadata",
1644         "1");
1645   }
1646
1647 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
1648 /* This changes are needed to enable Seekable Contents from server.
1649    We have observed that , for few specific networks ( VODAFONE ) , without theabove headers ,
1650    Youtube is sending non-seekable contents to the Client. */
1651   soup_message_headers_append (src->msg->request_headers, "Accept-Ranges","bytes");
1652
1653   if (src->cookie_jar) {
1654     GSList *cookie_list, *c;
1655     gchar *header;
1656
1657     SoupURI *uri = NULL;
1658     SoupCookie *cookie;
1659     uri = soup_uri_new (src->location);
1660
1661     if ((cookie_list = soup_cookie_jar_all_cookies (src->cookie_jar)) != NULL) {
1662       for (c = cookie_list; c; c = c->next) {
1663         cookie = (SoupCookie *)c->data;
1664         if (soup_cookie_applies_to_uri(cookie, uri)) {
1665           header = soup_cookie_to_cookie_header (cookie);
1666           soup_message_headers_append (src->msg->request_headers, "Cookie", header);
1667           g_free (header);
1668         }
1669       }
1670     }
1671     soup_cookies_free (cookie_list);
1672     soup_uri_free (uri);
1673   }
1674 #else
1675   if (src->cookies) {
1676     gchar **cookie;
1677
1678     for (cookie = src->cookies; *cookie != NULL; cookie++) {
1679       soup_message_headers_append (src->msg->request_headers, "Cookie",
1680           *cookie);
1681     }
1682   }
1683 #endif
1684
1685   soup_message_set_flags (src->msg, SOUP_MESSAGE_OVERWRITE_CHUNKS |
1686       (src->automatic_redirect ? 0 : SOUP_MESSAGE_NO_REDIRECT));
1687
1688   if (src->automatic_redirect) {
1689     g_signal_connect (src->msg, "restarted",
1690         G_CALLBACK (gst_soup_http_src_restarted_cb), src);
1691   }
1692
1693   gst_soup_http_src_add_range_header (src, src->request_position,
1694       src->stop_position);
1695
1696   gst_soup_http_src_add_extra_headers (src);
1697
1698 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
1699   soup_message_headers_foreach (src->msg->request_headers,
1700       gst_soup_http_src_headers_foreach, src);
1701 #endif
1702
1703   return TRUE;
1704 }
1705
1706 static GstFlowReturn
1707 gst_soup_http_src_send_message (GstSoupHTTPSrc * src)
1708 {
1709   GstFlowReturn ret;
1710   GError *error = NULL;
1711
1712   g_return_val_if_fail (src->msg != NULL, GST_FLOW_ERROR);
1713
1714   src->input_stream =
1715       soup_session_send (src->session, src->msg, src->cancellable, &error);
1716
1717   if (g_cancellable_is_cancelled (src->cancellable)) {
1718     ret = GST_FLOW_FLUSHING;
1719     goto done;
1720   }
1721
1722   ret = gst_soup_http_src_got_headers (src, src->msg);
1723   if (ret != GST_FLOW_OK) {
1724     goto done;
1725   }
1726
1727   if (!src->input_stream) {
1728     GST_DEBUG_OBJECT (src, "Didn't get an input stream: %s", error->message);
1729     ret = GST_FLOW_ERROR;
1730     goto done;
1731   }
1732
1733   if (SOUP_STATUS_IS_SUCCESSFUL (src->msg->status_code)) {
1734     GST_DEBUG_OBJECT (src, "Successfully got a reply");
1735   } else {
1736     /* FIXME - be more helpful to people debugging */
1737     ret = GST_FLOW_ERROR;
1738   }
1739
1740 done:
1741   if (error)
1742     g_error_free (error);
1743   return ret;
1744 }
1745
1746 static GstFlowReturn
1747 gst_soup_http_src_do_request (GstSoupHTTPSrc * src, const gchar * method)
1748 {
1749   GstFlowReturn ret;
1750
1751   if (src->max_retries != -1 && src->retry_count > src->max_retries) {
1752     GST_DEBUG_OBJECT (src, "Max retries reached");
1753     return GST_FLOW_ERROR;
1754   }
1755
1756   src->retry_count++;
1757   /* EOS immediately if we have an empty segment */
1758   if (src->request_position == src->stop_position)
1759     return GST_FLOW_EOS;
1760
1761   GST_LOG_OBJECT (src, "Running request for method: %s", method);
1762
1763   /* Update the position if we are retrying */
1764   if (src->msg && src->request_position > 0) {
1765     gst_soup_http_src_add_range_header (src, src->request_position,
1766         src->stop_position);
1767   }
1768
1769   if (!src->msg) {
1770     if (!gst_soup_http_src_build_message (src, method)) {
1771       return GST_FLOW_ERROR;
1772     }
1773   }
1774
1775   if (g_cancellable_is_cancelled (src->cancellable)) {
1776     GST_INFO_OBJECT (src, "interrupted");
1777     return GST_FLOW_FLUSHING;
1778   }
1779
1780   ret = gst_soup_http_src_send_message (src);
1781
1782   /* Check if Range header was respected. */
1783 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
1784   if (ret == GST_FLOW_OK && src->request_position > 0 &&
1785       (src->msg->status_code != SOUP_STATUS_PARTIAL_CONTENT) &&
1786           (src->request_position < src->content_size)) {
1787 #else
1788   if (ret == GST_FLOW_OK && src->request_position > 0 &&
1789       src->msg->status_code != SOUP_STATUS_PARTIAL_CONTENT) {
1790 #endif
1791     src->seekable = FALSE;
1792     GST_ELEMENT_ERROR_WITH_DETAILS (src, RESOURCE, SEEK,
1793         (_("Server does not support seeking.")),
1794         ("Server does not accept Range HTTP header, URL: %s, Redirect to: %s",
1795             src->location, GST_STR_NULL (src->redirection_uri)),
1796         ("http-status-code", G_TYPE_UINT, src->msg->status_code,
1797             "http-redirection-uri", G_TYPE_STRING,
1798             GST_STR_NULL (src->redirection_uri), NULL));
1799     ret = GST_FLOW_ERROR;
1800   }
1801
1802   return ret;
1803 }
1804
1805 /*
1806  * Check if the bytes_read is above a certain threshold of the blocksize, if
1807  * that happens a few times in a row, increase the blocksize; Do the same in
1808  * the opposite direction to reduce the blocksize.
1809  */
1810 static void
1811 gst_soup_http_src_check_update_blocksize (GstSoupHTTPSrc * src,
1812     gint64 bytes_read)
1813 {
1814   guint blocksize = gst_base_src_get_blocksize (GST_BASE_SRC_CAST (src));
1815
1816   GST_LOG_OBJECT (src, "Checking to update blocksize. Read:%" G_GINT64_FORMAT
1817       " blocksize:%u", bytes_read, blocksize);
1818
1819   if (bytes_read >= blocksize * GROW_BLOCKSIZE_LIMIT) {
1820     src->reduce_blocksize_count = 0;
1821     src->increase_blocksize_count++;
1822
1823     if (src->increase_blocksize_count >= GROW_BLOCKSIZE_COUNT) {
1824       blocksize *= GROW_BLOCKSIZE_FACTOR;
1825       GST_DEBUG_OBJECT (src, "Increased blocksize to %u", blocksize);
1826       gst_base_src_set_blocksize (GST_BASE_SRC_CAST (src), blocksize);
1827       src->increase_blocksize_count = 0;
1828     }
1829   } else if (bytes_read < blocksize * REDUCE_BLOCKSIZE_LIMIT) {
1830     src->reduce_blocksize_count++;
1831     src->increase_blocksize_count = 0;
1832
1833     if (src->reduce_blocksize_count >= REDUCE_BLOCKSIZE_COUNT) {
1834       blocksize *= REDUCE_BLOCKSIZE_FACTOR;
1835       blocksize = MAX (blocksize, src->minimum_blocksize);
1836       GST_DEBUG_OBJECT (src, "Decreased blocksize to %u", blocksize);
1837       gst_base_src_set_blocksize (GST_BASE_SRC_CAST (src), blocksize);
1838       src->reduce_blocksize_count = 0;
1839     }
1840   } else {
1841     src->reduce_blocksize_count = src->increase_blocksize_count = 0;
1842   }
1843 }
1844
1845 static void
1846 gst_soup_http_src_update_position (GstSoupHTTPSrc * src, gint64 bytes_read)
1847 {
1848   GstBaseSrc *basesrc = GST_BASE_SRC_CAST (src);
1849   guint64 new_position;
1850
1851   new_position = src->read_position + bytes_read;
1852   if (G_LIKELY (src->request_position == src->read_position))
1853     src->request_position = new_position;
1854   src->read_position = new_position;
1855
1856   if (src->have_size) {
1857     if (new_position > src->content_size) {
1858       GST_DEBUG_OBJECT (src, "Got position previous estimated content size "
1859           "(%" G_GINT64_FORMAT " > %" G_GINT64_FORMAT ")", new_position,
1860           src->content_size);
1861       src->content_size = new_position;
1862       basesrc->segment.duration = src->content_size;
1863       gst_element_post_message (GST_ELEMENT (src),
1864           gst_message_new_duration_changed (GST_OBJECT (src)));
1865     } else if (new_position == src->content_size) {
1866       GST_DEBUG_OBJECT (src, "We're EOS now");
1867     }
1868   }
1869 }
1870
1871 static GstFlowReturn
1872 gst_soup_http_src_read_buffer (GstSoupHTTPSrc * src, GstBuffer ** outbuf)
1873 {
1874   gssize read_bytes;
1875   GstMapInfo mapinfo;
1876   GstBaseSrc *bsrc;
1877   GstFlowReturn ret;
1878
1879   bsrc = GST_BASE_SRC_CAST (src);
1880
1881   *outbuf = gst_soup_http_src_alloc_buffer (src);
1882   if (!*outbuf) {
1883     GST_WARNING_OBJECT (src, "Failed to allocate buffer");
1884     return GST_FLOW_ERROR;
1885   }
1886
1887   if (!gst_buffer_map (*outbuf, &mapinfo, GST_MAP_WRITE)) {
1888     GST_WARNING_OBJECT (src, "Failed to map buffer");
1889     return GST_FLOW_ERROR;
1890   }
1891
1892   read_bytes =
1893       g_input_stream_read (src->input_stream, mapinfo.data, mapinfo.size,
1894       src->cancellable, NULL);
1895   GST_DEBUG_OBJECT (src, "Read %" G_GSSIZE_FORMAT " bytes from http input",
1896       read_bytes);
1897
1898   g_mutex_lock (&src->mutex);
1899   if (g_cancellable_is_cancelled (src->cancellable)) {
1900     gst_buffer_unmap (*outbuf, &mapinfo);
1901     gst_buffer_unref (*outbuf);
1902     g_mutex_unlock (&src->mutex);
1903     return GST_FLOW_FLUSHING;
1904   }
1905
1906   gst_buffer_unmap (*outbuf, &mapinfo);
1907   if (read_bytes > 0) {
1908     gst_buffer_set_size (*outbuf, read_bytes);
1909     GST_BUFFER_OFFSET (*outbuf) = bsrc->segment.position;
1910     ret = GST_FLOW_OK;
1911     gst_soup_http_src_update_position (src, read_bytes);
1912 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
1913     src->received_total += read_bytes;
1914 #endif
1915
1916     /* Got some data, reset retry counter */
1917     src->retry_count = 0;
1918
1919     gst_soup_http_src_check_update_blocksize (src, read_bytes);
1920
1921     /* If we're at the end of a range request, read again to let libsoup
1922      * finalize the request. This allows to reuse the connection again later,
1923      * otherwise we would have to cancel the message and close the connection
1924      */
1925     if (bsrc->segment.stop != -1
1926         && bsrc->segment.position + read_bytes >= bsrc->segment.stop) {
1927       guint8 tmp[128];
1928
1929       g_object_unref (src->msg);
1930       src->msg = NULL;
1931       src->have_body = TRUE;
1932
1933       /* This should return immediately as we're at the end of the range */
1934       read_bytes =
1935           g_input_stream_read (src->input_stream, tmp, sizeof (tmp),
1936           src->cancellable, NULL);
1937       if (read_bytes > 0)
1938         GST_ERROR_OBJECT (src,
1939             "Read %" G_GSIZE_FORMAT " bytes after end of range", read_bytes);
1940     }
1941   } else {
1942     gst_buffer_unref (*outbuf);
1943     if (read_bytes < 0 ||
1944         (src->have_size && src->read_position < src->content_size)) {
1945       /* Maybe the server disconnected, retry */
1946       ret = GST_FLOW_CUSTOM_ERROR;
1947     } else {
1948       g_object_unref (src->msg);
1949       src->msg = NULL;
1950       ret = GST_FLOW_EOS;
1951       src->have_body = TRUE;
1952     }
1953   }
1954   g_mutex_unlock (&src->mutex);
1955
1956   return ret;
1957 }
1958
1959 static GstFlowReturn
1960 gst_soup_http_src_create (GstPushSrc * psrc, GstBuffer ** outbuf)
1961 {
1962   GstSoupHTTPSrc *src;
1963   GstFlowReturn ret = GST_FLOW_OK;
1964   GstEvent *http_headers_event = NULL;
1965
1966   src = GST_SOUP_HTTP_SRC (psrc);
1967
1968 retry:
1969   g_mutex_lock (&src->mutex);
1970
1971   /* Check for pending position change */
1972   if (src->request_position != src->read_position) {
1973     if (src->input_stream) {
1974       g_input_stream_close (src->input_stream, src->cancellable, NULL);
1975       g_object_unref (src->input_stream);
1976       src->input_stream = NULL;
1977     }
1978   }
1979
1980   if (g_cancellable_is_cancelled (src->cancellable)) {
1981     ret = GST_FLOW_FLUSHING;
1982     g_mutex_unlock (&src->mutex);
1983     goto done;
1984   }
1985
1986   /* If we have no open connection to the server, start one */
1987   if (!src->input_stream) {
1988     *outbuf = NULL;
1989     ret =
1990         gst_soup_http_src_do_request (src,
1991         src->method ? src->method : SOUP_METHOD_GET);
1992     http_headers_event = src->http_headers_event;
1993     src->http_headers_event = NULL;
1994   }
1995   g_mutex_unlock (&src->mutex);
1996
1997   if (ret == GST_FLOW_OK || ret == GST_FLOW_CUSTOM_ERROR) {
1998     if (http_headers_event) {
1999       gst_pad_push_event (GST_BASE_SRC_PAD (src), http_headers_event);
2000       http_headers_event = NULL;
2001     }
2002   }
2003
2004   if (ret == GST_FLOW_OK)
2005     ret = gst_soup_http_src_read_buffer (src, outbuf);
2006
2007 done:
2008   GST_DEBUG_OBJECT (src, "Returning %d %s", ret, gst_flow_get_name (ret));
2009   if (ret != GST_FLOW_OK) {
2010     if (http_headers_event)
2011       gst_event_unref (http_headers_event);
2012
2013     g_mutex_lock (&src->mutex);
2014     if (src->input_stream) {
2015       g_object_unref (src->input_stream);
2016       src->input_stream = NULL;
2017     }
2018     g_mutex_unlock (&src->mutex);
2019     if (ret == GST_FLOW_CUSTOM_ERROR) {
2020       ret = GST_FLOW_OK;
2021       goto retry;
2022     }
2023   }
2024   return ret;
2025 }
2026
2027 static gboolean
2028 gst_soup_http_src_start (GstBaseSrc * bsrc)
2029 {
2030   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
2031
2032   GST_DEBUG_OBJECT (src, "start(\"%s\")", src->location);
2033
2034 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
2035   if (src->dash_oldest_segment) {
2036     g_free (src->dash_oldest_segment);
2037     src->dash_oldest_segment = NULL;
2038   }
2039   if (src->dash_newest_segment) {
2040     g_free (src->dash_newest_segment);
2041     src->dash_newest_segment = NULL;
2042   }
2043 #endif
2044   return gst_soup_http_src_session_open (src);
2045 }
2046
2047 static gboolean
2048 gst_soup_http_src_stop (GstBaseSrc * bsrc)
2049 {
2050   GstSoupHTTPSrc *src;
2051
2052   src = GST_SOUP_HTTP_SRC (bsrc);
2053   GST_DEBUG_OBJECT (src, "stop()");
2054   if (src->keep_alive && !src->msg)
2055     gst_soup_http_src_cancel_message (src);
2056   else
2057     gst_soup_http_src_session_close (src);
2058
2059   gst_soup_http_src_reset (src);
2060   return TRUE;
2061 }
2062
2063 static GstStateChangeReturn
2064 gst_soup_http_src_change_state (GstElement * element, GstStateChange transition)
2065 {
2066   GstStateChangeReturn ret;
2067   GstSoupHTTPSrc *src;
2068
2069   src = GST_SOUP_HTTP_SRC (element);
2070
2071   switch (transition) {
2072 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
2073     case GST_STATE_CHANGE_PAUSED_TO_READY:
2074       GST_WARNING_OBJECT (src, "Last read pos"
2075             ": %" G_GINT64_FORMAT ", received total : %" G_GINT64_FORMAT,
2076             src->read_position, src->received_total);
2077       break;
2078 #endif
2079     case GST_STATE_CHANGE_READY_TO_NULL:
2080       gst_soup_http_src_session_close (src);
2081       break;
2082     default:
2083       break;
2084   }
2085
2086   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2087
2088   return ret;
2089 }
2090
2091 /* Interrupt a blocking request. */
2092 static gboolean
2093 gst_soup_http_src_unlock (GstBaseSrc * bsrc)
2094 {
2095   GstSoupHTTPSrc *src;
2096
2097   src = GST_SOUP_HTTP_SRC (bsrc);
2098   GST_DEBUG_OBJECT (src, "unlock()");
2099
2100   gst_soup_http_src_cancel_message (src);
2101   return TRUE;
2102 }
2103
2104 /* Interrupt interrupt. */
2105 static gboolean
2106 gst_soup_http_src_unlock_stop (GstBaseSrc * bsrc)
2107 {
2108   GstSoupHTTPSrc *src;
2109
2110   src = GST_SOUP_HTTP_SRC (bsrc);
2111   GST_DEBUG_OBJECT (src, "unlock_stop()");
2112
2113   g_cancellable_reset (src->cancellable);
2114   return TRUE;
2115 }
2116
2117 static gboolean
2118 gst_soup_http_src_get_size (GstBaseSrc * bsrc, guint64 * size)
2119 {
2120   GstSoupHTTPSrc *src;
2121
2122   src = GST_SOUP_HTTP_SRC (bsrc);
2123
2124   if (src->have_size) {
2125     GST_DEBUG_OBJECT (src, "get_size() = %" G_GUINT64_FORMAT,
2126         src->content_size);
2127     *size = src->content_size;
2128     return TRUE;
2129   }
2130   GST_DEBUG_OBJECT (src, "get_size() = FALSE");
2131   return FALSE;
2132 }
2133
2134 static void
2135 gst_soup_http_src_check_seekable (GstSoupHTTPSrc * src)
2136 {
2137   GstFlowReturn ret = GST_FLOW_OK;
2138
2139   /* Special case to check if the server allows range requests
2140    * before really starting to get data in the buffer creation
2141    * loops.
2142    */
2143   if (!src->got_headers && GST_STATE (src) >= GST_STATE_PAUSED) {
2144     g_mutex_lock (&src->mutex);
2145     while (!src->got_headers && !g_cancellable_is_cancelled (src->cancellable)
2146         && ret == GST_FLOW_OK) {
2147       if ((src->msg && src->msg->method != SOUP_METHOD_HEAD)) {
2148         /* wait for the current request to finish */
2149         g_cond_wait (&src->have_headers_cond, &src->mutex);
2150       } else {
2151         if (gst_soup_http_src_session_open (src)) {
2152           ret = gst_soup_http_src_do_request (src, SOUP_METHOD_HEAD);
2153         }
2154       }
2155     }
2156     g_mutex_unlock (&src->mutex);
2157   }
2158 }
2159
2160 static gboolean
2161 gst_soup_http_src_is_seekable (GstBaseSrc * bsrc)
2162 {
2163   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
2164
2165   gst_soup_http_src_check_seekable (src);
2166
2167   return src->seekable;
2168 }
2169
2170 static gboolean
2171 gst_soup_http_src_do_seek (GstBaseSrc * bsrc, GstSegment * segment)
2172 {
2173   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
2174
2175   GST_DEBUG_OBJECT (src, "do_seek(%" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT
2176       ")", segment->start, segment->stop);
2177   if (src->read_position == segment->start &&
2178       src->request_position == src->read_position &&
2179       src->stop_position == segment->stop) {
2180     GST_DEBUG_OBJECT (src,
2181         "Seek to current read/end position and no seek pending");
2182     return TRUE;
2183   }
2184
2185   gst_soup_http_src_check_seekable (src);
2186
2187   /* If we have no headers we don't know yet if it is seekable or not.
2188    * Store the start position and error out later if it isn't */
2189   if (src->got_headers && !src->seekable) {
2190     GST_WARNING_OBJECT (src, "Not seekable");
2191     return FALSE;
2192   }
2193
2194   if (segment->rate < 0.0 || segment->format != GST_FORMAT_BYTES) {
2195     GST_WARNING_OBJECT (src, "Invalid seek segment");
2196     return FALSE;
2197   }
2198
2199   if (src->have_size && segment->start >= src->content_size) {
2200     GST_WARNING_OBJECT (src,
2201         "Potentially seeking behind end of file, might EOS immediately");
2202   }
2203
2204   /* Wait for create() to handle the jump in offset. */
2205   src->request_position = segment->start;
2206   src->stop_position = segment->stop;
2207
2208   return TRUE;
2209 }
2210
2211 static gboolean
2212 gst_soup_http_src_query (GstBaseSrc * bsrc, GstQuery * query)
2213 {
2214   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
2215   gboolean ret;
2216   GstSchedulingFlags flags;
2217   gint minsize, maxsize, align;
2218
2219   switch (GST_QUERY_TYPE (query)) {
2220     case GST_QUERY_URI:
2221       gst_query_set_uri (query, src->location);
2222       if (src->redirection_uri != NULL) {
2223         gst_query_set_uri_redirection (query, src->redirection_uri);
2224         gst_query_set_uri_redirection_permanent (query,
2225             src->redirection_permanent);
2226       }
2227       ret = TRUE;
2228       break;
2229     default:
2230       ret = FALSE;
2231       break;
2232   }
2233
2234   if (!ret)
2235     ret = GST_BASE_SRC_CLASS (parent_class)->query (bsrc, query);
2236
2237   switch (GST_QUERY_TYPE (query)) {
2238     case GST_QUERY_SCHEDULING:
2239
2240       gst_query_parse_scheduling (query, &flags, &minsize, &maxsize, &align);
2241       flags |= GST_SCHEDULING_FLAG_BANDWIDTH_LIMITED;
2242
2243 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
2244       if (gst_soup_http_src_is_seekable(bsrc)) {
2245           GST_DEBUG_OBJECT (src, "set seekable flag");
2246           flags |= GST_SCHEDULING_FLAG_SEEKABLE;
2247       }
2248 #endif
2249       gst_query_set_scheduling (query, flags, minsize, maxsize, align);
2250
2251       break;
2252     default:
2253       break;
2254   }
2255
2256   return ret;
2257 }
2258
2259 static gboolean
2260 gst_soup_http_src_set_location (GstSoupHTTPSrc * src, const gchar * uri,
2261     GError ** error)
2262 {
2263   const char *alt_schemes[] = { "icy://", "icyx://" };
2264   guint i;
2265
2266   if (src->location) {
2267     g_free (src->location);
2268     src->location = NULL;
2269   }
2270
2271   if (uri == NULL)
2272     return FALSE;
2273
2274   for (i = 0; i < G_N_ELEMENTS (alt_schemes); i++) {
2275     if (g_str_has_prefix (uri, alt_schemes[i])) {
2276       src->location =
2277           g_strdup_printf ("http://%s", uri + strlen (alt_schemes[i]));
2278       return TRUE;
2279     }
2280   }
2281
2282   if (src->redirection_uri) {
2283     g_free (src->redirection_uri);
2284     src->redirection_uri = NULL;
2285   }
2286
2287   src->location = g_strdup (uri);
2288
2289   return TRUE;
2290 }
2291
2292 static gboolean
2293 gst_soup_http_src_set_proxy (GstSoupHTTPSrc * src, const gchar * uri)
2294 {
2295   if (src->proxy) {
2296     soup_uri_free (src->proxy);
2297     src->proxy = NULL;
2298   }
2299
2300   if (uri == NULL || *uri == '\0')
2301     return TRUE;
2302
2303   if (g_str_has_prefix (uri, "http://")) {
2304     src->proxy = soup_uri_new (uri);
2305   } else {
2306     gchar *new_uri = g_strconcat ("http://", uri, NULL);
2307
2308     src->proxy = soup_uri_new (new_uri);
2309     g_free (new_uri);
2310   }
2311
2312   return (src->proxy != NULL);
2313 }
2314
2315 static guint
2316 gst_soup_http_src_uri_get_type (GType type)
2317 {
2318   return GST_URI_SRC;
2319 }
2320
2321 static const gchar *const *
2322 gst_soup_http_src_uri_get_protocols (GType type)
2323 {
2324   static const gchar *protocols[] = { "http", "https", "icy", "icyx", NULL };
2325
2326   return protocols;
2327 }
2328
2329 static gchar *
2330 gst_soup_http_src_uri_get_uri (GstURIHandler * handler)
2331 {
2332   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (handler);
2333
2334   /* FIXME: make thread-safe */
2335   return g_strdup (src->location);
2336 }
2337
2338 static gboolean
2339 gst_soup_http_src_uri_set_uri (GstURIHandler * handler, const gchar * uri,
2340     GError ** error)
2341 {
2342   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (handler);
2343
2344   return gst_soup_http_src_set_location (src, uri, error);
2345 }
2346
2347 static void
2348 gst_soup_http_src_uri_handler_init (gpointer g_iface, gpointer iface_data)
2349 {
2350   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
2351
2352   iface->get_type = gst_soup_http_src_uri_get_type;
2353   iface->get_protocols = gst_soup_http_src_uri_get_protocols;
2354   iface->get_uri = gst_soup_http_src_uri_get_uri;
2355   iface->set_uri = gst_soup_http_src_uri_set_uri;
2356 }