Add -Wold-style-definition
[platform/upstream/gstreamer.git] / ext / neon / gstneonhttpsrc.c
1 /* GStreamer
2  * Copyright (C) <2005> Edgard Lima <edgard.lima@indt.org.br>
3  * Copyright (C) <2006> Rosfran Borges <rosfran.borges@indt.org.br>
4  * Copyright (C) <2006> Andre Moreira Magalhaes <andre.magalhaes@indt.org.br>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more 
15  */
16
17 #ifdef HAVE_CONFIG_H
18 #include "config.h"
19 #endif
20
21 #include "gstneonhttpsrc.h"
22 #include <stdlib.h>
23 #include <string.h>
24 #ifdef _HAVE_UNISTD_H
25 #include <unistd.h>
26 #endif /* _HAVE_UNISTD_H */
27
28 #include <ne_redirect.h>
29
30 #define STATUS_IS_REDIRECTION(status)     ((status) >= 300 && (status) < 400)
31
32 GST_DEBUG_CATEGORY_STATIC (neonhttpsrc_debug);
33 #define GST_CAT_DEFAULT neonhttpsrc_debug
34
35 #define MAX_READ_SIZE (4 * 1024)
36
37 /* max number of HTTP redirects, when iterating over a sequence of HTTP 3xx status code */
38 #define MAX_HTTP_REDIRECTS_NUMBER 5
39
40 static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src",
41     GST_PAD_SRC,
42     GST_PAD_ALWAYS,
43     GST_STATIC_CAPS_ANY);
44
45 #define HTTP_SOCKET_ERROR        -2
46 #define HTTP_REQUEST_WRONG_PROXY -1
47 #define HTTP_DEFAULT_PORT        80
48 #define HTTPS_DEFAULT_PORT       443
49 #define HTTP_DEFAULT_HOST        "localhost"
50
51 /* default properties */
52 #define DEFAULT_LOCATION             "http://"HTTP_DEFAULT_HOST":"G_STRINGIFY(HTTP_DEFAULT_PORT)
53 #define DEFAULT_PROXY                ""
54 #define DEFAULT_USER_AGENT           "GStreamer neonhttpsrc"
55 #define DEFAULT_IRADIO_MODE          FALSE
56 #define DEFAULT_IRADIO_NAME          NULL
57 #define DEFAULT_IRADIO_GENRE         NULL
58 #define DEFAULT_IRADIO_URL           NULL
59 #define DEFAULT_AUTOMATIC_REDIRECT   TRUE
60 #define DEFAULT_ACCEPT_SELF_SIGNED   FALSE
61 #define DEFAULT_NEON_HTTP_DEBUG      FALSE
62
63 enum
64 {
65   PROP_0,
66   PROP_LOCATION,
67   PROP_PROXY,
68   PROP_USER_AGENT,
69   PROP_IRADIO_MODE,
70   PROP_IRADIO_NAME,
71   PROP_IRADIO_GENRE,
72   PROP_IRADIO_URL,
73   PROP_AUTOMATIC_REDIRECT,
74   PROP_ACCEPT_SELF_SIGNED,
75 #ifndef GST_DISABLE_GST_DEBUG
76   PROP_NEON_HTTP_DEBUG
77 #endif
78 };
79
80 static void gst_neonhttp_src_uri_handler_init (gpointer g_iface,
81     gpointer iface_data);
82 static void gst_neonhttp_src_dispose (GObject * gobject);
83 static void gst_neonhttp_src_set_property (GObject * object, guint prop_id,
84     const GValue * value, GParamSpec * pspec);
85 static void gst_neonhttp_src_get_property (GObject * object, guint prop_id,
86     GValue * value, GParamSpec * pspec);
87
88 static GstFlowReturn gst_neonhttp_src_create (GstPushSrc * psrc,
89     GstBuffer ** outbuf);
90 static gboolean gst_neonhttp_src_start (GstBaseSrc * bsrc);
91 static gboolean gst_neonhttp_src_stop (GstBaseSrc * bsrc);
92 static gboolean gst_neonhttp_src_get_size (GstBaseSrc * bsrc, guint64 * size);
93 static gboolean gst_neonhttp_src_is_seekable (GstBaseSrc * bsrc);
94 static gboolean gst_neonhttp_src_do_seek (GstBaseSrc * bsrc,
95     GstSegment * segment);
96
97 static gboolean gst_neonhttp_src_set_proxy (GstNeonhttpSrc * src,
98     const gchar * uri);
99 static gboolean gst_neonhttp_src_set_location (GstNeonhttpSrc * src,
100     const gchar * uri);
101 static gint gst_neonhttp_src_send_request_and_redirect (GstNeonhttpSrc * src,
102     ne_session ** ses, ne_request ** req, gint64 offset, gboolean do_redir);
103 static gint gst_neonhttp_src_request_dispatch (GstNeonhttpSrc * src,
104     GstBuffer * outbuf);
105 static void gst_neonhttp_src_close_session (GstNeonhttpSrc * src);
106 static gchar *gst_neonhttp_src_unicodify (const gchar * str);
107 static void oom_callback (void);
108
109 static void
110 _urihandler_init (GType type)
111 {
112   static const GInterfaceInfo urihandler_info = {
113     gst_neonhttp_src_uri_handler_init,
114     NULL,
115     NULL
116   };
117
118   g_type_add_interface_static (type, GST_TYPE_URI_HANDLER, &urihandler_info);
119
120   GST_DEBUG_CATEGORY_INIT (neonhttpsrc_debug, "neonhttpsrc", 0,
121       "NEON HTTP src");
122 }
123
124 GST_BOILERPLATE_FULL (GstNeonhttpSrc, gst_neonhttp_src, GstPushSrc,
125     GST_TYPE_PUSH_SRC, _urihandler_init);
126
127 static void
128 gst_neonhttp_src_base_init (gpointer g_class)
129 {
130   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
131
132   gst_element_class_add_pad_template (element_class,
133       gst_static_pad_template_get (&srctemplate));
134
135   gst_element_class_set_details_simple (element_class, "HTTP client source",
136       "Source/Network",
137       "Receive data as a client over the network via HTTP using NEON",
138       "Edgard Lima <edgard.lima@indt.org.br>, "
139       "Rosfran Borges <rosfran.borges@indt.org.br>, "
140       "Andre Moreira Magalhaes <andre.magalhaes@indt.org.br>");
141 }
142
143 static void
144 gst_neonhttp_src_class_init (GstNeonhttpSrcClass * klass)
145 {
146   GObjectClass *gobject_class;
147   GstBaseSrcClass *gstbasesrc_class;
148   GstPushSrcClass *gstpushsrc_class;
149
150   gobject_class = (GObjectClass *) klass;
151   gstbasesrc_class = (GstBaseSrcClass *) klass;
152   gstpushsrc_class = (GstPushSrcClass *) klass;
153
154   gobject_class->set_property = gst_neonhttp_src_set_property;
155   gobject_class->get_property = gst_neonhttp_src_get_property;
156   gobject_class->dispose = gst_neonhttp_src_dispose;
157
158   g_object_class_install_property
159       (gobject_class, PROP_LOCATION,
160       g_param_spec_string ("location", "Location",
161           "Location to read from", "", G_PARAM_READWRITE));
162
163   g_object_class_install_property
164       (gobject_class, PROP_PROXY,
165       g_param_spec_string ("proxy", "Proxy",
166           "Proxy server to use, in the form HOSTNAME:PORT. "
167           "Defaults to the http_proxy environment variable",
168           "", G_PARAM_READWRITE));
169
170   g_object_class_install_property
171       (gobject_class, PROP_USER_AGENT,
172       g_param_spec_string ("user-agent", "User-Agent",
173           "Value of the User-Agent HTTP request header field",
174           "GStreamer neonhttpsrc", G_PARAM_READWRITE));
175
176   g_object_class_install_property
177       (gobject_class, PROP_IRADIO_MODE,
178       g_param_spec_boolean ("iradio-mode", "iradio-mode",
179           "Enable internet radio mode (extraction of shoutcast/icecast metadata)",
180           FALSE, G_PARAM_READWRITE));
181
182   g_object_class_install_property (gobject_class,
183       PROP_IRADIO_NAME,
184       g_param_spec_string ("iradio-name",
185           "iradio-name", "Name of the stream", NULL, G_PARAM_READABLE));
186
187   g_object_class_install_property (gobject_class,
188       PROP_IRADIO_GENRE,
189       g_param_spec_string ("iradio-genre",
190           "iradio-genre", "Genre of the stream", NULL, G_PARAM_READABLE));
191
192   g_object_class_install_property (gobject_class,
193       PROP_IRADIO_URL,
194       g_param_spec_string ("iradio-url",
195           "iradio-url",
196           "Homepage URL for radio stream", NULL, G_PARAM_READABLE));
197
198   g_object_class_install_property
199       (gobject_class, PROP_AUTOMATIC_REDIRECT,
200       g_param_spec_boolean ("automatic-redirect", "automatic-redirect",
201           "Automatically follow HTTP redirects (HTTP Status Code 3xx)",
202           TRUE, G_PARAM_READWRITE));
203
204   g_object_class_install_property
205       (gobject_class, PROP_ACCEPT_SELF_SIGNED,
206       g_param_spec_boolean ("accept-self-signed", "accept-self-signed",
207           "Accept self-signed SSL/TLS certificates",
208           DEFAULT_ACCEPT_SELF_SIGNED, G_PARAM_READWRITE));
209
210 #ifndef GST_DISABLE_GST_DEBUG
211   g_object_class_install_property
212       (gobject_class, PROP_NEON_HTTP_DEBUG,
213       g_param_spec_boolean ("neon-http-debug", "neon-http-debug",
214           "Enable Neon HTTP debug messages",
215           DEFAULT_NEON_HTTP_DEBUG, G_PARAM_READWRITE));
216 #endif
217
218   gstbasesrc_class->start = GST_DEBUG_FUNCPTR (gst_neonhttp_src_start);
219   gstbasesrc_class->stop = GST_DEBUG_FUNCPTR (gst_neonhttp_src_stop);
220   gstbasesrc_class->get_size = GST_DEBUG_FUNCPTR (gst_neonhttp_src_get_size);
221   gstbasesrc_class->is_seekable =
222       GST_DEBUG_FUNCPTR (gst_neonhttp_src_is_seekable);
223   gstbasesrc_class->do_seek = GST_DEBUG_FUNCPTR (gst_neonhttp_src_do_seek);
224
225   gstpushsrc_class->create = GST_DEBUG_FUNCPTR (gst_neonhttp_src_create);
226
227   GST_DEBUG_CATEGORY_INIT (neonhttpsrc_debug, "neonhttpsrc", 0,
228       "NEON HTTP Client Source");
229 }
230
231 static void
232 gst_neonhttp_src_init (GstNeonhttpSrc * src, GstNeonhttpSrcClass * g_class)
233 {
234   const gchar *str;
235
236   src->neon_http_debug = DEFAULT_NEON_HTTP_DEBUG;
237   src->iradio_mode = DEFAULT_IRADIO_MODE;
238   src->iradio_name = DEFAULT_IRADIO_NAME;
239   src->iradio_genre = DEFAULT_IRADIO_GENRE;
240   src->iradio_url = DEFAULT_IRADIO_URL;
241   src->user_agent = g_strdup (DEFAULT_USER_AGENT);
242   src->automatic_redirect = DEFAULT_AUTOMATIC_REDIRECT;
243   src->accept_self_signed = DEFAULT_ACCEPT_SELF_SIGNED;
244
245   src->session = NULL;
246   src->request = NULL;
247   memset (&src->uri, 0, sizeof (src->uri));
248   memset (&src->proxy, 0, sizeof (src->proxy));
249   src->content_size = -1;
250   src->icy_caps = NULL;
251   src->icy_metaint = 0;
252   src->seekable = TRUE;
253
254   gst_neonhttp_src_set_location (src, DEFAULT_LOCATION);
255
256   /* configure proxy */
257   str = g_getenv ("http_proxy");
258   if (str && !gst_neonhttp_src_set_proxy (src, str)) {
259     GST_WARNING_OBJECT (src,
260         "The proxy set on http_proxy env var ('%s') cannot be parsed.", str);
261   }
262 }
263
264 static void
265 gst_neonhttp_src_dispose (GObject * gobject)
266 {
267   GstNeonhttpSrc *src = GST_NEONHTTP_SRC (gobject);
268
269   ne_uri_free (&src->uri);
270   ne_uri_free (&src->proxy);
271
272   g_free (src->user_agent);
273   g_free (src->iradio_name);
274   g_free (src->iradio_genre);
275   g_free (src->iradio_url);
276
277   if (src->icy_caps) {
278     gst_caps_unref (src->icy_caps);
279     src->icy_caps = NULL;
280   }
281
282   if (src->request) {
283     ne_request_destroy (src->request);
284     src->request = NULL;
285   }
286
287   if (src->session) {
288     ne_close_connection (src->session);
289     ne_session_destroy (src->session);
290     src->session = NULL;
291   }
292
293   if (src->location) {
294     ne_free (src->location);
295   }
296   if (src->query_string) {
297     ne_free (src->query_string);
298   }
299
300   G_OBJECT_CLASS (parent_class)->dispose (gobject);
301 }
302
303 static void
304 gst_neonhttp_src_set_property (GObject * object, guint prop_id,
305     const GValue * value, GParamSpec * pspec)
306 {
307   GstNeonhttpSrc *src = GST_NEONHTTP_SRC (object);
308
309   switch (prop_id) {
310     case PROP_PROXY:
311     {
312       const gchar *proxy;
313
314       proxy = g_value_get_string (value);
315
316       if (proxy == NULL) {
317         GST_WARNING ("proxy property cannot be NULL");
318         goto done;
319       }
320       if (!gst_neonhttp_src_set_proxy (src, proxy)) {
321         GST_WARNING ("badly formated proxy");
322         goto done;
323       }
324       break;
325     }
326     case PROP_LOCATION:
327     {
328       const gchar *location;
329
330       location = g_value_get_string (value);
331
332       if (location == NULL) {
333         GST_WARNING ("location property cannot be NULL");
334         goto done;
335       }
336       if (!gst_neonhttp_src_set_location (src, location)) {
337         GST_WARNING ("badly formated location");
338         goto done;
339       }
340       break;
341     }
342     case PROP_USER_AGENT:
343       if (src->user_agent)
344         g_free (src->user_agent);
345       src->user_agent = g_strdup (g_value_get_string (value));
346       break;
347     case PROP_IRADIO_MODE:
348       src->iradio_mode = g_value_get_boolean (value);
349       break;
350     case PROP_AUTOMATIC_REDIRECT:
351       src->automatic_redirect = g_value_get_boolean (value);
352       break;
353     case PROP_ACCEPT_SELF_SIGNED:
354       src->accept_self_signed = g_value_get_boolean (value);
355       break;
356 #ifndef GST_DISABLE_GST_DEBUG
357     case PROP_NEON_HTTP_DEBUG:
358       src->neon_http_debug = g_value_get_boolean (value);
359       break;
360 #endif
361     default:
362       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
363       break;
364   }
365 done:
366   return;
367 }
368
369 static void
370 gst_neonhttp_src_get_property (GObject * object, guint prop_id,
371     GValue * value, GParamSpec * pspec)
372 {
373   GstNeonhttpSrc *neonhttpsrc = GST_NEONHTTP_SRC (object);
374
375   switch (prop_id) {
376     case PROP_PROXY:
377     {
378       gchar *str;
379
380       if (neonhttpsrc->proxy.host) {
381         str = ne_uri_unparse (&neonhttpsrc->proxy);
382         if (!str)
383           break;
384         g_value_set_string (value, str);
385         ne_free (str);
386       } else {
387         g_value_set_static_string (value, "");
388       }
389       break;
390     }
391     case PROP_LOCATION:
392     {
393       gchar *str;
394
395       if (neonhttpsrc->uri.host) {
396         str = ne_uri_unparse (&neonhttpsrc->uri);
397         if (!str)
398           break;
399         g_value_set_string (value, str);
400         ne_free (str);
401       } else {
402         g_value_set_static_string (value, "");
403       }
404       break;
405     }
406     case PROP_USER_AGENT:
407       g_value_set_string (value, neonhttpsrc->user_agent);
408       break;
409     case PROP_IRADIO_MODE:
410       g_value_set_boolean (value, neonhttpsrc->iradio_mode);
411       break;
412     case PROP_IRADIO_NAME:
413       g_value_set_string (value, neonhttpsrc->iradio_name);
414       break;
415     case PROP_IRADIO_GENRE:
416       g_value_set_string (value, neonhttpsrc->iradio_genre);
417       break;
418     case PROP_IRADIO_URL:
419       g_value_set_string (value, neonhttpsrc->iradio_url);
420       break;
421     case PROP_AUTOMATIC_REDIRECT:
422       g_value_set_boolean (value, neonhttpsrc->automatic_redirect);
423       break;
424     case PROP_ACCEPT_SELF_SIGNED:
425       g_value_set_boolean (value, neonhttpsrc->accept_self_signed);
426       break;
427 #ifndef GST_DISABLE_GST_DEBUG
428     case PROP_NEON_HTTP_DEBUG:
429       g_value_set_boolean (value, neonhttpsrc->neon_http_debug);
430       break;
431 #endif
432     default:
433       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
434       break;
435   }
436 }
437
438 /* NEON CALLBACK */
439 static void
440 oom_callback (void)
441 {
442   GST_ERROR ("memory exeception in neon");
443 }
444
445 static GstFlowReturn
446 gst_neonhttp_src_create (GstPushSrc * psrc, GstBuffer ** outbuf)
447 {
448   GstNeonhttpSrc *src;
449   GstBaseSrc *basesrc;
450   GstFlowReturn ret;
451   gint read;
452
453   src = GST_NEONHTTP_SRC (psrc);
454   basesrc = GST_BASE_SRC_CAST (psrc);
455
456   /* The caller should know the number of bytes and not read beyond EOS. */
457   if (G_UNLIKELY (src->eos))
458     goto eos;
459
460   /* Create the buffer. */
461   ret = gst_pad_alloc_buffer (GST_BASE_SRC_PAD (basesrc),
462       basesrc->segment.last_stop, basesrc->blocksize,
463       src->icy_caps ? src->icy_caps :
464       GST_PAD_CAPS (GST_BASE_SRC_PAD (basesrc)), outbuf);
465
466   if (G_UNLIKELY (ret != GST_FLOW_OK))
467     goto done;
468
469   read = gst_neonhttp_src_request_dispatch (src, *outbuf);
470   if (G_UNLIKELY (read < 0))
471     goto read_error;
472
473   GST_LOG_OBJECT (src, "returning %u bytes", GST_BUFFER_SIZE (*outbuf));
474
475 done:
476   return ret;
477
478   /* ERRORS */
479 eos:
480   {
481     GST_DEBUG_OBJECT (src, "EOS reached");
482     return GST_FLOW_UNEXPECTED;
483   }
484 read_error:
485   {
486     GST_ELEMENT_ERROR (src, RESOURCE, READ,
487         (NULL), ("Could not read any bytes (%i, %s)", read,
488             ne_get_error (src->session)));
489     gst_buffer_unref (*outbuf);
490     *outbuf = NULL;
491     return GST_FLOW_ERROR;
492   }
493 }
494
495 /* create a socket for connecting to remote server */
496 static gboolean
497 gst_neonhttp_src_start (GstBaseSrc * bsrc)
498 {
499   GstNeonhttpSrc *src = GST_NEONHTTP_SRC (bsrc);
500   const gchar *content_length;
501   gint res;
502
503 #ifndef GST_DISABLE_GST_DEBUG
504   if (src->neon_http_debug)
505     ne_debug_init (stderr, NE_DBG_HTTP);
506 #endif
507
508   ne_oom_callback (oom_callback);
509
510   res = ne_sock_init ();
511   if (res != 0)
512     goto init_failed;
513
514   res = gst_neonhttp_src_send_request_and_redirect (src,
515       &src->session, &src->request, 0, src->automatic_redirect);
516
517   if (res != NE_OK || !src->session) {
518     if (res == HTTP_SOCKET_ERROR) {
519       goto socket_error;
520     } else if (res == HTTP_REQUEST_WRONG_PROXY) {
521       goto wrong_proxy;
522     } else {
523       goto begin_req_failed;
524     }
525   }
526
527   content_length = ne_get_response_header (src->request, "Content-Length");
528
529   if (content_length)
530     src->content_size = g_ascii_strtoull (content_length, NULL, 10);
531   else
532     src->content_size = -1;
533
534   if (src->iradio_mode) {
535     /* Icecast stuff */
536     const gchar *str_value;
537     gint gint_value;
538
539     str_value = ne_get_response_header (src->request, "icy-metaint");
540     if (str_value) {
541       if (sscanf (str_value, "%d", &gint_value) == 1) {
542         if (src->icy_caps) {
543           gst_caps_unref (src->icy_caps);
544           src->icy_caps = NULL;
545         }
546         src->icy_metaint = gint_value;
547         src->icy_caps = gst_caps_new_simple ("application/x-icy",
548             "metadata-interval", G_TYPE_INT, src->icy_metaint, NULL);
549       }
550     }
551
552     str_value = ne_get_response_header (src->request, "icy-name");
553     if (str_value) {
554       if (src->iradio_name) {
555         g_free (src->iradio_name);
556         src->iradio_name = NULL;
557       }
558       src->iradio_name = gst_neonhttp_src_unicodify (str_value);
559     }
560     str_value = ne_get_response_header (src->request, "icy-genre");
561     if (str_value) {
562       if (src->iradio_genre) {
563         g_free (src->iradio_genre);
564         src->iradio_genre = NULL;
565       }
566       src->iradio_genre = gst_neonhttp_src_unicodify (str_value);
567     }
568     str_value = ne_get_response_header (src->request, "icy-url");
569     if (str_value) {
570       if (src->iradio_url) {
571         g_free (src->iradio_url);
572         src->iradio_url = NULL;
573       }
574       src->iradio_url = gst_neonhttp_src_unicodify (str_value);
575     }
576   }
577
578   return TRUE;
579
580   /* ERRORS */
581 init_failed:
582   {
583     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
584         ("ne_sock_init() failed: %d", res));
585     return FALSE;
586   }
587 socket_error:
588   {
589     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
590         ("HTTP Request failed when opening socket: %d", res));
591     return FALSE;
592   }
593 wrong_proxy:
594   {
595     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
596         ("Proxy Server URI is invalid - make sure that either both proxy host "
597             "and port are specified or neither."));
598     return FALSE;
599   }
600 begin_req_failed:
601   {
602     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
603         ("Could not begin request: %d", res));
604     return FALSE;
605   }
606 }
607
608 /* close the socket and associated resources
609  * used both to recover from errors and go to NULL state */
610 static gboolean
611 gst_neonhttp_src_stop (GstBaseSrc * bsrc)
612 {
613   GstNeonhttpSrc *src;
614
615   src = GST_NEONHTTP_SRC (bsrc);
616
617   if (src->iradio_name) {
618     g_free (src->iradio_name);
619     src->iradio_name = NULL;
620   }
621
622   if (src->iradio_genre) {
623     g_free (src->iradio_genre);
624     src->iradio_genre = NULL;
625   }
626
627   if (src->iradio_url) {
628     g_free (src->iradio_url);
629     src->iradio_url = NULL;
630   }
631
632   if (src->icy_caps) {
633     gst_caps_unref (src->icy_caps);
634     src->icy_caps = NULL;
635   }
636
637   src->eos = FALSE;
638   src->content_size = -1;
639   src->read_position = 0;
640   src->seekable = TRUE;
641
642   gst_neonhttp_src_close_session (src);
643
644 #ifndef GST_DISABLE_GST_DEBUG
645   ne_debug_init (NULL, 0);
646 #endif
647   ne_oom_callback (NULL);
648   ne_sock_exit ();
649
650   return TRUE;
651 }
652
653 static gboolean
654 gst_neonhttp_src_get_size (GstBaseSrc * bsrc, guint64 * size)
655 {
656   GstNeonhttpSrc *src;
657
658   src = GST_NEONHTTP_SRC (bsrc);
659
660   if (src->content_size == -1)
661     return FALSE;
662
663   *size = src->content_size;
664
665   return TRUE;
666 }
667
668 static gboolean
669 gst_neonhttp_src_is_seekable (GstBaseSrc * bsrc)
670 {
671   return TRUE;
672 }
673
674 static gboolean
675 gst_neonhttp_src_do_seek (GstBaseSrc * bsrc, GstSegment * segment)
676 {
677   GstNeonhttpSrc *src;
678   gint res;
679   ne_session *session = NULL;
680   ne_request *request = NULL;
681
682   src = GST_NEONHTTP_SRC (bsrc);
683
684   if (!src->seekable)
685     return FALSE;
686
687   if (src->read_position == segment->start)
688     return TRUE;
689
690   res = gst_neonhttp_src_send_request_and_redirect (src,
691       &session, &request, segment->start, src->automatic_redirect);
692
693   /* if we are able to seek, replace the session */
694   if (res == NE_OK && session) {
695     gst_neonhttp_src_close_session (src);
696     src->session = session;
697     src->request = request;
698     src->read_position = segment->start;
699     return TRUE;
700   }
701
702   return FALSE;
703 }
704
705 static gboolean
706 gst_neonhttp_src_set_location (GstNeonhttpSrc * src, const gchar * uri)
707 {
708   ne_uri_free (&src->uri);
709   if (src->location) {
710     ne_free (src->location);
711     src->location = NULL;
712   }
713   if (src->query_string) {
714     ne_free (src->query_string);
715     src->query_string = NULL;
716   }
717
718   if (ne_uri_parse (uri, &src->uri) != 0)
719     goto parse_error;
720
721   if (src->uri.scheme == NULL)
722     src->uri.scheme = g_strdup ("http");
723
724   if (src->uri.host == NULL)
725     src->uri.host = g_strdup (DEFAULT_LOCATION);
726
727   if (src->uri.port == 0) {
728     if (!strcmp (src->uri.scheme, "https"))
729       src->uri.port = HTTPS_DEFAULT_PORT;
730     else
731       src->uri.port = HTTP_DEFAULT_PORT;
732   }
733
734   if (!src->uri.path)
735     src->uri.path = g_strdup ("");
736
737   src->query_string = g_strjoin ("?", src->uri.path, src->uri.query, NULL);
738
739   src->location = ne_uri_unparse (&src->uri);
740
741   return TRUE;
742
743   /* ERRORS */
744 parse_error:
745   {
746     if (src->location) {
747       ne_free (src->location);
748       src->location = NULL;
749     }
750     if (src->query_string) {
751       ne_free (src->query_string);
752       src->query_string = NULL;
753     }
754     ne_uri_free (&src->uri);
755     return FALSE;
756   }
757 }
758
759 static gboolean
760 gst_neonhttp_src_set_proxy (GstNeonhttpSrc * src, const char *uri)
761 {
762   ne_uri_free (&src->proxy);
763
764   if (ne_uri_parse (uri, &src->proxy) != 0)
765     goto error;
766
767   if (src->proxy.scheme)
768     GST_WARNING ("The proxy schema shouldn't be defined (schema is '%s')",
769         src->proxy.scheme);
770
771   if (src->proxy.host && !src->proxy.port)
772     goto error;
773
774   if (!src->proxy.path || src->proxy.userinfo)
775     goto error;
776   return TRUE;
777
778   /* ERRORS */
779 error:
780   {
781     ne_uri_free (&src->proxy);
782     return FALSE;
783   }
784 }
785
786 static int
787 ssl_verify_callback (void *data, int failures, const ne_ssl_certificate * cert)
788 {
789   GstNeonhttpSrc *src = GST_NEONHTTP_SRC (data);
790
791   if ((failures & NE_SSL_UNTRUSTED) &&
792       src->accept_self_signed && !ne_ssl_cert_signedby (cert)) {
793     GST_ELEMENT_INFO (src, RESOURCE, READ,
794         (NULL), ("Accepting self-signed server certificate"));
795
796     failures &= ~NE_SSL_UNTRUSTED;
797   }
798
799   if (failures & NE_SSL_NOTYETVALID)
800     GST_ELEMENT_ERROR (src, RESOURCE, READ,
801         (NULL), ("Server certificate not valid yet"));
802   if (failures & NE_SSL_EXPIRED)
803     GST_ELEMENT_ERROR (src, RESOURCE, READ,
804         (NULL), ("Server certificate has expired"));
805   if (failures & NE_SSL_IDMISMATCH)
806     GST_ELEMENT_ERROR (src, RESOURCE, READ,
807         (NULL), ("Server certificate doesn't match hostname"));
808   if (failures & NE_SSL_UNTRUSTED)
809     GST_ELEMENT_ERROR (src, RESOURCE, READ,
810         (NULL), ("Server certificate signer not trusted"));
811
812   GST_DEBUG_OBJECT (src, "failures: %d\n", failures);
813
814   return failures;
815 }
816
817 /* Try to send the HTTP request to the Icecast server, and if possible deals with
818  * all the probable redirections (HTTP status code == 3xx)
819  */
820 static gint
821 gst_neonhttp_src_send_request_and_redirect (GstNeonhttpSrc * src,
822     ne_session ** ses, ne_request ** req, gint64 offset, gboolean do_redir)
823 {
824   ne_session *session = NULL;
825   ne_request *request = NULL;
826   gint res;
827   gint http_status = 0;
828   guint request_count = 0;
829
830   do {
831     if (src->proxy.host && src->proxy.port) {
832       session =
833           ne_session_create (src->uri.scheme, src->uri.host, src->uri.port);
834       ne_session_proxy (session, src->proxy.host, src->proxy.port);
835     } else if (src->proxy.host || src->proxy.port) {
836       /* both proxy host and port must be specified or none */
837       return HTTP_REQUEST_WRONG_PROXY;
838     } else {
839       session =
840           ne_session_create (src->uri.scheme, src->uri.host, src->uri.port);
841     }
842
843     ne_set_session_flag (session, NE_SESSFLAG_ICYPROTO, 1);
844     ne_ssl_set_verify (session, ssl_verify_callback, src);
845
846     request = ne_request_create (session, "GET", src->query_string);
847
848     if (src->user_agent) {
849       ne_add_request_header (request, "User-Agent", src->user_agent);
850     }
851
852     if (src->iradio_mode) {
853       ne_add_request_header (request, "icy-metadata", "1");
854     }
855
856     if (offset > 0) {
857       ne_print_request_header (request, "Range",
858           "bytes=%" G_GINT64_FORMAT "-", offset);
859     }
860
861     res = ne_begin_request (request);
862
863     if (res == NE_OK) {
864       /* When the HTTP status code is 3xx, it is not the SHOUTcast streaming content yet;
865        * Reload the HTTP request with a new URI value */
866       http_status = ne_get_status (request)->code;
867       if (STATUS_IS_REDIRECTION (http_status) && do_redir) {
868         const gchar *redir;
869
870         /* the new URI value to go when redirecting can be found on the 'Location' HTTP header */
871         redir = ne_get_response_header (request, "Location");
872         if (redir != NULL) {
873           ne_uri_free (&src->uri);
874           gst_neonhttp_src_set_location (src, redir);
875           GST_LOG_OBJECT (src, "Got HTTP Status Code %d", http_status);
876           GST_LOG_OBJECT (src, "Using 'Location' header [%s]", src->uri.host);
877         }
878       }
879     }
880
881     if ((res != NE_OK) ||
882         (offset == 0 && http_status != 200) ||
883         (offset > 0 && http_status != 206 &&
884             !STATUS_IS_REDIRECTION (http_status))) {
885       ne_request_destroy (request);
886       request = NULL;
887       ne_close_connection (session);
888       ne_session_destroy (session);
889       session = NULL;
890       if (offset > 0 && http_status != 206 &&
891           !STATUS_IS_REDIRECTION (http_status)) {
892         src->seekable = FALSE;
893       }
894     }
895
896     /* if - NE_OK */
897     if (STATUS_IS_REDIRECTION (http_status) && do_redir) {
898       ++request_count;
899       GST_LOG_OBJECT (src, "redirect request_count is now %d", request_count);
900       if (request_count < MAX_HTTP_REDIRECTS_NUMBER && do_redir) {
901         GST_INFO_OBJECT (src, "Redirecting to %s", src->uri.host);
902       } else {
903         GST_WARNING_OBJECT (src, "Will not redirect, try again with a "
904             "different URI or redirect location %s", src->uri.host);
905       }
906       /* FIXME: when not redirecting automatically, shouldn't we post a 
907        * redirect element message on the bus? */
908     }
909     /* do the redirect, go back to send another HTTP request now using the 'Location' */
910   } while (do_redir && (request_count < MAX_HTTP_REDIRECTS_NUMBER)
911       && STATUS_IS_REDIRECTION (http_status));
912
913   if (session) {
914     *ses = session;
915     *req = request;
916   }
917
918   return res;
919 }
920
921 static gint
922 gst_neonhttp_src_request_dispatch (GstNeonhttpSrc * src, GstBuffer * outbuf)
923 {
924   gint ret;
925   gint read = 0;
926   gint sizetoread = GST_BUFFER_SIZE (outbuf);
927
928   /* Loop sending the request:
929    * Retry whilst authentication fails and we supply it. */
930
931   ssize_t len = 0;
932
933   while (sizetoread > 0) {
934     len = ne_read_response_block (src->request,
935         (gchar *) GST_BUFFER_DATA (outbuf) + read, sizetoread);
936     if (len > 0) {
937       read += len;
938       sizetoread -= len;
939     } else {
940       break;
941     }
942
943   }
944
945   GST_BUFFER_SIZE (outbuf) = read;
946
947   if (len < 0) {
948     read = -2;
949     goto done;
950   } else if (len == 0) {
951     ret = ne_end_request (src->request);
952     if (ret != NE_RETRY) {
953       if (ret == NE_OK) {
954         src->eos = TRUE;
955       } else {
956         read = -3;
957       }
958     }
959     goto done;
960   }
961
962   if (read > 0)
963     src->read_position += read;
964
965 done:
966   return read;
967 }
968
969 static void
970 gst_neonhttp_src_close_session (GstNeonhttpSrc * src)
971 {
972   if (src->request) {
973     ne_request_destroy (src->request);
974     src->request = NULL;
975   }
976
977   if (src->session) {
978     ne_close_connection (src->session);
979     ne_session_destroy (src->session);
980     src->session = NULL;
981   }
982 }
983
984 /* The following two charset mangling functions were copied from gnomevfssrc.
985  * Preserve them under the unverified assumption that they do something vaguely
986  * worthwhile.
987  */
988 static gchar *
989 unicodify (const gchar * str, gint len, ...)
990 {
991   gchar *ret = NULL, *cset;
992   va_list args;
993   gsize bytes_read, bytes_written;
994
995   if (g_utf8_validate (str, len, NULL))
996     return g_strndup (str, len >= 0 ? len : strlen (str));
997
998   va_start (args, len);
999   while ((cset = va_arg (args, gchar *)) != NULL) {
1000     if (!strcmp (cset, "locale"))
1001       ret = g_locale_to_utf8 (str, len, &bytes_read, &bytes_written, NULL);
1002     else
1003       ret = g_convert (str, len, "UTF-8", cset,
1004           &bytes_read, &bytes_written, NULL);
1005     if (ret)
1006       break;
1007   }
1008   va_end (args);
1009
1010   return ret;
1011 }
1012
1013 static gchar *
1014 gst_neonhttp_src_unicodify (const gchar * str)
1015 {
1016   return unicodify (str, -1, "locale", "ISO-8859-1", NULL);
1017 }
1018
1019 /* GstURIHandler Interface */
1020 static guint
1021 gst_neonhttp_src_uri_get_type (void)
1022 {
1023   return GST_URI_SRC;
1024 }
1025
1026 static gchar **
1027 gst_neonhttp_src_uri_get_protocols (void)
1028 {
1029   static const gchar *protocols[] = { "http", "https", NULL };
1030   return (gchar **) protocols;
1031 }
1032
1033 static const gchar *
1034 gst_neonhttp_src_uri_get_uri (GstURIHandler * handler)
1035 {
1036   GstNeonhttpSrc *src = GST_NEONHTTP_SRC (handler);
1037
1038   return src->location;
1039 }
1040
1041 static gboolean
1042 gst_neonhttp_src_uri_set_uri (GstURIHandler * handler, const gchar * uri)
1043 {
1044   GstNeonhttpSrc *src = GST_NEONHTTP_SRC (handler);
1045
1046   return gst_neonhttp_src_set_location (src, uri);
1047 }
1048
1049 static void
1050 gst_neonhttp_src_uri_handler_init (gpointer g_iface, gpointer iface_data)
1051 {
1052   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
1053
1054   iface->get_type = gst_neonhttp_src_uri_get_type;
1055   iface->get_protocols = gst_neonhttp_src_uri_get_protocols;
1056   iface->get_uri = gst_neonhttp_src_uri_get_uri;
1057   iface->set_uri = gst_neonhttp_src_uri_set_uri;
1058 }
1059
1060 /* entry point to initialize the plug-in
1061  * initialize the plug-in itself
1062  * register the element factories and pad templates
1063  * register the features
1064  */
1065 static gboolean
1066 plugin_init (GstPlugin * plugin)
1067 {
1068   return gst_element_register (plugin, "neonhttpsrc", GST_RANK_NONE,
1069       GST_TYPE_NEONHTTP_SRC);
1070 }
1071
1072 /* this is the structure that gst-register looks for
1073  * so keep the name plugin_desc, or you cannot get your plug-in registered */
1074 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1075     GST_VERSION_MINOR,
1076     "neon",
1077     "lib neon http client src",
1078     plugin_init, VERSION, GST_LICENSE, GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)