use local address, not remote, in SDP
[platform/upstream/gstreamer.git] / gst / rtsp-server / rtsp-client.c
1 /* GStreamer
2  * Copyright (C) 2008 Wim Taymans <wim.taymans at gmail.com>
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 details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
17  * Boston, MA 02110-1301, USA.
18  */
19
20 #include <stdio.h>
21 #include <string.h>
22
23 #include "rtsp-client.h"
24 #include "rtsp-sdp.h"
25 #include "rtsp-params.h"
26
27 #define GST_RTSP_CLIENT_GET_PRIVATE(obj)  \
28    (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_RTSP_CLIENT, GstRTSPClientPrivate))
29
30 /* locking order:
31  * send_lock, lock, tunnels_lock
32  */
33
34 struct _GstRTSPClientPrivate
35 {
36   GMutex lock;                  /* protects everything else */
37   GMutex send_lock;
38   GstRTSPConnection *connection;
39   GstRTSPWatch *watch;
40   guint close_seq;
41   gchar *server_ip;
42   gboolean is_ipv6;
43   gboolean use_client_settings;
44
45   GstRTSPClientSendFunc send_func;      /* protected by send_lock */
46   gpointer send_data;           /* protected by send_lock */
47   GDestroyNotify send_notify;   /* protected by send_lock */
48
49   GstRTSPSessionPool *session_pool;
50   GstRTSPMountPoints *mount_points;
51   GstRTSPAuth *auth;
52
53   GstRTSPUrl *uri;
54   GstRTSPMedia *media;
55
56   GList *transports;
57   GList *sessions;
58 };
59
60 static GMutex tunnels_lock;
61 static GHashTable *tunnels;     /* protected by tunnels_lock */
62
63 #define DEFAULT_SESSION_POOL            NULL
64 #define DEFAULT_MOUNT_POINTS            NULL
65 #define DEFAULT_USE_CLIENT_SETTINGS     FALSE
66
67 enum
68 {
69   PROP_0,
70   PROP_SESSION_POOL,
71   PROP_MOUNT_POINTS,
72   PROP_USE_CLIENT_SETTINGS,
73   PROP_LAST
74 };
75
76 enum
77 {
78   SIGNAL_CLOSED,
79   SIGNAL_NEW_SESSION,
80   SIGNAL_OPTIONS_REQUEST,
81   SIGNAL_DESCRIBE_REQUEST,
82   SIGNAL_SETUP_REQUEST,
83   SIGNAL_PLAY_REQUEST,
84   SIGNAL_PAUSE_REQUEST,
85   SIGNAL_TEARDOWN_REQUEST,
86   SIGNAL_SET_PARAMETER_REQUEST,
87   SIGNAL_GET_PARAMETER_REQUEST,
88   SIGNAL_LAST
89 };
90
91 GST_DEBUG_CATEGORY_STATIC (rtsp_client_debug);
92 #define GST_CAT_DEFAULT rtsp_client_debug
93
94 static guint gst_rtsp_client_signals[SIGNAL_LAST] = { 0 };
95
96 static void gst_rtsp_client_get_property (GObject * object, guint propid,
97     GValue * value, GParamSpec * pspec);
98 static void gst_rtsp_client_set_property (GObject * object, guint propid,
99     const GValue * value, GParamSpec * pspec);
100 static void gst_rtsp_client_finalize (GObject * obj);
101
102 static GstSDPMessage *create_sdp (GstRTSPClient * client, GstRTSPMedia * media);
103 static void client_session_finalized (GstRTSPClient * client,
104     GstRTSPSession * session);
105 static void unlink_session_transports (GstRTSPClient * client,
106     GstRTSPSession * session, GstRTSPSessionMedia * media);
107
108 G_DEFINE_TYPE (GstRTSPClient, gst_rtsp_client, G_TYPE_OBJECT);
109
110 static void
111 gst_rtsp_client_class_init (GstRTSPClientClass * klass)
112 {
113   GObjectClass *gobject_class;
114
115   g_type_class_add_private (klass, sizeof (GstRTSPClientPrivate));
116
117   gobject_class = G_OBJECT_CLASS (klass);
118
119   gobject_class->get_property = gst_rtsp_client_get_property;
120   gobject_class->set_property = gst_rtsp_client_set_property;
121   gobject_class->finalize = gst_rtsp_client_finalize;
122
123   klass->create_sdp = create_sdp;
124
125   g_object_class_install_property (gobject_class, PROP_SESSION_POOL,
126       g_param_spec_object ("session-pool", "Session Pool",
127           "The session pool to use for client session",
128           GST_TYPE_RTSP_SESSION_POOL,
129           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
130
131   g_object_class_install_property (gobject_class, PROP_MOUNT_POINTS,
132       g_param_spec_object ("mount-points", "Mount Points",
133           "The mount points to use for client session",
134           GST_TYPE_RTSP_MOUNT_POINTS,
135           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
136
137   g_object_class_install_property (gobject_class, PROP_USE_CLIENT_SETTINGS,
138       g_param_spec_boolean ("use-client-settings", "Use Client Settings",
139           "Use client settings for ttl and destination in multicast",
140           DEFAULT_USE_CLIENT_SETTINGS,
141           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
142
143   gst_rtsp_client_signals[SIGNAL_CLOSED] =
144       g_signal_new ("closed", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
145       G_STRUCT_OFFSET (GstRTSPClientClass, closed), NULL, NULL,
146       g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0, G_TYPE_NONE);
147
148   gst_rtsp_client_signals[SIGNAL_NEW_SESSION] =
149       g_signal_new ("new-session", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
150       G_STRUCT_OFFSET (GstRTSPClientClass, new_session), NULL, NULL,
151       g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1, GST_TYPE_RTSP_SESSION);
152
153   gst_rtsp_client_signals[SIGNAL_OPTIONS_REQUEST] =
154       g_signal_new ("options-request", G_TYPE_FROM_CLASS (klass),
155       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, options_request),
156       NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1,
157       G_TYPE_POINTER);
158
159   gst_rtsp_client_signals[SIGNAL_DESCRIBE_REQUEST] =
160       g_signal_new ("describe-request", G_TYPE_FROM_CLASS (klass),
161       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, describe_request),
162       NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1,
163       G_TYPE_POINTER);
164
165   gst_rtsp_client_signals[SIGNAL_SETUP_REQUEST] =
166       g_signal_new ("setup-request", G_TYPE_FROM_CLASS (klass),
167       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, setup_request),
168       NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1,
169       G_TYPE_POINTER);
170
171   gst_rtsp_client_signals[SIGNAL_PLAY_REQUEST] =
172       g_signal_new ("play-request", G_TYPE_FROM_CLASS (klass),
173       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, play_request),
174       NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1,
175       G_TYPE_POINTER);
176
177   gst_rtsp_client_signals[SIGNAL_PAUSE_REQUEST] =
178       g_signal_new ("pause-request", G_TYPE_FROM_CLASS (klass),
179       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, pause_request),
180       NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1,
181       G_TYPE_POINTER);
182
183   gst_rtsp_client_signals[SIGNAL_TEARDOWN_REQUEST] =
184       g_signal_new ("teardown-request", G_TYPE_FROM_CLASS (klass),
185       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, teardown_request),
186       NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1,
187       G_TYPE_POINTER);
188
189   gst_rtsp_client_signals[SIGNAL_SET_PARAMETER_REQUEST] =
190       g_signal_new ("set-parameter-request", G_TYPE_FROM_CLASS (klass),
191       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass,
192           set_parameter_request), NULL, NULL, g_cclosure_marshal_VOID__POINTER,
193       G_TYPE_NONE, 1, G_TYPE_POINTER);
194
195   gst_rtsp_client_signals[SIGNAL_GET_PARAMETER_REQUEST] =
196       g_signal_new ("get-parameter-request", G_TYPE_FROM_CLASS (klass),
197       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass,
198           get_parameter_request), NULL, NULL, g_cclosure_marshal_VOID__POINTER,
199       G_TYPE_NONE, 1, G_TYPE_POINTER);
200
201   tunnels =
202       g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_object_unref);
203   g_mutex_init (&tunnels_lock);
204
205   GST_DEBUG_CATEGORY_INIT (rtsp_client_debug, "rtspclient", 0, "GstRTSPClient");
206 }
207
208 static void
209 gst_rtsp_client_init (GstRTSPClient * client)
210 {
211   GstRTSPClientPrivate *priv = GST_RTSP_CLIENT_GET_PRIVATE (client);
212
213   client->priv = priv;
214
215   g_mutex_init (&priv->lock);
216   g_mutex_init (&priv->send_lock);
217   priv->use_client_settings = DEFAULT_USE_CLIENT_SETTINGS;
218   priv->close_seq = 0;
219 }
220
221 static GstRTSPFilterResult
222 filter_session (GstRTSPSession * sess, GstRTSPSessionMedia * media,
223     gpointer user_data)
224 {
225   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
226
227   gst_rtsp_session_media_set_state (media, GST_STATE_NULL);
228   unlink_session_transports (client, sess, media);
229
230   /* unmanage the media in the session */
231   return GST_RTSP_FILTER_REMOVE;
232 }
233
234 static void
235 client_unlink_session (GstRTSPClient * client, GstRTSPSession * session)
236 {
237   /* unlink all media managed in this session */
238   gst_rtsp_session_filter (session, filter_session, client);
239 }
240
241 static void
242 client_cleanup_sessions (GstRTSPClient * client)
243 {
244   GstRTSPClientPrivate *priv = client->priv;
245   GList *sessions;
246
247   /* remove weak-ref from sessions */
248   for (sessions = priv->sessions; sessions; sessions = g_list_next (sessions)) {
249     GstRTSPSession *session = (GstRTSPSession *) sessions->data;
250     g_object_weak_unref (G_OBJECT (session),
251         (GWeakNotify) client_session_finalized, client);
252     client_unlink_session (client, session);
253   }
254   g_list_free (priv->sessions);
255   priv->sessions = NULL;
256 }
257
258 /* A client is finalized when the connection is broken */
259 static void
260 gst_rtsp_client_finalize (GObject * obj)
261 {
262   GstRTSPClient *client = GST_RTSP_CLIENT (obj);
263   GstRTSPClientPrivate *priv = client->priv;
264
265   GST_INFO ("finalize client %p", client);
266
267   gst_rtsp_client_set_send_func (client, NULL, NULL, NULL);
268
269   if (priv->watch)
270     g_source_destroy ((GSource *) priv->watch);
271
272   client_cleanup_sessions (client);
273
274   if (priv->connection)
275     gst_rtsp_connection_free (priv->connection);
276   if (priv->session_pool)
277     g_object_unref (priv->session_pool);
278   if (priv->mount_points)
279     g_object_unref (priv->mount_points);
280   if (priv->auth)
281     g_object_unref (priv->auth);
282
283   if (priv->uri)
284     gst_rtsp_url_free (priv->uri);
285   if (priv->media) {
286     gst_rtsp_media_unprepare (priv->media);
287     g_object_unref (priv->media);
288   }
289
290   g_free (priv->server_ip);
291   g_mutex_clear (&priv->lock);
292   g_mutex_clear (&priv->send_lock);
293
294   G_OBJECT_CLASS (gst_rtsp_client_parent_class)->finalize (obj);
295 }
296
297 static void
298 gst_rtsp_client_get_property (GObject * object, guint propid,
299     GValue * value, GParamSpec * pspec)
300 {
301   GstRTSPClient *client = GST_RTSP_CLIENT (object);
302
303   switch (propid) {
304     case PROP_SESSION_POOL:
305       g_value_take_object (value, gst_rtsp_client_get_session_pool (client));
306       break;
307     case PROP_MOUNT_POINTS:
308       g_value_take_object (value, gst_rtsp_client_get_mount_points (client));
309       break;
310     case PROP_USE_CLIENT_SETTINGS:
311       g_value_set_boolean (value,
312           gst_rtsp_client_get_use_client_settings (client));
313       break;
314     default:
315       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, propid, pspec);
316   }
317 }
318
319 static void
320 gst_rtsp_client_set_property (GObject * object, guint propid,
321     const GValue * value, GParamSpec * pspec)
322 {
323   GstRTSPClient *client = GST_RTSP_CLIENT (object);
324
325   switch (propid) {
326     case PROP_SESSION_POOL:
327       gst_rtsp_client_set_session_pool (client, g_value_get_object (value));
328       break;
329     case PROP_MOUNT_POINTS:
330       gst_rtsp_client_set_mount_points (client, g_value_get_object (value));
331       break;
332     case PROP_USE_CLIENT_SETTINGS:
333       gst_rtsp_client_set_use_client_settings (client,
334           g_value_get_boolean (value));
335       break;
336     default:
337       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, propid, pspec);
338   }
339 }
340
341 /**
342  * gst_rtsp_client_new:
343  *
344  * Create a new #GstRTSPClient instance.
345  *
346  * Returns: a new #GstRTSPClient
347  */
348 GstRTSPClient *
349 gst_rtsp_client_new (void)
350 {
351   GstRTSPClient *result;
352
353   result = g_object_new (GST_TYPE_RTSP_CLIENT, NULL);
354
355   return result;
356 }
357
358 static void
359 send_response (GstRTSPClient * client, GstRTSPSession * session,
360     GstRTSPMessage * response, gboolean close)
361 {
362   GstRTSPClientPrivate *priv = client->priv;
363
364   gst_rtsp_message_add_header (response, GST_RTSP_HDR_SERVER,
365       "GStreamer RTSP server");
366
367   /* remove any previous header */
368   gst_rtsp_message_remove_header (response, GST_RTSP_HDR_SESSION, -1);
369
370   /* add the new session header for new session ids */
371   if (session) {
372     gst_rtsp_message_take_header (response, GST_RTSP_HDR_SESSION,
373         gst_rtsp_session_get_header (session));
374   }
375
376   if (gst_debug_category_get_threshold (rtsp_client_debug) >= GST_LEVEL_LOG) {
377     gst_rtsp_message_dump (response);
378   }
379
380   if (close)
381     gst_rtsp_message_add_header (response, GST_RTSP_HDR_CONNECTION, "close");
382
383   g_mutex_lock (&priv->send_lock);
384   if (priv->send_func)
385     priv->send_func (client, response, close, priv->send_data);
386   g_mutex_unlock (&priv->send_lock);
387
388   gst_rtsp_message_unset (response);
389 }
390
391 static void
392 send_generic_response (GstRTSPClient * client, GstRTSPStatusCode code,
393     GstRTSPClientState * state)
394 {
395   gst_rtsp_message_init_response (state->response, code,
396       gst_rtsp_status_as_text (code), state->request);
397
398   send_response (client, NULL, state->response, FALSE);
399 }
400
401 static void
402 handle_unauthorized_request (GstRTSPClient * client, GstRTSPAuth * auth,
403     GstRTSPClientState * state)
404 {
405   gst_rtsp_message_init_response (state->response, GST_RTSP_STS_UNAUTHORIZED,
406       gst_rtsp_status_as_text (GST_RTSP_STS_UNAUTHORIZED), state->request);
407
408   if (auth) {
409     /* and let the authentication manager setup the auth tokens */
410     gst_rtsp_auth_setup_auth (auth, client, 0, state);
411   }
412
413   send_response (client, state->session, state->response, FALSE);
414 }
415
416
417 static gboolean
418 compare_uri (const GstRTSPUrl * uri1, const GstRTSPUrl * uri2)
419 {
420   if (uri1 == NULL || uri2 == NULL)
421     return FALSE;
422
423   if (strcmp (uri1->abspath, uri2->abspath))
424     return FALSE;
425
426   return TRUE;
427 }
428
429 /* this function is called to initially find the media for the DESCRIBE request
430  * but is cached for when the same client (without breaking the connection) is
431  * doing a setup for the exact same url. */
432 static GstRTSPMedia *
433 find_media (GstRTSPClient * client, GstRTSPClientState * state)
434 {
435   GstRTSPClientPrivate *priv = client->priv;
436   GstRTSPMediaFactory *factory;
437   GstRTSPMedia *media;
438   GstRTSPAuth *auth;
439
440   if (!compare_uri (priv->uri, state->uri)) {
441     /* remove any previously cached values before we try to construct a new
442      * media for uri */
443     if (priv->uri)
444       gst_rtsp_url_free (priv->uri);
445     priv->uri = NULL;
446     if (priv->media) {
447       gst_rtsp_media_unprepare (priv->media);
448       g_object_unref (priv->media);
449     }
450     priv->media = NULL;
451
452     if (!priv->mount_points)
453       goto no_mount_points;
454
455     /* find the factory for the uri first */
456     if (!(factory =
457             gst_rtsp_mount_points_find_factory (priv->mount_points,
458                 state->uri)))
459       goto no_factory;
460
461     /* check if we have access to the factory */
462     if ((auth = gst_rtsp_media_factory_get_auth (factory))) {
463       state->factory = factory;
464
465       if (!gst_rtsp_auth_check (auth, client, 0, state))
466         goto not_allowed;
467
468       state->factory = NULL;
469       g_object_unref (auth);
470     }
471
472     /* prepare the media and add it to the pipeline */
473     if (!(media = gst_rtsp_media_factory_construct (factory, state->uri)))
474       goto no_media;
475
476     g_object_unref (factory);
477     factory = NULL;
478
479     /* prepare the media */
480     if (!(gst_rtsp_media_prepare (media)))
481       goto no_prepare;
482
483     /* now keep track of the uri and the media */
484     priv->uri = gst_rtsp_url_copy (state->uri);
485     priv->media = media;
486     state->media = media;
487   } else {
488     /* we have seen this uri before, used cached media */
489     media = priv->media;
490     state->media = media;
491     GST_INFO ("reusing cached media %p", media);
492   }
493
494   if (media)
495     g_object_ref (media);
496
497   return media;
498
499   /* ERRORS */
500 no_mount_points:
501   {
502     GST_ERROR ("client %p: no mount points configured", client);
503     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, state);
504     return NULL;
505   }
506 no_factory:
507   {
508     GST_ERROR ("client %p: no factory for uri", client);
509     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, state);
510     return NULL;
511   }
512 not_allowed:
513   {
514     GST_ERROR ("client %p: unauthorized request", client);
515     handle_unauthorized_request (client, auth, state);
516     g_object_unref (factory);
517     state->factory = NULL;
518     g_object_unref (auth);
519     return NULL;
520   }
521 no_media:
522   {
523     GST_ERROR ("client %p: can't create media", client);
524     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, state);
525     g_object_unref (factory);
526     return NULL;
527   }
528 no_prepare:
529   {
530     GST_ERROR ("client %p: can't prepare media", client);
531     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, state);
532     g_object_unref (media);
533     return NULL;
534   }
535 }
536
537 static gboolean
538 do_send_data (GstBuffer * buffer, guint8 channel, GstRTSPClient * client)
539 {
540   GstRTSPClientPrivate *priv = client->priv;
541   GstRTSPMessage message = { 0 };
542   GstMapInfo map_info;
543   guint8 *data;
544   guint usize;
545
546   gst_rtsp_message_init_data (&message, channel);
547
548   /* FIXME, need some sort of iovec RTSPMessage here */
549   if (!gst_buffer_map (buffer, &map_info, GST_MAP_READ))
550     return FALSE;
551
552   gst_rtsp_message_take_body (&message, map_info.data, map_info.size);
553
554   g_mutex_lock (&priv->send_lock);
555   if (priv->send_func)
556     priv->send_func (client, &message, FALSE, priv->send_data);
557   g_mutex_unlock (&priv->send_lock);
558
559   gst_rtsp_message_steal_body (&message, &data, &usize);
560   gst_buffer_unmap (buffer, &map_info);
561
562   gst_rtsp_message_unset (&message);
563
564   return TRUE;
565 }
566
567 static void
568 link_transport (GstRTSPClient * client, GstRTSPSession * session,
569     GstRTSPStreamTransport * trans)
570 {
571   GstRTSPClientPrivate *priv = client->priv;
572
573   GST_DEBUG ("client %p: linking transport %p", client, trans);
574
575   gst_rtsp_stream_transport_set_callbacks (trans,
576       (GstRTSPSendFunc) do_send_data,
577       (GstRTSPSendFunc) do_send_data, client, NULL);
578
579   priv->transports = g_list_prepend (priv->transports, trans);
580
581   /* make sure our session can't expire */
582   gst_rtsp_session_prevent_expire (session);
583 }
584
585 static void
586 unlink_transport (GstRTSPClient * client, GstRTSPSession * session,
587     GstRTSPStreamTransport * trans)
588 {
589   GstRTSPClientPrivate *priv = client->priv;
590
591   GST_DEBUG ("client %p: unlinking transport %p", client, trans);
592
593   gst_rtsp_stream_transport_set_callbacks (trans, NULL, NULL, NULL, NULL);
594
595   priv->transports = g_list_remove (priv->transports, trans);
596
597   /* our session can now expire */
598   gst_rtsp_session_allow_expire (session);
599 }
600
601 static void
602 unlink_session_transports (GstRTSPClient * client, GstRTSPSession * session,
603     GstRTSPSessionMedia * media)
604 {
605   guint n_streams, i;
606
607   n_streams =
608       gst_rtsp_media_n_streams (gst_rtsp_session_media_get_media (media));
609   for (i = 0; i < n_streams; i++) {
610     GstRTSPStreamTransport *trans;
611     const GstRTSPTransport *tr;
612
613     /* get the transport, if there is no transport configured, skip this stream */
614     trans = gst_rtsp_session_media_get_transport (media, i);
615     if (trans == NULL)
616       continue;
617
618     tr = gst_rtsp_stream_transport_get_transport (trans);
619
620     if (tr->lower_transport == GST_RTSP_LOWER_TRANS_TCP) {
621       /* for TCP, unlink the stream from the TCP connection of the client */
622       unlink_transport (client, session, trans);
623     }
624   }
625 }
626
627 static void
628 close_connection (GstRTSPClient * client)
629 {
630   GstRTSPClientPrivate *priv = client->priv;
631   const gchar *tunnelid;
632
633   GST_DEBUG ("client %p: closing connection", client);
634
635   if ((tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection))) {
636     g_mutex_lock (&tunnels_lock);
637     /* remove from tunnelids */
638     g_hash_table_remove (tunnels, tunnelid);
639     g_mutex_unlock (&tunnels_lock);
640   }
641
642   gst_rtsp_connection_close (priv->connection);
643 }
644
645 static gboolean
646 handle_teardown_request (GstRTSPClient * client, GstRTSPClientState * state)
647 {
648   GstRTSPClientPrivate *priv = client->priv;
649   GstRTSPSession *session;
650   GstRTSPSessionMedia *media;
651   GstRTSPStatusCode code;
652
653   if (!state->session)
654     goto no_session;
655
656   session = state->session;
657
658   /* get a handle to the configuration of the media in the session */
659   media = gst_rtsp_session_get_media (session, state->uri);
660   if (!media)
661     goto not_found;
662
663   state->sessmedia = media;
664
665   /* we emit the signal before closing the connection */
666   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_TEARDOWN_REQUEST],
667       0, state);
668
669   /* unlink the all TCP callbacks */
670   unlink_session_transports (client, session, media);
671
672   /* remove the session from the watched sessions */
673   g_object_weak_unref (G_OBJECT (session),
674       (GWeakNotify) client_session_finalized, client);
675   priv->sessions = g_list_remove (priv->sessions, session);
676
677   gst_rtsp_session_media_set_state (media, GST_STATE_NULL);
678
679   /* unmanage the media in the session, returns false if all media session
680    * are torn down. */
681   if (!gst_rtsp_session_release_media (session, media)) {
682     /* remove the session */
683     gst_rtsp_session_pool_remove (priv->session_pool, session);
684   }
685   /* construct the response now */
686   code = GST_RTSP_STS_OK;
687   gst_rtsp_message_init_response (state->response, code,
688       gst_rtsp_status_as_text (code), state->request);
689
690   send_response (client, session, state->response, TRUE);
691
692   return TRUE;
693
694   /* ERRORS */
695 no_session:
696   {
697     GST_ERROR ("client %p: no session", client);
698     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, state);
699     return FALSE;
700   }
701 not_found:
702   {
703     GST_ERROR ("client %p: no media for uri", client);
704     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, state);
705     return FALSE;
706   }
707 }
708
709 static gboolean
710 handle_get_param_request (GstRTSPClient * client, GstRTSPClientState * state)
711 {
712   GstRTSPResult res;
713   guint8 *data;
714   guint size;
715
716   res = gst_rtsp_message_get_body (state->request, &data, &size);
717   if (res != GST_RTSP_OK)
718     goto bad_request;
719
720   if (size == 0) {
721     /* no body, keep-alive request */
722     send_generic_response (client, GST_RTSP_STS_OK, state);
723   } else {
724     /* there is a body, handle the params */
725     res = gst_rtsp_params_get (client, state);
726     if (res != GST_RTSP_OK)
727       goto bad_request;
728
729     send_response (client, state->session, state->response, FALSE);
730   }
731
732   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_GET_PARAMETER_REQUEST],
733       0, state);
734
735   return TRUE;
736
737   /* ERRORS */
738 bad_request:
739   {
740     GST_ERROR ("client %p: bad request", client);
741     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, state);
742     return FALSE;
743   }
744 }
745
746 static gboolean
747 handle_set_param_request (GstRTSPClient * client, GstRTSPClientState * state)
748 {
749   GstRTSPResult res;
750   guint8 *data;
751   guint size;
752
753   res = gst_rtsp_message_get_body (state->request, &data, &size);
754   if (res != GST_RTSP_OK)
755     goto bad_request;
756
757   if (size == 0) {
758     /* no body, keep-alive request */
759     send_generic_response (client, GST_RTSP_STS_OK, state);
760   } else {
761     /* there is a body, handle the params */
762     res = gst_rtsp_params_set (client, state);
763     if (res != GST_RTSP_OK)
764       goto bad_request;
765
766     send_response (client, state->session, state->response, FALSE);
767   }
768
769   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_SET_PARAMETER_REQUEST],
770       0, state);
771
772   return TRUE;
773
774   /* ERRORS */
775 bad_request:
776   {
777     GST_ERROR ("client %p: bad request", client);
778     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, state);
779     return FALSE;
780   }
781 }
782
783 static gboolean
784 handle_pause_request (GstRTSPClient * client, GstRTSPClientState * state)
785 {
786   GstRTSPSession *session;
787   GstRTSPSessionMedia *media;
788   GstRTSPStatusCode code;
789   GstRTSPState rtspstate;
790
791   if (!(session = state->session))
792     goto no_session;
793
794   /* get a handle to the configuration of the media in the session */
795   media = gst_rtsp_session_get_media (session, state->uri);
796   if (!media)
797     goto not_found;
798
799   state->sessmedia = media;
800
801   rtspstate = gst_rtsp_session_media_get_rtsp_state (media);
802   /* the session state must be playing or recording */
803   if (rtspstate != GST_RTSP_STATE_PLAYING &&
804       rtspstate != GST_RTSP_STATE_RECORDING)
805     goto invalid_state;
806
807   /* unlink the all TCP callbacks */
808   unlink_session_transports (client, session, media);
809
810   /* then pause sending */
811   gst_rtsp_session_media_set_state (media, GST_STATE_PAUSED);
812
813   /* construct the response now */
814   code = GST_RTSP_STS_OK;
815   gst_rtsp_message_init_response (state->response, code,
816       gst_rtsp_status_as_text (code), state->request);
817
818   send_response (client, session, state->response, FALSE);
819
820   /* the state is now READY */
821   gst_rtsp_session_media_set_rtsp_state (media, GST_RTSP_STATE_READY);
822
823   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_PAUSE_REQUEST],
824       0, state);
825
826   return TRUE;
827
828   /* ERRORS */
829 no_session:
830   {
831     GST_ERROR ("client %p: no seesion", client);
832     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, state);
833     return FALSE;
834   }
835 not_found:
836   {
837     GST_ERROR ("client %p: no media for uri", client);
838     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, state);
839     return FALSE;
840   }
841 invalid_state:
842   {
843     GST_ERROR ("client %p: not PLAYING or RECORDING", client);
844     send_generic_response (client, GST_RTSP_STS_METHOD_NOT_VALID_IN_THIS_STATE,
845         state);
846     return FALSE;
847   }
848 }
849
850 static gboolean
851 handle_play_request (GstRTSPClient * client, GstRTSPClientState * state)
852 {
853   GstRTSPSession *session;
854   GstRTSPSessionMedia *media;
855   GstRTSPStatusCode code;
856   GString *rtpinfo;
857   guint n_streams, i, infocount;
858   gchar *str;
859   GstRTSPTimeRange *range;
860   GstRTSPResult res;
861   GstRTSPState rtspstate;
862   GstRTSPRangeUnit unit = GST_RTSP_RANGE_NPT;
863
864   if (!(session = state->session))
865     goto no_session;
866
867   /* get a handle to the configuration of the media in the session */
868   media = gst_rtsp_session_get_media (session, state->uri);
869   if (!media)
870     goto not_found;
871
872   state->sessmedia = media;
873
874   /* the session state must be playing or ready */
875   rtspstate = gst_rtsp_session_media_get_rtsp_state (media);
876   if (rtspstate != GST_RTSP_STATE_PLAYING && rtspstate != GST_RTSP_STATE_READY)
877     goto invalid_state;
878
879   /* parse the range header if we have one */
880   res =
881       gst_rtsp_message_get_header (state->request, GST_RTSP_HDR_RANGE, &str, 0);
882   if (res == GST_RTSP_OK) {
883     if (gst_rtsp_range_parse (str, &range) == GST_RTSP_OK) {
884       /* we have a range, seek to the position */
885       gst_rtsp_media_seek (gst_rtsp_session_media_get_media (media), range);
886       unit = range->unit;
887       gst_rtsp_range_free (range);
888     }
889   }
890
891   /* grab RTPInfo from the payloaders now */
892   rtpinfo = g_string_new ("");
893
894   n_streams =
895       gst_rtsp_media_n_streams (gst_rtsp_session_media_get_media (media));
896   for (i = 0, infocount = 0; i < n_streams; i++) {
897     GstRTSPStreamTransport *trans;
898     GstRTSPStream *stream;
899     const GstRTSPTransport *tr;
900     gchar *uristr;
901     guint rtptime, seq;
902
903     /* get the transport, if there is no transport configured, skip this stream */
904     trans = gst_rtsp_session_media_get_transport (media, i);
905     if (trans == NULL) {
906       GST_INFO ("stream %d is not configured", i);
907       continue;
908     }
909     tr = gst_rtsp_stream_transport_get_transport (trans);
910
911     if (tr->lower_transport == GST_RTSP_LOWER_TRANS_TCP) {
912       /* for TCP, link the stream to the TCP connection of the client */
913       link_transport (client, session, trans);
914     }
915
916     stream = gst_rtsp_stream_transport_get_stream (trans);
917     if (gst_rtsp_stream_get_rtpinfo (stream, &rtptime, &seq)) {
918       if (infocount > 0)
919         g_string_append (rtpinfo, ", ");
920
921       uristr = gst_rtsp_url_get_request_uri (state->uri);
922       g_string_append_printf (rtpinfo, "url=%s/stream=%d;seq=%u;rtptime=%u",
923           uristr, i, seq, rtptime);
924       g_free (uristr);
925
926       infocount++;
927     } else {
928       GST_WARNING ("RTP-Info cannot be determined for stream %d", i);
929     }
930   }
931
932   /* construct the response now */
933   code = GST_RTSP_STS_OK;
934   gst_rtsp_message_init_response (state->response, code,
935       gst_rtsp_status_as_text (code), state->request);
936
937   /* add the RTP-Info header */
938   if (infocount > 0) {
939     str = g_string_free (rtpinfo, FALSE);
940     gst_rtsp_message_take_header (state->response, GST_RTSP_HDR_RTP_INFO, str);
941   } else {
942     g_string_free (rtpinfo, TRUE);
943   }
944
945   /* add the range */
946   str =
947       gst_rtsp_media_get_range_string (gst_rtsp_session_media_get_media (media),
948       TRUE, unit);
949   gst_rtsp_message_take_header (state->response, GST_RTSP_HDR_RANGE, str);
950
951   send_response (client, session, state->response, FALSE);
952
953   /* start playing after sending the request */
954   gst_rtsp_session_media_set_state (media, GST_STATE_PLAYING);
955
956   gst_rtsp_session_media_set_rtsp_state (media, GST_RTSP_STATE_PLAYING);
957
958   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_PLAY_REQUEST],
959       0, state);
960
961   return TRUE;
962
963   /* ERRORS */
964 no_session:
965   {
966     GST_ERROR ("client %p: no session", client);
967     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, state);
968     return FALSE;
969   }
970 not_found:
971   {
972     GST_ERROR ("client %p: media not found", client);
973     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, state);
974     return FALSE;
975   }
976 invalid_state:
977   {
978     GST_ERROR ("client %p: not PLAYING or READY", client);
979     send_generic_response (client, GST_RTSP_STS_METHOD_NOT_VALID_IN_THIS_STATE,
980         state);
981     return FALSE;
982   }
983 }
984
985 static void
986 do_keepalive (GstRTSPSession * session)
987 {
988   GST_INFO ("keep session %p alive", session);
989   gst_rtsp_session_touch (session);
990 }
991
992 /* parse @transport and return a valid transport in @tr. only transports
993  * from @supported are returned. Returns FALSE if no valid transport
994  * was found. */
995 static gboolean
996 parse_transport (const char *transport, GstRTSPLowerTrans supported,
997     GstRTSPTransport * tr)
998 {
999   gint i;
1000   gboolean res;
1001   gchar **transports;
1002
1003   res = FALSE;
1004   gst_rtsp_transport_init (tr);
1005
1006   GST_DEBUG ("parsing transports %s", transport);
1007
1008   transports = g_strsplit (transport, ",", 0);
1009
1010   /* loop through the transports, try to parse */
1011   for (i = 0; transports[i]; i++) {
1012     res = gst_rtsp_transport_parse (transports[i], tr);
1013     if (res != GST_RTSP_OK) {
1014       /* no valid transport, search some more */
1015       GST_WARNING ("could not parse transport %s", transports[i]);
1016       goto next;
1017     }
1018
1019     /* we have a transport, see if it's RTP/AVP */
1020     if (tr->trans != GST_RTSP_TRANS_RTP || tr->profile != GST_RTSP_PROFILE_AVP) {
1021       GST_WARNING ("invalid transport %s", transports[i]);
1022       goto next;
1023     }
1024
1025     if (!(tr->lower_transport & supported)) {
1026       GST_WARNING ("unsupported transport %s", transports[i]);
1027       goto next;
1028     }
1029
1030     /* we have a valid transport */
1031     GST_INFO ("found valid transport %s", transports[i]);
1032     res = TRUE;
1033     break;
1034
1035   next:
1036     gst_rtsp_transport_init (tr);
1037   }
1038   g_strfreev (transports);
1039
1040   return res;
1041 }
1042
1043 static gboolean
1044 handle_blocksize (GstRTSPMedia * media, GstRTSPStream * stream,
1045     GstRTSPMessage * request)
1046 {
1047   gchar *blocksize_str;
1048   gboolean ret = TRUE;
1049
1050   if (gst_rtsp_message_get_header (request, GST_RTSP_HDR_BLOCKSIZE,
1051           &blocksize_str, 0) == GST_RTSP_OK) {
1052     guint64 blocksize;
1053     gchar *end;
1054
1055     blocksize = g_ascii_strtoull (blocksize_str, &end, 10);
1056     if (end == blocksize_str) {
1057       GST_ERROR ("failed to parse blocksize");
1058       ret = FALSE;
1059     } else {
1060       /* we don't want to change the mtu when this media
1061        * can be shared because it impacts other clients */
1062       if (gst_rtsp_media_is_shared (media))
1063         return TRUE;
1064
1065       if (blocksize > G_MAXUINT)
1066         blocksize = G_MAXUINT;
1067       gst_rtsp_stream_set_mtu (stream, blocksize);
1068     }
1069   }
1070   return ret;
1071 }
1072
1073 static gboolean
1074 configure_client_transport (GstRTSPClient * client, GstRTSPClientState * state,
1075     GstRTSPTransport * ct)
1076 {
1077   GstRTSPClientPrivate *priv = client->priv;
1078
1079   /* we have a valid transport now, set the destination of the client. */
1080   if (ct->lower_transport == GST_RTSP_LOWER_TRANS_UDP_MCAST) {
1081     if (ct->destination && priv->use_client_settings) {
1082       GstRTSPAddress *addr;
1083
1084       addr = gst_rtsp_stream_reserve_address (state->stream, ct->destination,
1085           ct->port.min, ct->port.max - ct->port.min + 1, ct->ttl);
1086
1087       if (addr == NULL)
1088         goto no_address;
1089
1090       gst_rtsp_address_free (addr);
1091     } else {
1092       GstRTSPAddress *addr;
1093
1094       addr = gst_rtsp_stream_get_address (state->stream);
1095       if (addr == NULL)
1096         goto no_address;
1097
1098       g_free (ct->destination);
1099       ct->destination = g_strdup (addr->address);
1100       ct->port.min = addr->port;
1101       ct->port.max = addr->port + addr->n_ports - 1;
1102       ct->ttl = addr->ttl;
1103
1104       gst_rtsp_address_free (addr);
1105     }
1106   } else {
1107     GstRTSPUrl *url;
1108
1109     url = gst_rtsp_connection_get_url (priv->connection);
1110     g_free (ct->destination);
1111     ct->destination = g_strdup (url->host);
1112
1113     if (ct->lower_transport & GST_RTSP_LOWER_TRANS_TCP) {
1114       /* check if the client selected channels for TCP */
1115       if (ct->interleaved.min == -1 || ct->interleaved.max == -1) {
1116         gst_rtsp_session_media_alloc_channels (state->sessmedia,
1117             &ct->interleaved);
1118       }
1119     }
1120   }
1121   return TRUE;
1122
1123   /* ERRORS */
1124 no_address:
1125   {
1126     GST_ERROR_OBJECT (client, "failed to acquire address for stream");
1127     return FALSE;
1128   }
1129 }
1130
1131 static GstRTSPTransport *
1132 make_server_transport (GstRTSPClient * client, GstRTSPClientState * state,
1133     GstRTSPTransport * ct)
1134 {
1135   GstRTSPTransport *st;
1136   GInetAddress *addr;
1137   GSocketFamily family;
1138
1139   /* prepare the server transport */
1140   gst_rtsp_transport_new (&st);
1141
1142   st->trans = ct->trans;
1143   st->profile = ct->profile;
1144   st->lower_transport = ct->lower_transport;
1145
1146   addr = g_inet_address_new_from_string (ct->destination);
1147
1148   if (!addr) {
1149     GST_ERROR ("failed to get inet addr from client destination");
1150     family = G_SOCKET_FAMILY_IPV4;
1151   } else {
1152     family = g_inet_address_get_family (addr);
1153     g_object_unref (addr);
1154     addr = NULL;
1155   }
1156
1157   switch (st->lower_transport) {
1158     case GST_RTSP_LOWER_TRANS_UDP:
1159       st->client_port = ct->client_port;
1160       gst_rtsp_stream_get_server_port (state->stream, &st->server_port, 
1161           family);
1162       break;
1163     case GST_RTSP_LOWER_TRANS_UDP_MCAST:
1164       st->port = ct->port;
1165       st->destination = g_strdup (ct->destination);
1166       st->ttl = ct->ttl;
1167       break;
1168     case GST_RTSP_LOWER_TRANS_TCP:
1169       st->interleaved = ct->interleaved;
1170     default:
1171       break;
1172   }
1173
1174   gst_rtsp_stream_get_ssrc (state->stream, &st->ssrc);
1175
1176   return st;
1177 }
1178
1179 static gboolean
1180 handle_setup_request (GstRTSPClient * client, GstRTSPClientState * state)
1181 {
1182   GstRTSPClientPrivate *priv = client->priv;
1183   GstRTSPResult res;
1184   GstRTSPUrl *uri;
1185   gchar *transport;
1186   GstRTSPTransport *ct, *st;
1187   GstRTSPLowerTrans supported;
1188   GstRTSPStatusCode code;
1189   GstRTSPSession *session;
1190   GstRTSPStreamTransport *trans;
1191   gchar *trans_str, *pos;
1192   guint streamid;
1193   GstRTSPSessionMedia *sessmedia;
1194   GstRTSPMedia *media;
1195   GstRTSPStream *stream;
1196   GstRTSPState rtspstate;
1197
1198   uri = state->uri;
1199
1200   /* the uri contains the stream number we added in the SDP config, which is
1201    * always /stream=%d so we need to strip that off
1202    * parse the stream we need to configure, look for the stream in the abspath
1203    * first and then in the query. */
1204   if (uri->abspath == NULL || !(pos = strstr (uri->abspath, "/stream="))) {
1205     if (uri->query == NULL || !(pos = strstr (uri->query, "/stream=")))
1206       goto bad_request;
1207   }
1208
1209   /* we can mofify the parsed uri in place */
1210   *pos = '\0';
1211
1212   pos += strlen ("/stream=");
1213   if (sscanf (pos, "%u", &streamid) != 1)
1214     goto bad_request;
1215
1216   /* parse the transport */
1217   res =
1218       gst_rtsp_message_get_header (state->request, GST_RTSP_HDR_TRANSPORT,
1219       &transport, 0);
1220   if (res != GST_RTSP_OK)
1221     goto no_transport;
1222
1223   gst_rtsp_transport_new (&ct);
1224
1225   /* our supported transports */
1226   supported = GST_RTSP_LOWER_TRANS_UDP |
1227       GST_RTSP_LOWER_TRANS_UDP_MCAST | GST_RTSP_LOWER_TRANS_TCP;
1228
1229   /* parse and find a usable supported transport */
1230   if (!parse_transport (transport, supported, ct))
1231     goto unsupported_transports;
1232
1233   /* we create the session after parsing stuff so that we don't make
1234    * a session for malformed requests */
1235   if (priv->session_pool == NULL)
1236     goto no_pool;
1237
1238   session = state->session;
1239
1240   if (session) {
1241     g_object_ref (session);
1242     /* get a handle to the configuration of the media in the session, this can
1243      * return NULL if this is a new url to manage in this session. */
1244     sessmedia = gst_rtsp_session_get_media (session, uri);
1245   } else {
1246     /* create a session if this fails we probably reached our session limit or
1247      * something. */
1248     if (!(session = gst_rtsp_session_pool_create (priv->session_pool)))
1249       goto service_unavailable;
1250
1251     state->session = session;
1252
1253     /* we need a new media configuration in this session */
1254     sessmedia = NULL;
1255   }
1256
1257   /* we have no media, find one and manage it */
1258   if (sessmedia == NULL) {
1259     /* get a handle to the configuration of the media in the session */
1260     if ((media = find_media (client, state))) {
1261       /* manage the media in our session now */
1262       sessmedia = gst_rtsp_session_manage_media (session, uri, media);
1263     }
1264   }
1265
1266   /* if we stil have no media, error */
1267   if (sessmedia == NULL)
1268     goto not_found;
1269
1270   state->sessmedia = sessmedia;
1271   state->media = media = gst_rtsp_session_media_get_media (sessmedia);
1272
1273   /* now get the stream */
1274   stream = gst_rtsp_media_get_stream (media, streamid);
1275   if (stream == NULL)
1276     goto not_found;
1277
1278   state->stream = stream;
1279
1280   /* set blocksize on this stream */
1281   if (!handle_blocksize (media, stream, state->request))
1282     goto invalid_blocksize;
1283
1284   /* update the client transport */
1285   if (!configure_client_transport (client, state, ct))
1286     goto unsupported_client_transport;
1287
1288   /* set in the session media transport */
1289   trans = gst_rtsp_session_media_set_transport (sessmedia, stream, ct);
1290
1291   /* configure keepalive for this transport */
1292   gst_rtsp_stream_transport_set_keepalive (trans,
1293       (GstRTSPKeepAliveFunc) do_keepalive, session, NULL);
1294
1295   /* create and serialize the server transport */
1296   st = make_server_transport (client, state, ct);
1297   trans_str = gst_rtsp_transport_as_text (st);
1298   gst_rtsp_transport_free (st);
1299
1300   /* construct the response now */
1301   code = GST_RTSP_STS_OK;
1302   gst_rtsp_message_init_response (state->response, code,
1303       gst_rtsp_status_as_text (code), state->request);
1304
1305   gst_rtsp_message_add_header (state->response, GST_RTSP_HDR_TRANSPORT,
1306       trans_str);
1307   g_free (trans_str);
1308
1309   send_response (client, session, state->response, FALSE);
1310
1311   /* update the state */
1312   rtspstate = gst_rtsp_session_media_get_rtsp_state (sessmedia);
1313   switch (rtspstate) {
1314     case GST_RTSP_STATE_PLAYING:
1315     case GST_RTSP_STATE_RECORDING:
1316     case GST_RTSP_STATE_READY:
1317       /* no state change */
1318       break;
1319     default:
1320       gst_rtsp_session_media_set_rtsp_state (sessmedia, GST_RTSP_STATE_READY);
1321       break;
1322   }
1323   g_object_unref (session);
1324
1325   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_SETUP_REQUEST],
1326       0, state);
1327
1328   return TRUE;
1329
1330   /* ERRORS */
1331 bad_request:
1332   {
1333     GST_ERROR ("client %p: bad request", client);
1334     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, state);
1335     return FALSE;
1336   }
1337 not_found:
1338   {
1339     GST_ERROR ("client %p: media not found", client);
1340     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, state);
1341     g_object_unref (session);
1342     gst_rtsp_transport_free (ct);
1343     return FALSE;
1344   }
1345 invalid_blocksize:
1346   {
1347     GST_ERROR ("client %p: invalid blocksize", client);
1348     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, state);
1349     g_object_unref (session);
1350     gst_rtsp_transport_free (ct);
1351     return FALSE;
1352   }
1353 unsupported_client_transport:
1354   {
1355     GST_ERROR ("client %p: unsupported client transport", client);
1356     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, state);
1357     g_object_unref (session);
1358     gst_rtsp_transport_free (ct);
1359     return FALSE;
1360   }
1361 no_transport:
1362   {
1363     GST_ERROR ("client %p: no transport", client);
1364     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, state);
1365     return FALSE;
1366   }
1367 unsupported_transports:
1368   {
1369     GST_ERROR ("client %p: unsupported transports", client);
1370     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, state);
1371     gst_rtsp_transport_free (ct);
1372     return FALSE;
1373   }
1374 no_pool:
1375   {
1376     GST_ERROR ("client %p: no session pool configured", client);
1377     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, state);
1378     gst_rtsp_transport_free (ct);
1379     return FALSE;
1380   }
1381 service_unavailable:
1382   {
1383     GST_ERROR ("client %p: can't create session", client);
1384     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, state);
1385     gst_rtsp_transport_free (ct);
1386     return FALSE;
1387   }
1388 }
1389
1390 static GstSDPMessage *
1391 create_sdp (GstRTSPClient * client, GstRTSPMedia * media)
1392 {
1393   GstRTSPClientPrivate *priv = client->priv;
1394   GstSDPMessage *sdp;
1395   GstSDPInfo info;
1396   const gchar *proto;
1397
1398   gst_sdp_message_new (&sdp);
1399
1400   /* some standard things first */
1401   gst_sdp_message_set_version (sdp, "0");
1402
1403   if (priv->is_ipv6)
1404     proto = "IP6";
1405   else
1406     proto = "IP4";
1407
1408   gst_sdp_message_set_origin (sdp, "-", "1188340656180883", "1", "IN", proto,
1409       priv->server_ip);
1410
1411   gst_sdp_message_set_session_name (sdp, "Session streamed with GStreamer");
1412   gst_sdp_message_set_information (sdp, "rtsp-server");
1413   gst_sdp_message_add_time (sdp, "0", "0", NULL);
1414   gst_sdp_message_add_attribute (sdp, "tool", "GStreamer");
1415   gst_sdp_message_add_attribute (sdp, "type", "broadcast");
1416   gst_sdp_message_add_attribute (sdp, "control", "*");
1417
1418   info.server_proto = proto;
1419   info.server_ip = g_strdup (priv->server_ip);
1420
1421   /* create an SDP for the media object */
1422   if (!gst_rtsp_sdp_from_media (sdp, &info, media))
1423     goto no_sdp;
1424
1425   g_free (info.server_ip);
1426
1427   return sdp;
1428
1429   /* ERRORS */
1430 no_sdp:
1431   {
1432     GST_ERROR ("client %p: could not create SDP", client);
1433     g_free (info.server_ip);
1434     gst_sdp_message_free (sdp);
1435     return NULL;
1436   }
1437 }
1438
1439 /* for the describe we must generate an SDP */
1440 static gboolean
1441 handle_describe_request (GstRTSPClient * client, GstRTSPClientState * state)
1442 {
1443   GstRTSPResult res;
1444   GstSDPMessage *sdp;
1445   guint i, str_len;
1446   gchar *str, *content_base;
1447   GstRTSPMedia *media;
1448   GstRTSPClientClass *klass;
1449
1450   klass = GST_RTSP_CLIENT_GET_CLASS (client);
1451
1452   /* check what kind of format is accepted, we don't really do anything with it
1453    * and always return SDP for now. */
1454   for (i = 0; i++;) {
1455     gchar *accept;
1456
1457     res =
1458         gst_rtsp_message_get_header (state->request, GST_RTSP_HDR_ACCEPT,
1459         &accept, i);
1460     if (res == GST_RTSP_ENOTIMPL)
1461       break;
1462
1463     if (g_ascii_strcasecmp (accept, "application/sdp") == 0)
1464       break;
1465   }
1466
1467   /* find the media object for the uri */
1468   if (!(media = find_media (client, state)))
1469     goto no_media;
1470
1471   /* create an SDP for the media object on this client */
1472   if (!(sdp = klass->create_sdp (client, media)))
1473     goto no_sdp;
1474
1475   g_object_unref (media);
1476
1477   gst_rtsp_message_init_response (state->response, GST_RTSP_STS_OK,
1478       gst_rtsp_status_as_text (GST_RTSP_STS_OK), state->request);
1479
1480   gst_rtsp_message_add_header (state->response, GST_RTSP_HDR_CONTENT_TYPE,
1481       "application/sdp");
1482
1483   /* content base for some clients that might screw up creating the setup uri */
1484   str = gst_rtsp_url_get_request_uri (state->uri);
1485   str_len = strlen (str);
1486
1487   /* check for trailing '/' and append one */
1488   if (str[str_len - 1] != '/') {
1489     content_base = g_malloc (str_len + 2);
1490     memcpy (content_base, str, str_len);
1491     content_base[str_len] = '/';
1492     content_base[str_len + 1] = '\0';
1493     g_free (str);
1494   } else {
1495     content_base = str;
1496   }
1497
1498   GST_INFO ("adding content-base: %s", content_base);
1499
1500   gst_rtsp_message_add_header (state->response, GST_RTSP_HDR_CONTENT_BASE,
1501       content_base);
1502   g_free (content_base);
1503
1504   /* add SDP to the response body */
1505   str = gst_sdp_message_as_text (sdp);
1506   gst_rtsp_message_take_body (state->response, (guint8 *) str, strlen (str));
1507   gst_sdp_message_free (sdp);
1508
1509   send_response (client, state->session, state->response, FALSE);
1510
1511   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_DESCRIBE_REQUEST],
1512       0, state);
1513
1514   return TRUE;
1515
1516   /* ERRORS */
1517 no_media:
1518   {
1519     GST_ERROR ("client %p: no media", client);
1520     /* error reply is already sent */
1521     return FALSE;
1522   }
1523 no_sdp:
1524   {
1525     GST_ERROR ("client %p: can't create SDP", client);
1526     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, state);
1527     g_object_unref (media);
1528     return FALSE;
1529   }
1530 }
1531
1532 static gboolean
1533 handle_options_request (GstRTSPClient * client, GstRTSPClientState * state)
1534 {
1535   GstRTSPMethod options;
1536   gchar *str;
1537
1538   options = GST_RTSP_DESCRIBE |
1539       GST_RTSP_OPTIONS |
1540       GST_RTSP_PAUSE |
1541       GST_RTSP_PLAY |
1542       GST_RTSP_SETUP |
1543       GST_RTSP_GET_PARAMETER | GST_RTSP_SET_PARAMETER | GST_RTSP_TEARDOWN;
1544
1545   str = gst_rtsp_options_as_text (options);
1546
1547   gst_rtsp_message_init_response (state->response, GST_RTSP_STS_OK,
1548       gst_rtsp_status_as_text (GST_RTSP_STS_OK), state->request);
1549
1550   gst_rtsp_message_add_header (state->response, GST_RTSP_HDR_PUBLIC, str);
1551   g_free (str);
1552
1553   send_response (client, state->session, state->response, FALSE);
1554
1555   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_OPTIONS_REQUEST],
1556       0, state);
1557
1558   return TRUE;
1559 }
1560
1561 /* remove duplicate and trailing '/' */
1562 static void
1563 sanitize_uri (GstRTSPUrl * uri)
1564 {
1565   gint i, len;
1566   gchar *s, *d;
1567   gboolean have_slash, prev_slash;
1568
1569   s = d = uri->abspath;
1570   len = strlen (uri->abspath);
1571
1572   prev_slash = FALSE;
1573
1574   for (i = 0; i < len; i++) {
1575     have_slash = s[i] == '/';
1576     *d = s[i];
1577     if (!have_slash || !prev_slash)
1578       d++;
1579     prev_slash = have_slash;
1580   }
1581   len = d - uri->abspath;
1582   /* don't remove the first slash if that's the only thing left */
1583   if (len > 1 && *(d - 1) == '/')
1584     d--;
1585   *d = '\0';
1586 }
1587
1588 static void
1589 client_session_finalized (GstRTSPClient * client, GstRTSPSession * session)
1590 {
1591   GstRTSPClientPrivate *priv = client->priv;
1592
1593   GST_INFO ("client %p: session %p finished", client, session);
1594
1595   /* unlink all media managed in this session */
1596   client_unlink_session (client, session);
1597
1598   /* remove the session */
1599   if (!(priv->sessions = g_list_remove (priv->sessions, session))) {
1600     GST_INFO ("client %p: all sessions finalized, close the connection",
1601         client);
1602     close_connection (client);
1603   }
1604 }
1605
1606 static void
1607 client_watch_session (GstRTSPClient * client, GstRTSPSession * session)
1608 {
1609   GstRTSPClientPrivate *priv = client->priv;
1610   GList *walk;
1611
1612   for (walk = priv->sessions; walk; walk = g_list_next (walk)) {
1613     GstRTSPSession *msession = (GstRTSPSession *) walk->data;
1614
1615     /* we already know about this session */
1616     if (msession == session)
1617       return;
1618   }
1619
1620   GST_INFO ("watching session %p", session);
1621
1622   g_object_weak_ref (G_OBJECT (session), (GWeakNotify) client_session_finalized,
1623       client);
1624   priv->sessions = g_list_prepend (priv->sessions, session);
1625
1626   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_NEW_SESSION], 0,
1627       session);
1628 }
1629
1630 static void
1631 handle_request (GstRTSPClient * client, GstRTSPMessage * request)
1632 {
1633   GstRTSPClientPrivate *priv = client->priv;
1634   GstRTSPMethod method;
1635   const gchar *uristr;
1636   GstRTSPUrl *uri = NULL;
1637   GstRTSPVersion version;
1638   GstRTSPResult res;
1639   GstRTSPSession *session = NULL;
1640   GstRTSPClientState state = { NULL };
1641   GstRTSPMessage response = { 0 };
1642   gchar *sessid;
1643
1644   state.request = request;
1645   state.response = &response;
1646
1647   if (gst_debug_category_get_threshold (rtsp_client_debug) >= GST_LEVEL_LOG) {
1648     gst_rtsp_message_dump (request);
1649   }
1650
1651   GST_INFO ("client %p: received a request", client);
1652
1653   gst_rtsp_message_parse_request (request, &method, &uristr, &version);
1654
1655   /* we can only handle 1.0 requests */
1656   if (version != GST_RTSP_VERSION_1_0)
1657     goto not_supported;
1658
1659   state.method = method;
1660
1661   /* we always try to parse the url first */
1662   if (gst_rtsp_url_parse (uristr, &uri) != GST_RTSP_OK)
1663     goto bad_request;
1664
1665   /* get the session if there is any */
1666   res = gst_rtsp_message_get_header (request, GST_RTSP_HDR_SESSION, &sessid, 0);
1667   if (res == GST_RTSP_OK) {
1668     if (priv->session_pool == NULL)
1669       goto no_pool;
1670
1671     /* we had a session in the request, find it again */
1672     if (!(session = gst_rtsp_session_pool_find (priv->session_pool, sessid)))
1673       goto session_not_found;
1674
1675     /* we add the session to the client list of watched sessions. When a session
1676      * disappears because it times out, we will be notified. If all sessions are
1677      * gone, we will close the connection */
1678     client_watch_session (client, session);
1679   }
1680
1681   /* sanitize the uri */
1682   sanitize_uri (uri);
1683   state.uri = uri;
1684   state.session = session;
1685
1686   if (priv->auth) {
1687     if (!gst_rtsp_auth_check (priv->auth, client, 0, &state))
1688       goto not_authorized;
1689   }
1690
1691   /* now see what is asked and dispatch to a dedicated handler */
1692   switch (method) {
1693     case GST_RTSP_OPTIONS:
1694       handle_options_request (client, &state);
1695       break;
1696     case GST_RTSP_DESCRIBE:
1697       handle_describe_request (client, &state);
1698       break;
1699     case GST_RTSP_SETUP:
1700       handle_setup_request (client, &state);
1701       break;
1702     case GST_RTSP_PLAY:
1703       handle_play_request (client, &state);
1704       break;
1705     case GST_RTSP_PAUSE:
1706       handle_pause_request (client, &state);
1707       break;
1708     case GST_RTSP_TEARDOWN:
1709       handle_teardown_request (client, &state);
1710       break;
1711     case GST_RTSP_SET_PARAMETER:
1712       handle_set_param_request (client, &state);
1713       break;
1714     case GST_RTSP_GET_PARAMETER:
1715       handle_get_param_request (client, &state);
1716       break;
1717     case GST_RTSP_ANNOUNCE:
1718     case GST_RTSP_RECORD:
1719     case GST_RTSP_REDIRECT:
1720       goto not_implemented;
1721     case GST_RTSP_INVALID:
1722     default:
1723       goto bad_request;
1724   }
1725
1726 done:
1727   if (session)
1728     g_object_unref (session);
1729   if (uri)
1730     gst_rtsp_url_free (uri);
1731   return;
1732
1733   /* ERRORS */
1734 not_supported:
1735   {
1736     GST_ERROR ("client %p: version %d not supported", client, version);
1737     send_generic_response (client, GST_RTSP_STS_RTSP_VERSION_NOT_SUPPORTED,
1738         &state);
1739     goto done;
1740   }
1741 bad_request:
1742   {
1743     GST_ERROR ("client %p: bad request", client);
1744     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, &state);
1745     goto done;
1746   }
1747 no_pool:
1748   {
1749     GST_ERROR ("client %p: no pool configured", client);
1750     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, &state);
1751     goto done;
1752   }
1753 session_not_found:
1754   {
1755     GST_ERROR ("client %p: session not found", client);
1756     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, &state);
1757     goto done;
1758   }
1759 not_authorized:
1760   {
1761     GST_ERROR ("client %p: not allowed", client);
1762     handle_unauthorized_request (client, priv->auth, &state);
1763     goto done;
1764   }
1765 not_implemented:
1766   {
1767     GST_ERROR ("client %p: method %d not implemented", client, method);
1768     send_generic_response (client, GST_RTSP_STS_NOT_IMPLEMENTED, &state);
1769     goto done;
1770   }
1771 }
1772
1773 static void
1774 handle_data (GstRTSPClient * client, GstRTSPMessage * message)
1775 {
1776   GstRTSPClientPrivate *priv = client->priv;
1777   GstRTSPResult res;
1778   guint8 channel;
1779   GList *walk;
1780   guint8 *data;
1781   guint size;
1782   GstBuffer *buffer;
1783   gboolean handled;
1784
1785   /* find the stream for this message */
1786   res = gst_rtsp_message_parse_data (message, &channel);
1787   if (res != GST_RTSP_OK)
1788     return;
1789
1790   gst_rtsp_message_steal_body (message, &data, &size);
1791
1792   buffer = gst_buffer_new_wrapped (data, size);
1793
1794   handled = FALSE;
1795   for (walk = priv->transports; walk; walk = g_list_next (walk)) {
1796     GstRTSPStreamTransport *trans;
1797     GstRTSPStream *stream;
1798     const GstRTSPTransport *tr;
1799
1800     trans = walk->data;
1801
1802     tr = gst_rtsp_stream_transport_get_transport (trans);
1803     stream = gst_rtsp_stream_transport_get_stream (trans);
1804
1805     /* check for TCP transport */
1806     if (tr->lower_transport == GST_RTSP_LOWER_TRANS_TCP) {
1807       /* dispatch to the stream based on the channel number */
1808       if (tr->interleaved.min == channel) {
1809         gst_rtsp_stream_recv_rtp (stream, buffer);
1810         handled = TRUE;
1811         break;
1812       } else if (tr->interleaved.max == channel) {
1813         gst_rtsp_stream_recv_rtcp (stream, buffer);
1814         handled = TRUE;
1815         break;
1816       }
1817     }
1818   }
1819   if (!handled)
1820     gst_buffer_unref (buffer);
1821 }
1822
1823 /**
1824  * gst_rtsp_client_set_session_pool:
1825  * @client: a #GstRTSPClient
1826  * @pool: a #GstRTSPSessionPool
1827  *
1828  * Set @pool as the sessionpool for @client which it will use to find
1829  * or allocate sessions. the sessionpool is usually inherited from the server
1830  * that created the client but can be overridden later.
1831  */
1832 void
1833 gst_rtsp_client_set_session_pool (GstRTSPClient * client,
1834     GstRTSPSessionPool * pool)
1835 {
1836   GstRTSPSessionPool *old;
1837   GstRTSPClientPrivate *priv;
1838
1839   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
1840
1841   priv = client->priv;
1842
1843   if (pool)
1844     g_object_ref (pool);
1845
1846   g_mutex_lock (&priv->lock);
1847   old = priv->session_pool;
1848   priv->session_pool = pool;
1849   g_mutex_unlock (&priv->lock);
1850
1851   if (old)
1852     g_object_unref (old);
1853 }
1854
1855 /**
1856  * gst_rtsp_client_get_session_pool:
1857  * @client: a #GstRTSPClient
1858  *
1859  * Get the #GstRTSPSessionPool object that @client uses to manage its sessions.
1860  *
1861  * Returns: (transfer full): a #GstRTSPSessionPool, unref after usage.
1862  */
1863 GstRTSPSessionPool *
1864 gst_rtsp_client_get_session_pool (GstRTSPClient * client)
1865 {
1866   GstRTSPClientPrivate *priv;
1867   GstRTSPSessionPool *result;
1868
1869   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
1870
1871   priv = client->priv;
1872
1873   g_mutex_lock (&priv->lock);
1874   if ((result = priv->session_pool))
1875     g_object_ref (result);
1876   g_mutex_unlock (&priv->lock);
1877
1878   return result;
1879 }
1880
1881 /**
1882  * gst_rtsp_client_set_mount_points:
1883  * @client: a #GstRTSPClient
1884  * @mounts: a #GstRTSPMountPoints
1885  *
1886  * Set @mounts as the mount points for @client which it will use to map urls
1887  * to media streams. These mount points are usually inherited from the server that
1888  * created the client but can be overriden later.
1889  */
1890 void
1891 gst_rtsp_client_set_mount_points (GstRTSPClient * client,
1892     GstRTSPMountPoints * mounts)
1893 {
1894   GstRTSPClientPrivate *priv;
1895   GstRTSPMountPoints *old;
1896
1897   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
1898
1899   priv = client->priv;
1900
1901   if (mounts)
1902     g_object_ref (mounts);
1903
1904   g_mutex_lock (&priv->lock);
1905   old = priv->mount_points;
1906   priv->mount_points = mounts;
1907   g_mutex_unlock (&priv->lock);
1908
1909   if (old)
1910     g_object_unref (old);
1911 }
1912
1913 /**
1914  * gst_rtsp_client_get_mount_points:
1915  * @client: a #GstRTSPClient
1916  *
1917  * Get the #GstRTSPMountPoints object that @client uses to manage its sessions.
1918  *
1919  * Returns: (transfer full): a #GstRTSPMountPoints, unref after usage.
1920  */
1921 GstRTSPMountPoints *
1922 gst_rtsp_client_get_mount_points (GstRTSPClient * client)
1923 {
1924   GstRTSPClientPrivate *priv;
1925   GstRTSPMountPoints *result;
1926
1927   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
1928
1929   priv = client->priv;
1930
1931   g_mutex_lock (&priv->lock);
1932   if ((result = priv->mount_points))
1933     g_object_ref (result);
1934   g_mutex_unlock (&priv->lock);
1935
1936   return result;
1937 }
1938
1939 /**
1940  * gst_rtsp_client_set_use_client_settings:
1941  * @client: a #GstRTSPClient
1942  * @use_client_settings: whether to use client settings for multicast
1943  *
1944  * Use client transport settings (destination and ttl) for multicast.
1945  * When @use_client_settings is %FALSE, the server settings will be
1946  * used.
1947  */
1948 void
1949 gst_rtsp_client_set_use_client_settings (GstRTSPClient * client,
1950     gboolean use_client_settings)
1951 {
1952   GstRTSPClientPrivate *priv;
1953
1954   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
1955
1956   priv = client->priv;
1957
1958   g_mutex_lock (&priv->lock);
1959   priv->use_client_settings = use_client_settings;
1960   g_mutex_unlock (&priv->lock);
1961 }
1962
1963 /**
1964  * gst_rtsp_client_get_use_client_settings:
1965  * @client: a #GstRTSPClient
1966  *
1967  * Check if client transport settings (destination and ttl) for multicast
1968  * will be used.
1969  */
1970 gboolean
1971 gst_rtsp_client_get_use_client_settings (GstRTSPClient * client)
1972 {
1973   GstRTSPClientPrivate *priv;
1974   gboolean res;
1975
1976   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), FALSE);
1977
1978   priv = client->priv;
1979
1980   g_mutex_lock (&priv->lock);
1981   res = priv->use_client_settings;
1982   g_mutex_unlock (&priv->lock);
1983
1984   return res;
1985 }
1986
1987 /**
1988  * gst_rtsp_client_set_auth:
1989  * @client: a #GstRTSPClient
1990  * @auth: a #GstRTSPAuth
1991  *
1992  * configure @auth to be used as the authentication manager of @client.
1993  */
1994 void
1995 gst_rtsp_client_set_auth (GstRTSPClient * client, GstRTSPAuth * auth)
1996 {
1997   GstRTSPClientPrivate *priv;
1998   GstRTSPAuth *old;
1999
2000   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2001
2002   priv = client->priv;
2003
2004   if (auth)
2005     g_object_ref (auth);
2006
2007   g_mutex_lock (&priv->lock);
2008   old = priv->auth;
2009   priv->auth = auth;
2010   g_mutex_unlock (&priv->lock);
2011
2012   if (old)
2013     g_object_unref (old);
2014 }
2015
2016
2017 /**
2018  * gst_rtsp_client_get_auth:
2019  * @client: a #GstRTSPClient
2020  *
2021  * Get the #GstRTSPAuth used as the authentication manager of @client.
2022  *
2023  * Returns: (transfer full): the #GstRTSPAuth of @client. g_object_unref() after
2024  * usage.
2025  */
2026 GstRTSPAuth *
2027 gst_rtsp_client_get_auth (GstRTSPClient * client)
2028 {
2029   GstRTSPClientPrivate *priv;
2030   GstRTSPAuth *result;
2031
2032   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2033
2034   priv = client->priv;
2035
2036   g_mutex_lock (&priv->lock);
2037   if ((result = priv->auth))
2038     g_object_ref (result);
2039   g_mutex_unlock (&priv->lock);
2040
2041   return result;
2042 }
2043
2044 /**
2045  * gst_rtsp_client_get_uri:
2046  * @client: a #GstRTSPClient
2047  *
2048  * Get the #GstRTSPUrl of @client.
2049  *
2050  * Returns: (transfer full): the #GstRTSPUrl of @client. Free with
2051  * gst_rtsp_url_free () after usage.
2052  */
2053 GstRTSPUrl *
2054 gst_rtsp_client_get_uri (GstRTSPClient * client)
2055 {
2056   GstRTSPClientPrivate *priv;
2057   GstRTSPUrl *result = NULL;
2058
2059   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2060
2061   priv = client->priv;
2062
2063   g_mutex_lock (&priv->lock);
2064   if (priv->uri != NULL)
2065     result = gst_rtsp_url_copy (priv->uri);
2066   g_mutex_unlock (&priv->lock);
2067
2068   return result;
2069 }
2070
2071 /**
2072  * gst_rtsp_client_set_connection:
2073  * @client: a #GstRTSPClient
2074  * @conn: (transfer full): a #GstRTSPConnection
2075  *
2076  * Set the #GstRTSPConnection of @client. This function takes ownership of
2077  * @conn.
2078  *
2079  * Returns: %TRUE on success.
2080  */
2081 gboolean
2082 gst_rtsp_client_set_connection (GstRTSPClient * client,
2083     GstRTSPConnection * conn)
2084 {
2085   GstRTSPClientPrivate *priv;
2086   GSocket *read_socket;
2087   GSocketAddress *address;
2088   GstRTSPUrl *url;
2089   GError *error = NULL;
2090
2091   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), FALSE);
2092   g_return_val_if_fail (conn != NULL, FALSE);
2093
2094   priv = client->priv;
2095
2096   read_socket = gst_rtsp_connection_get_read_socket (conn);
2097
2098   if (!(address = g_socket_get_local_address (read_socket, &error)))
2099     goto no_address;
2100
2101   g_free (priv->server_ip);
2102   /* keep the original ip that the client connected to */
2103   if (G_IS_INET_SOCKET_ADDRESS (address)) {
2104     GInetAddress *iaddr;
2105
2106     iaddr = g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (address));
2107
2108     /* socket might be ipv6 but adress still ipv4 */
2109     priv->is_ipv6 = g_inet_address_get_family (iaddr) == G_SOCKET_FAMILY_IPV6;
2110     priv->server_ip = g_inet_address_to_string (iaddr);
2111     g_object_unref (address);
2112   } else {
2113     priv->is_ipv6 = g_socket_get_family (read_socket) == G_SOCKET_FAMILY_IPV6;
2114     priv->server_ip = g_strdup ("unknown");
2115   }
2116
2117   GST_INFO ("client %p connected to server ip %s, ipv6 = %d", client,
2118       priv->server_ip, priv->is_ipv6);
2119
2120   url = gst_rtsp_connection_get_url (conn);
2121   GST_INFO ("added new client %p ip %s:%d", client, url->host, url->port);
2122
2123   priv->connection = conn;
2124
2125   return TRUE;
2126
2127   /* ERRORS */
2128 no_address:
2129   {
2130     GST_ERROR ("could not get remote address %s", error->message);
2131     g_error_free (error);
2132     return FALSE;
2133   }
2134 }
2135
2136 /**
2137  * gst_rtsp_client_get_connection:
2138  * @client: a #GstRTSPClient
2139  *
2140  * Get the #GstRTSPConnection of @client.
2141  *
2142  * Returns: (transfer none): the #GstRTSPConnection of @client.
2143  * The connection object returned remains valid until the client is freed.
2144  */
2145 GstRTSPConnection *
2146 gst_rtsp_client_get_connection (GstRTSPClient * client)
2147 {
2148   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2149
2150   return client->priv->connection;
2151 }
2152
2153 /**
2154  * gst_rtsp_client_set_send_func:
2155  * @client: a #GstRTSPClient
2156  * @func: a #GstRTSPClientSendFunc
2157  * @user_data: user data passed to @func
2158  * @notify: called when @user_data is no longer in use
2159  *
2160  * Set @func as the callback that will be called when a new message needs to be
2161  * sent to the client. @user_data is passed to @func and @notify is called when
2162  * @user_data is no longer in use.
2163  */
2164 void
2165 gst_rtsp_client_set_send_func (GstRTSPClient * client,
2166     GstRTSPClientSendFunc func, gpointer user_data, GDestroyNotify notify)
2167 {
2168   GstRTSPClientPrivate *priv;
2169   GDestroyNotify old_notify;
2170   gpointer old_data;
2171
2172   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2173
2174   priv = client->priv;
2175
2176   g_mutex_lock (&priv->send_lock);
2177   priv->send_func = func;
2178   old_notify = priv->send_notify;
2179   old_data = priv->send_data;
2180   priv->send_notify = notify;
2181   priv->send_data = user_data;
2182   g_mutex_unlock (&priv->send_lock);
2183
2184   if (old_notify)
2185     old_notify (old_data);
2186 }
2187
2188 /**
2189  * gst_rtsp_client_handle_message:
2190  * @client: a #GstRTSPClient
2191  * @message: an #GstRTSPMessage
2192  *
2193  * Let the client handle @message.
2194  *
2195  * Returns: a #GstRTSPResult.
2196  */
2197 GstRTSPResult
2198 gst_rtsp_client_handle_message (GstRTSPClient * client,
2199     GstRTSPMessage * message)
2200 {
2201   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), GST_RTSP_EINVAL);
2202   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2203
2204   switch (message->type) {
2205     case GST_RTSP_MESSAGE_REQUEST:
2206       handle_request (client, message);
2207       break;
2208     case GST_RTSP_MESSAGE_RESPONSE:
2209       break;
2210     case GST_RTSP_MESSAGE_DATA:
2211       handle_data (client, message);
2212       break;
2213     default:
2214       break;
2215   }
2216   return GST_RTSP_OK;
2217 }
2218
2219 static GstRTSPResult
2220 do_send_message (GstRTSPClient * client, GstRTSPMessage * message,
2221     gboolean close, gpointer user_data)
2222 {
2223   GstRTSPClientPrivate *priv = client->priv;
2224
2225   /* send the response and store the seq number so we can wait until it's
2226    * written to the client to close the connection */
2227   return gst_rtsp_watch_send_message (priv->watch, message, close ?
2228       &priv->close_seq : NULL);
2229 }
2230
2231 static GstRTSPResult
2232 message_received (GstRTSPWatch * watch, GstRTSPMessage * message,
2233     gpointer user_data)
2234 {
2235   return gst_rtsp_client_handle_message (GST_RTSP_CLIENT (user_data), message);
2236 }
2237
2238 static GstRTSPResult
2239 message_sent (GstRTSPWatch * watch, guint cseq, gpointer user_data)
2240 {
2241   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2242   GstRTSPClientPrivate *priv = client->priv;
2243
2244   if (priv->close_seq && priv->close_seq == cseq) {
2245     priv->close_seq = 0;
2246     close_connection (client);
2247   }
2248
2249   return GST_RTSP_OK;
2250 }
2251
2252 static GstRTSPResult
2253 closed (GstRTSPWatch * watch, gpointer user_data)
2254 {
2255   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2256   GstRTSPClientPrivate *priv = client->priv;
2257   const gchar *tunnelid;
2258
2259   GST_INFO ("client %p: connection closed", client);
2260
2261   if ((tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection))) {
2262     g_mutex_lock (&tunnels_lock);
2263     /* remove from tunnelids */
2264     g_hash_table_remove (tunnels, tunnelid);
2265     g_mutex_unlock (&tunnels_lock);
2266   }
2267
2268   gst_rtsp_client_set_send_func (client, NULL, NULL, NULL);
2269
2270   return GST_RTSP_OK;
2271 }
2272
2273 static GstRTSPResult
2274 error (GstRTSPWatch * watch, GstRTSPResult result, gpointer user_data)
2275 {
2276   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2277   gchar *str;
2278
2279   str = gst_rtsp_strresult (result);
2280   GST_INFO ("client %p: received an error %s", client, str);
2281   g_free (str);
2282
2283   return GST_RTSP_OK;
2284 }
2285
2286 static GstRTSPResult
2287 error_full (GstRTSPWatch * watch, GstRTSPResult result,
2288     GstRTSPMessage * message, guint id, gpointer user_data)
2289 {
2290   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2291   gchar *str;
2292
2293   str = gst_rtsp_strresult (result);
2294   GST_INFO
2295       ("client %p: error when handling message %p with id %d: %s",
2296       client, message, id, str);
2297   g_free (str);
2298
2299   return GST_RTSP_OK;
2300 }
2301
2302 static gboolean
2303 remember_tunnel (GstRTSPClient * client)
2304 {
2305   GstRTSPClientPrivate *priv = client->priv;
2306   const gchar *tunnelid;
2307
2308   /* store client in the pending tunnels */
2309   tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection);
2310   if (tunnelid == NULL)
2311     goto no_tunnelid;
2312
2313   GST_INFO ("client %p: inserting tunnel session %s", client, tunnelid);
2314
2315   /* we can't have two clients connecting with the same tunnelid */
2316   g_mutex_lock (&tunnels_lock);
2317   if (g_hash_table_lookup (tunnels, tunnelid))
2318     goto tunnel_existed;
2319
2320   g_hash_table_insert (tunnels, g_strdup (tunnelid), g_object_ref (client));
2321   g_mutex_unlock (&tunnels_lock);
2322
2323   return TRUE;
2324
2325   /* ERRORS */
2326 no_tunnelid:
2327   {
2328     GST_ERROR ("client %p: no tunnelid provided", client);
2329     return FALSE;
2330   }
2331 tunnel_existed:
2332   {
2333     g_mutex_unlock (&tunnels_lock);
2334     GST_ERROR ("client %p: tunnel session %s already existed", client,
2335         tunnelid);
2336     return FALSE;
2337   }
2338 }
2339
2340 static GstRTSPStatusCode
2341 tunnel_start (GstRTSPWatch * watch, gpointer user_data)
2342 {
2343   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2344   GstRTSPClientPrivate *priv = client->priv;
2345
2346   GST_INFO ("client %p: tunnel start (connection %p)", client,
2347       priv->connection);
2348
2349   if (!remember_tunnel (client))
2350     goto tunnel_error;
2351
2352   return GST_RTSP_STS_OK;
2353
2354   /* ERRORS */
2355 tunnel_error:
2356   {
2357     GST_ERROR ("client %p: error starting tunnel", client);
2358     return GST_RTSP_STS_SERVICE_UNAVAILABLE;
2359   }
2360 }
2361
2362 static GstRTSPResult
2363 tunnel_lost (GstRTSPWatch * watch, gpointer user_data)
2364 {
2365   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2366   GstRTSPClientPrivate *priv = client->priv;
2367
2368   GST_WARNING ("client %p: tunnel lost (connection %p)", client,
2369       priv->connection);
2370
2371   /* ignore error, it'll only be a problem when the client does a POST again */
2372   remember_tunnel (client);
2373
2374   return GST_RTSP_OK;
2375 }
2376
2377 static GstRTSPResult
2378 tunnel_complete (GstRTSPWatch * watch, gpointer user_data)
2379 {
2380   const gchar *tunnelid;
2381   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2382   GstRTSPClientPrivate *priv = client->priv;
2383   GstRTSPClient *oclient;
2384   GstRTSPClientPrivate *opriv;
2385
2386   GST_INFO ("client %p: tunnel complete", client);
2387
2388   /* find previous tunnel */
2389   tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection);
2390   if (tunnelid == NULL)
2391     goto no_tunnelid;
2392
2393   g_mutex_lock (&tunnels_lock);
2394   if (!(oclient = g_hash_table_lookup (tunnels, tunnelid)))
2395     goto no_tunnel;
2396
2397   /* remove the old client from the table. ref before because removing it will
2398    * remove the ref to it. */
2399   g_object_ref (oclient);
2400   g_hash_table_remove (tunnels, tunnelid);
2401
2402   opriv = oclient->priv;
2403
2404   if (opriv->watch == NULL)
2405     goto tunnel_closed;
2406   g_mutex_unlock (&tunnels_lock);
2407
2408   GST_INFO ("client %p: found tunnel %p (old %p, new %p)", client, oclient,
2409       opriv->connection, priv->connection);
2410
2411   /* merge the tunnels into the first client */
2412   gst_rtsp_connection_do_tunnel (opriv->connection, priv->connection);
2413   gst_rtsp_watch_reset (opriv->watch);
2414   g_object_unref (oclient);
2415
2416   return GST_RTSP_OK;
2417
2418   /* ERRORS */
2419 no_tunnelid:
2420   {
2421     GST_ERROR ("client %p: no tunnelid provided", client);
2422     return GST_RTSP_ERROR;
2423   }
2424 no_tunnel:
2425   {
2426     g_mutex_unlock (&tunnels_lock);
2427     GST_ERROR ("client %p: tunnel session %s not found", client, tunnelid);
2428     return GST_RTSP_ERROR;
2429   }
2430 tunnel_closed:
2431   {
2432     g_mutex_unlock (&tunnels_lock);
2433     GST_ERROR ("client %p: tunnel session %s was closed", client, tunnelid);
2434     g_object_unref (oclient);
2435     return GST_RTSP_ERROR;
2436   }
2437 }
2438
2439 static GstRTSPWatchFuncs watch_funcs = {
2440   message_received,
2441   message_sent,
2442   closed,
2443   error,
2444   tunnel_start,
2445   tunnel_complete,
2446   error_full,
2447   tunnel_lost
2448 };
2449
2450 static void
2451 client_watch_notify (GstRTSPClient * client)
2452 {
2453   GstRTSPClientPrivate *priv = client->priv;
2454
2455   GST_INFO ("client %p: watch destroyed", client);
2456   priv->watch = NULL;
2457   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_CLOSED], 0, NULL);
2458   g_object_unref (client);
2459 }
2460
2461 /**
2462  * gst_rtsp_client_attach:
2463  * @client: a #GstRTSPClient
2464  * @context: (allow-none): a #GMainContext
2465  *
2466  * Attaches @client to @context. When the mainloop for @context is run, the
2467  * client will be dispatched. When @context is NULL, the default context will be
2468  * used).
2469  *
2470  * This function should be called when the client properties and urls are fully
2471  * configured and the client is ready to start.
2472  *
2473  * Returns: the ID (greater than 0) for the source within the GMainContext.
2474  */
2475 guint
2476 gst_rtsp_client_attach (GstRTSPClient * client, GMainContext * context)
2477 {
2478   GstRTSPClientPrivate *priv;
2479   guint res;
2480
2481   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), 0);
2482   priv = client->priv;
2483   g_return_val_if_fail (priv->watch == NULL, 0);
2484
2485   /* create watch for the connection and attach */
2486   priv->watch = gst_rtsp_watch_new (priv->connection, &watch_funcs,
2487       g_object_ref (client), (GDestroyNotify) client_watch_notify);
2488   gst_rtsp_client_set_send_func (client, do_send_message, priv->watch,
2489       (GDestroyNotify) gst_rtsp_watch_unref);
2490
2491   /* FIXME make this configurable. We don't want to do this yet because it will
2492    * be superceeded by a cache object later */
2493   gst_rtsp_watch_set_send_backlog (priv->watch, 0, 100);
2494
2495   GST_INFO ("attaching to context %p", context);
2496   res = gst_rtsp_watch_attach (priv->watch, context);
2497
2498   return res;
2499 }