rtsp-client: If we have a single-stream media and SETUP contains no control, use...
[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  * SECTION:rtsp-client
21  * @short_description: A client connection state
22  * @see_also: #GstRTSPServer, #GstRTSPThreadPool
23  *
24  * The client object handles the connection with a client for as long as a TCP
25  * connection is open.
26  *
27  * A #GstRTSPClient is created by #GstRTSPServer when a new connection is
28  * accepted and it inherits the #GstRTSPMountPoints, #GstRTSPSessionPool,
29  * #GstRTSPAuth and #GstRTSPThreadPool from the server.
30  *
31  * The client connection should be configured with the #GstRTSPConnection using
32  * gst_rtsp_client_set_connection() before it can be attached to a #GMainContext
33  * using gst_rtsp_client_attach(). From then on the client will handle requests
34  * on the connection.
35  *
36  * Use gst_rtsp_client_session_filter() to iterate or modify all the
37  * #GstRTSPSession objects managed by the client object.
38  *
39  * Last reviewed on 2013-07-11 (1.0.0)
40  */
41
42 #include <stdio.h>
43 #include <string.h>
44
45 #include <gst/sdp/gstmikey.h>
46
47 #include "rtsp-client.h"
48 #include "rtsp-sdp.h"
49 #include "rtsp-params.h"
50
51 #define GST_RTSP_CLIENT_GET_PRIVATE(obj)  \
52    (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_RTSP_CLIENT, GstRTSPClientPrivate))
53
54 /* locking order:
55  * send_lock, lock, tunnels_lock
56  */
57
58 struct _GstRTSPClientPrivate
59 {
60   GMutex lock;                  /* protects everything else */
61   GMutex send_lock;
62   GMutex watch_lock;
63   GstRTSPConnection *connection;
64   GstRTSPWatch *watch;
65   GMainContext *watch_context;
66   guint close_seq;
67   gchar *server_ip;
68   gboolean is_ipv6;
69
70   GstRTSPClientSendFunc send_func;      /* protected by send_lock */
71   gpointer send_data;           /* protected by send_lock */
72   GDestroyNotify send_notify;   /* protected by send_lock */
73
74   GstRTSPSessionPool *session_pool;
75   gulong session_removed_id;
76   GstRTSPMountPoints *mount_points;
77   GstRTSPAuth *auth;
78   GstRTSPThreadPool *thread_pool;
79
80   /* used to cache the media in the last requested DESCRIBE so that
81    * we can pick it up in the next SETUP immediately */
82   gchar *path;
83   GstRTSPMedia *media;
84
85   GHashTable *transports;
86   GList *sessions;
87   guint sessions_cookie;
88
89   gboolean drop_backlog;
90 };
91
92 static GMutex tunnels_lock;
93 static GHashTable *tunnels;     /* protected by tunnels_lock */
94
95 /* FIXME make this configurable. We don't want to do this yet because it will
96  * be superceeded by a cache object later */
97 #define WATCH_BACKLOG_SIZE              100
98
99 #define DEFAULT_SESSION_POOL            NULL
100 #define DEFAULT_MOUNT_POINTS            NULL
101 #define DEFAULT_DROP_BACKLOG            TRUE
102
103 enum
104 {
105   PROP_0,
106   PROP_SESSION_POOL,
107   PROP_MOUNT_POINTS,
108   PROP_DROP_BACKLOG,
109   PROP_LAST
110 };
111
112 enum
113 {
114   SIGNAL_CLOSED,
115   SIGNAL_NEW_SESSION,
116   SIGNAL_OPTIONS_REQUEST,
117   SIGNAL_DESCRIBE_REQUEST,
118   SIGNAL_SETUP_REQUEST,
119   SIGNAL_PLAY_REQUEST,
120   SIGNAL_PAUSE_REQUEST,
121   SIGNAL_TEARDOWN_REQUEST,
122   SIGNAL_SET_PARAMETER_REQUEST,
123   SIGNAL_GET_PARAMETER_REQUEST,
124   SIGNAL_HANDLE_RESPONSE,
125   SIGNAL_SEND_MESSAGE,
126   SIGNAL_LAST
127 };
128
129 GST_DEBUG_CATEGORY_STATIC (rtsp_client_debug);
130 #define GST_CAT_DEFAULT rtsp_client_debug
131
132 static guint gst_rtsp_client_signals[SIGNAL_LAST] = { 0 };
133
134 static void gst_rtsp_client_get_property (GObject * object, guint propid,
135     GValue * value, GParamSpec * pspec);
136 static void gst_rtsp_client_set_property (GObject * object, guint propid,
137     const GValue * value, GParamSpec * pspec);
138 static void gst_rtsp_client_finalize (GObject * obj);
139
140 static GstSDPMessage *create_sdp (GstRTSPClient * client, GstRTSPMedia * media);
141 static gboolean default_configure_client_media (GstRTSPClient * client,
142     GstRTSPMedia * media, GstRTSPStream * stream, GstRTSPContext * ctx);
143 static gboolean default_configure_client_transport (GstRTSPClient * client,
144     GstRTSPContext * ctx, GstRTSPTransport * ct);
145 static GstRTSPResult default_params_set (GstRTSPClient * client,
146     GstRTSPContext * ctx);
147 static GstRTSPResult default_params_get (GstRTSPClient * client,
148     GstRTSPContext * ctx);
149 static gchar *default_make_path_from_uri (GstRTSPClient * client,
150     const GstRTSPUrl * uri);
151 static void client_session_removed (GstRTSPSessionPool * pool,
152     GstRTSPSession * session, GstRTSPClient * client);
153
154 G_DEFINE_TYPE (GstRTSPClient, gst_rtsp_client, G_TYPE_OBJECT);
155
156 static void
157 gst_rtsp_client_class_init (GstRTSPClientClass * klass)
158 {
159   GObjectClass *gobject_class;
160
161   g_type_class_add_private (klass, sizeof (GstRTSPClientPrivate));
162
163   gobject_class = G_OBJECT_CLASS (klass);
164
165   gobject_class->get_property = gst_rtsp_client_get_property;
166   gobject_class->set_property = gst_rtsp_client_set_property;
167   gobject_class->finalize = gst_rtsp_client_finalize;
168
169   klass->create_sdp = create_sdp;
170   klass->configure_client_media = default_configure_client_media;
171   klass->configure_client_transport = default_configure_client_transport;
172   klass->params_set = default_params_set;
173   klass->params_get = default_params_get;
174   klass->make_path_from_uri = default_make_path_from_uri;
175
176   g_object_class_install_property (gobject_class, PROP_SESSION_POOL,
177       g_param_spec_object ("session-pool", "Session Pool",
178           "The session pool to use for client session",
179           GST_TYPE_RTSP_SESSION_POOL,
180           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
181
182   g_object_class_install_property (gobject_class, PROP_MOUNT_POINTS,
183       g_param_spec_object ("mount-points", "Mount Points",
184           "The mount points to use for client session",
185           GST_TYPE_RTSP_MOUNT_POINTS,
186           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
187
188   g_object_class_install_property (gobject_class, PROP_DROP_BACKLOG,
189       g_param_spec_boolean ("drop-backlog", "Drop Backlog",
190           "Drop data when the backlog queue is full",
191           DEFAULT_DROP_BACKLOG, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
192
193   gst_rtsp_client_signals[SIGNAL_CLOSED] =
194       g_signal_new ("closed", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
195       G_STRUCT_OFFSET (GstRTSPClientClass, closed), NULL, NULL,
196       g_cclosure_marshal_generic, G_TYPE_NONE, 0, G_TYPE_NONE);
197
198   gst_rtsp_client_signals[SIGNAL_NEW_SESSION] =
199       g_signal_new ("new-session", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
200       G_STRUCT_OFFSET (GstRTSPClientClass, new_session), NULL, NULL,
201       g_cclosure_marshal_generic, G_TYPE_NONE, 1, GST_TYPE_RTSP_SESSION);
202
203   gst_rtsp_client_signals[SIGNAL_OPTIONS_REQUEST] =
204       g_signal_new ("options-request", G_TYPE_FROM_CLASS (klass),
205       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, options_request),
206       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 1,
207       GST_TYPE_RTSP_CONTEXT);
208
209   gst_rtsp_client_signals[SIGNAL_DESCRIBE_REQUEST] =
210       g_signal_new ("describe-request", G_TYPE_FROM_CLASS (klass),
211       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, describe_request),
212       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 1,
213       GST_TYPE_RTSP_CONTEXT);
214
215   gst_rtsp_client_signals[SIGNAL_SETUP_REQUEST] =
216       g_signal_new ("setup-request", G_TYPE_FROM_CLASS (klass),
217       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, setup_request),
218       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 1,
219       GST_TYPE_RTSP_CONTEXT);
220
221   gst_rtsp_client_signals[SIGNAL_PLAY_REQUEST] =
222       g_signal_new ("play-request", G_TYPE_FROM_CLASS (klass),
223       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, play_request),
224       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 1,
225       GST_TYPE_RTSP_CONTEXT);
226
227   gst_rtsp_client_signals[SIGNAL_PAUSE_REQUEST] =
228       g_signal_new ("pause-request", G_TYPE_FROM_CLASS (klass),
229       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, pause_request),
230       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 1,
231       GST_TYPE_RTSP_CONTEXT);
232
233   gst_rtsp_client_signals[SIGNAL_TEARDOWN_REQUEST] =
234       g_signal_new ("teardown-request", G_TYPE_FROM_CLASS (klass),
235       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, teardown_request),
236       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 1,
237       GST_TYPE_RTSP_CONTEXT);
238
239   gst_rtsp_client_signals[SIGNAL_SET_PARAMETER_REQUEST] =
240       g_signal_new ("set-parameter-request", G_TYPE_FROM_CLASS (klass),
241       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass,
242           set_parameter_request), NULL, NULL, g_cclosure_marshal_generic,
243       G_TYPE_NONE, 1, GST_TYPE_RTSP_CONTEXT);
244
245   gst_rtsp_client_signals[SIGNAL_GET_PARAMETER_REQUEST] =
246       g_signal_new ("get-parameter-request", G_TYPE_FROM_CLASS (klass),
247       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass,
248           get_parameter_request), NULL, NULL, g_cclosure_marshal_generic,
249       G_TYPE_NONE, 1, GST_TYPE_RTSP_CONTEXT);
250
251   gst_rtsp_client_signals[SIGNAL_HANDLE_RESPONSE] =
252       g_signal_new ("handle-response", G_TYPE_FROM_CLASS (klass),
253       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass,
254           handle_response), NULL, NULL, g_cclosure_marshal_generic,
255       G_TYPE_NONE, 1, GST_TYPE_RTSP_CONTEXT);
256
257   /**
258    * GstRTSPClient::send-message:
259    * @client: The RTSP client
260    * @session: (type GstRtspServer.RTSPSession): The session
261    * @message: (type GstRtsp.RTSPMessage): The message
262    */
263   gst_rtsp_client_signals[SIGNAL_SEND_MESSAGE] =
264       g_signal_new ("send-message", G_TYPE_FROM_CLASS (klass),
265       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass,
266           send_message), NULL, NULL, g_cclosure_marshal_generic,
267       G_TYPE_NONE, 2, GST_TYPE_RTSP_CONTEXT, G_TYPE_POINTER);
268
269   tunnels =
270       g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_object_unref);
271   g_mutex_init (&tunnels_lock);
272
273   GST_DEBUG_CATEGORY_INIT (rtsp_client_debug, "rtspclient", 0, "GstRTSPClient");
274 }
275
276 static void
277 gst_rtsp_client_init (GstRTSPClient * client)
278 {
279   GstRTSPClientPrivate *priv = GST_RTSP_CLIENT_GET_PRIVATE (client);
280
281   client->priv = priv;
282
283   g_mutex_init (&priv->lock);
284   g_mutex_init (&priv->send_lock);
285   g_mutex_init (&priv->watch_lock);
286   priv->close_seq = 0;
287   priv->drop_backlog = DEFAULT_DROP_BACKLOG;
288   priv->transports =
289       g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL,
290       g_object_unref);
291 }
292
293 static GstRTSPFilterResult
294 filter_session_media (GstRTSPSession * sess, GstRTSPSessionMedia * sessmedia,
295     gpointer user_data)
296 {
297   gst_rtsp_session_media_set_state (sessmedia, GST_STATE_NULL);
298
299   return GST_RTSP_FILTER_REMOVE;
300 }
301
302 static void
303 client_watch_session (GstRTSPClient * client, GstRTSPSession * session)
304 {
305   GstRTSPClientPrivate *priv = client->priv;
306
307   g_mutex_lock (&priv->lock);
308   /* check if we already know about this session */
309   if (g_list_find (priv->sessions, session) == NULL) {
310     GST_INFO ("watching session %p", session);
311
312     priv->sessions = g_list_prepend (priv->sessions, g_object_ref (session));
313     priv->sessions_cookie++;
314
315     /* connect removed session handler, it will be disconnected when the last
316      * session gets removed  */
317     if (priv->session_removed_id == 0)
318       priv->session_removed_id = g_signal_connect_data (priv->session_pool,
319           "session-removed", G_CALLBACK (client_session_removed),
320           g_object_ref (client), (GClosureNotify) g_object_unref, 0);
321   }
322   g_mutex_unlock (&priv->lock);
323
324   return;
325 }
326
327 /* should be called with lock */
328 static void
329 client_unwatch_session (GstRTSPClient * client, GstRTSPSession * session,
330     GList * link)
331 {
332   GstRTSPClientPrivate *priv = client->priv;
333
334   GST_INFO ("client %p: unwatch session %p", client, session);
335
336   if (link == NULL) {
337     link = g_list_find (priv->sessions, session);
338     if (link == NULL)
339       return;
340   }
341
342   priv->sessions = g_list_delete_link (priv->sessions, link);
343   priv->sessions_cookie++;
344
345   /* if this was the last session, disconnect the handler.
346    * This will also drop the extra client ref */
347   if (!priv->sessions) {
348     g_signal_handler_disconnect (priv->session_pool, priv->session_removed_id);
349     priv->session_removed_id = 0;
350   }
351
352   /* remove the session */
353   g_object_unref (session);
354 }
355
356 static GstRTSPFilterResult
357 cleanup_session (GstRTSPClient * client, GstRTSPSession * sess,
358     gpointer user_data)
359 {
360   /* unlink all media managed in this session. This needs to happen
361    * without the client lock, so we really want to do it here. */
362   gst_rtsp_session_filter (sess, filter_session_media, client);
363
364   return GST_RTSP_FILTER_REMOVE;
365 }
366
367 static void
368 clean_cached_media (GstRTSPClient * client, gboolean unprepare)
369 {
370   GstRTSPClientPrivate *priv = client->priv;
371
372   if (priv->path) {
373     g_free (priv->path);
374     priv->path = NULL;
375   }
376   if (priv->media) {
377     if (unprepare)
378       gst_rtsp_media_unprepare (priv->media);
379     g_object_unref (priv->media);
380     priv->media = NULL;
381   }
382 }
383
384 /* A client is finalized when the connection is broken */
385 static void
386 gst_rtsp_client_finalize (GObject * obj)
387 {
388   GstRTSPClient *client = GST_RTSP_CLIENT (obj);
389   GstRTSPClientPrivate *priv = client->priv;
390
391   GST_INFO ("finalize client %p", client);
392
393   if (priv->watch)
394     gst_rtsp_watch_set_flushing (priv->watch, TRUE);
395   gst_rtsp_client_set_send_func (client, NULL, NULL, NULL);
396
397   if (priv->watch)
398     g_source_destroy ((GSource *) priv->watch);
399
400   if (priv->watch_context)
401     g_main_context_unref (priv->watch_context);
402
403   /* all sessions should have been removed by now. We keep a ref to
404    * the client object for the session removed handler. The ref is
405    * dropped when the last session is removed from the list. */
406   g_assert (priv->sessions == NULL);
407   g_assert (priv->session_removed_id == 0);
408
409   g_hash_table_unref (priv->transports);
410
411   if (priv->connection)
412     gst_rtsp_connection_free (priv->connection);
413   if (priv->session_pool) {
414     g_object_unref (priv->session_pool);
415   }
416   if (priv->mount_points)
417     g_object_unref (priv->mount_points);
418   if (priv->auth)
419     g_object_unref (priv->auth);
420   if (priv->thread_pool)
421     g_object_unref (priv->thread_pool);
422
423   clean_cached_media (client, TRUE);
424
425   g_free (priv->server_ip);
426   g_mutex_clear (&priv->lock);
427   g_mutex_clear (&priv->send_lock);
428   g_mutex_clear (&priv->watch_lock);
429
430   G_OBJECT_CLASS (gst_rtsp_client_parent_class)->finalize (obj);
431 }
432
433 static void
434 gst_rtsp_client_get_property (GObject * object, guint propid,
435     GValue * value, GParamSpec * pspec)
436 {
437   GstRTSPClient *client = GST_RTSP_CLIENT (object);
438   GstRTSPClientPrivate *priv = client->priv;
439
440   switch (propid) {
441     case PROP_SESSION_POOL:
442       g_value_take_object (value, gst_rtsp_client_get_session_pool (client));
443       break;
444     case PROP_MOUNT_POINTS:
445       g_value_take_object (value, gst_rtsp_client_get_mount_points (client));
446       break;
447     case PROP_DROP_BACKLOG:
448       g_value_set_boolean (value, priv->drop_backlog);
449       break;
450     default:
451       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, propid, pspec);
452   }
453 }
454
455 static void
456 gst_rtsp_client_set_property (GObject * object, guint propid,
457     const GValue * value, GParamSpec * pspec)
458 {
459   GstRTSPClient *client = GST_RTSP_CLIENT (object);
460   GstRTSPClientPrivate *priv = client->priv;
461
462   switch (propid) {
463     case PROP_SESSION_POOL:
464       gst_rtsp_client_set_session_pool (client, g_value_get_object (value));
465       break;
466     case PROP_MOUNT_POINTS:
467       gst_rtsp_client_set_mount_points (client, g_value_get_object (value));
468       break;
469     case PROP_DROP_BACKLOG:
470       g_mutex_lock (&priv->lock);
471       priv->drop_backlog = g_value_get_boolean (value);
472       g_mutex_unlock (&priv->lock);
473       break;
474     default:
475       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, propid, pspec);
476   }
477 }
478
479 /**
480  * gst_rtsp_client_new:
481  *
482  * Create a new #GstRTSPClient instance.
483  *
484  * Returns: (transfer full): a new #GstRTSPClient
485  */
486 GstRTSPClient *
487 gst_rtsp_client_new (void)
488 {
489   GstRTSPClient *result;
490
491   result = g_object_new (GST_TYPE_RTSP_CLIENT, NULL);
492
493   return result;
494 }
495
496 static void
497 send_message (GstRTSPClient * client, GstRTSPContext * ctx,
498     GstRTSPMessage * message, gboolean close)
499 {
500   GstRTSPClientPrivate *priv = client->priv;
501
502   gst_rtsp_message_add_header (message, GST_RTSP_HDR_SERVER,
503       "GStreamer RTSP server");
504
505   /* remove any previous header */
506   gst_rtsp_message_remove_header (message, GST_RTSP_HDR_SESSION, -1);
507
508   /* add the new session header for new session ids */
509   if (ctx->session) {
510     gst_rtsp_message_take_header (message, GST_RTSP_HDR_SESSION,
511         gst_rtsp_session_get_header (ctx->session));
512   }
513
514   if (gst_debug_category_get_threshold (rtsp_client_debug) >= GST_LEVEL_LOG) {
515     gst_rtsp_message_dump (message);
516   }
517
518   if (close)
519     gst_rtsp_message_add_header (message, GST_RTSP_HDR_CONNECTION, "close");
520
521   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_SEND_MESSAGE],
522       0, ctx, message);
523
524   g_mutex_lock (&priv->send_lock);
525   if (priv->send_func)
526     priv->send_func (client, message, close, priv->send_data);
527   g_mutex_unlock (&priv->send_lock);
528
529   gst_rtsp_message_unset (message);
530 }
531
532 static void
533 send_generic_response (GstRTSPClient * client, GstRTSPStatusCode code,
534     GstRTSPContext * ctx)
535 {
536   gst_rtsp_message_init_response (ctx->response, code,
537       gst_rtsp_status_as_text (code), ctx->request);
538
539   ctx->session = NULL;
540
541   send_message (client, ctx, ctx->response, FALSE);
542 }
543
544 static void
545 send_option_not_supported_response (GstRTSPClient * client,
546     GstRTSPContext * ctx, const gchar * unsupported_options)
547 {
548   GstRTSPStatusCode code = GST_RTSP_STS_OPTION_NOT_SUPPORTED;
549
550   gst_rtsp_message_init_response (ctx->response, code,
551       gst_rtsp_status_as_text (code), ctx->request);
552
553   if (unsupported_options != NULL) {
554     gst_rtsp_message_add_header (ctx->response, GST_RTSP_HDR_UNSUPPORTED,
555         unsupported_options);
556   }
557
558   ctx->session = NULL;
559
560   send_message (client, ctx, ctx->response, FALSE);
561 }
562
563 static gboolean
564 paths_are_equal (const gchar * path1, const gchar * path2, gint len2)
565 {
566   if (path1 == NULL || path2 == NULL)
567     return FALSE;
568
569   if (strlen (path1) != len2)
570     return FALSE;
571
572   if (strncmp (path1, path2, len2))
573     return FALSE;
574
575   return TRUE;
576 }
577
578 /* this function is called to initially find the media for the DESCRIBE request
579  * but is cached for when the same client (without breaking the connection) is
580  * doing a setup for the exact same url. */
581 static GstRTSPMedia *
582 find_media (GstRTSPClient * client, GstRTSPContext * ctx, gchar * path,
583     gint * matched)
584 {
585   GstRTSPClientPrivate *priv = client->priv;
586   GstRTSPMediaFactory *factory;
587   GstRTSPMedia *media;
588   gint path_len;
589
590   /* find the longest matching factory for the uri first */
591   if (!(factory = gst_rtsp_mount_points_match (priv->mount_points,
592               path, matched)))
593     goto no_factory;
594
595   ctx->factory = factory;
596
597   if (!gst_rtsp_auth_check (GST_RTSP_AUTH_CHECK_MEDIA_FACTORY_ACCESS))
598     goto no_factory_access;
599
600   if (!gst_rtsp_auth_check (GST_RTSP_AUTH_CHECK_MEDIA_FACTORY_CONSTRUCT))
601     goto not_authorized;
602
603   if (matched)
604     path_len = *matched;
605   else
606     path_len = strlen (path);
607
608   if (!paths_are_equal (priv->path, path, path_len)) {
609     GstRTSPThread *thread;
610
611     /* remove any previously cached values before we try to construct a new
612      * media for uri */
613     clean_cached_media (client, TRUE);
614
615     /* prepare the media and add it to the pipeline */
616     if (!(media = gst_rtsp_media_factory_construct (factory, ctx->uri)))
617       goto no_media;
618
619     ctx->media = media;
620
621     thread = gst_rtsp_thread_pool_get_thread (priv->thread_pool,
622         GST_RTSP_THREAD_TYPE_MEDIA, ctx);
623     if (thread == NULL)
624       goto no_thread;
625
626     /* prepare the media */
627     if (!(gst_rtsp_media_prepare (media, thread)))
628       goto no_prepare;
629
630     /* now keep track of the uri and the media */
631     priv->path = g_strndup (path, path_len);
632     priv->media = media;
633   } else {
634     /* we have seen this path before, used cached media */
635     media = priv->media;
636     ctx->media = media;
637     GST_INFO ("reusing cached media %p for path %s", media, priv->path);
638   }
639
640   g_object_unref (factory);
641   ctx->factory = NULL;
642
643   if (media)
644     g_object_ref (media);
645
646   return media;
647
648   /* ERRORS */
649 no_factory:
650   {
651     GST_ERROR ("client %p: no factory for path %s", client, path);
652     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
653     return NULL;
654   }
655 no_factory_access:
656   {
657     GST_ERROR ("client %p: not authorized to see factory path %s", client,
658         path);
659     /* error reply is already sent */
660     return NULL;
661   }
662 not_authorized:
663   {
664     GST_ERROR ("client %p: not authorized for factory path %s", client, path);
665     /* error reply is already sent */
666     return NULL;
667   }
668 no_media:
669   {
670     GST_ERROR ("client %p: can't create media", client);
671     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
672     g_object_unref (factory);
673     ctx->factory = NULL;
674     return NULL;
675   }
676 no_thread:
677   {
678     GST_ERROR ("client %p: can't create thread", client);
679     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, ctx);
680     g_object_unref (media);
681     ctx->media = NULL;
682     g_object_unref (factory);
683     ctx->factory = NULL;
684     return NULL;
685   }
686 no_prepare:
687   {
688     GST_ERROR ("client %p: can't prepare media", client);
689     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, ctx);
690     g_object_unref (media);
691     ctx->media = NULL;
692     g_object_unref (factory);
693     ctx->factory = NULL;
694     return NULL;
695   }
696 }
697
698 static gboolean
699 do_send_data (GstBuffer * buffer, guint8 channel, GstRTSPClient * client)
700 {
701   GstRTSPClientPrivate *priv = client->priv;
702   GstRTSPMessage message = { 0 };
703   GstRTSPResult res = GST_RTSP_OK;
704   GstMapInfo map_info;
705   guint8 *data;
706   guint usize;
707
708   gst_rtsp_message_init_data (&message, channel);
709
710   /* FIXME, need some sort of iovec RTSPMessage here */
711   if (!gst_buffer_map (buffer, &map_info, GST_MAP_READ))
712     return FALSE;
713
714   gst_rtsp_message_take_body (&message, map_info.data, map_info.size);
715
716   g_mutex_lock (&priv->send_lock);
717   if (priv->send_func)
718     res = priv->send_func (client, &message, FALSE, priv->send_data);
719   g_mutex_unlock (&priv->send_lock);
720
721   gst_rtsp_message_steal_body (&message, &data, &usize);
722   gst_buffer_unmap (buffer, &map_info);
723
724   gst_rtsp_message_unset (&message);
725
726   return res == GST_RTSP_OK;
727 }
728
729 /**
730  * gst_rtsp_client_close:
731  * @client: a #GstRTSPClient
732  *
733  * Close the connection of @client and remove all media it was managing.
734  *
735  * Since: 1.4
736  */
737 void
738 gst_rtsp_client_close (GstRTSPClient * client)
739 {
740   GstRTSPClientPrivate *priv = client->priv;
741   const gchar *tunnelid;
742
743   GST_DEBUG ("client %p: closing connection", client);
744
745   if (priv->connection) {
746     if ((tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection))) {
747       g_mutex_lock (&tunnels_lock);
748       /* remove from tunnelids */
749       g_hash_table_remove (tunnels, tunnelid);
750       g_mutex_unlock (&tunnels_lock);
751     }
752     gst_rtsp_connection_close (priv->connection);
753   }
754
755   /* connection is now closed, destroy the watch which will also cause the
756    * closed signal to be emitted */
757   if (priv->watch) {
758     GST_DEBUG ("client %p: destroying watch", client);
759     g_source_destroy ((GSource *) priv->watch);
760     priv->watch = NULL;
761     gst_rtsp_client_set_send_func (client, NULL, NULL, NULL);
762     g_main_context_unref (priv->watch_context);
763     priv->watch_context = NULL;
764   }
765 }
766
767 static gchar *
768 default_make_path_from_uri (GstRTSPClient * client, const GstRTSPUrl * uri)
769 {
770   gchar *path;
771
772   if (uri->query)
773     path = g_strconcat (uri->abspath, "?", uri->query, NULL);
774   else
775     path = g_strdup (uri->abspath);
776
777   return path;
778 }
779
780 static gboolean
781 handle_teardown_request (GstRTSPClient * client, GstRTSPContext * ctx)
782 {
783   GstRTSPClientPrivate *priv = client->priv;
784   GstRTSPClientClass *klass;
785   GstRTSPSession *session;
786   GstRTSPSessionMedia *sessmedia;
787   GstRTSPStatusCode code;
788   gchar *path;
789   gint matched;
790   gboolean keep_session;
791
792   if (!ctx->session)
793     goto no_session;
794
795   session = ctx->session;
796
797   if (!ctx->uri)
798     goto no_uri;
799
800   klass = GST_RTSP_CLIENT_GET_CLASS (client);
801   path = klass->make_path_from_uri (client, ctx->uri);
802
803   /* get a handle to the configuration of the media in the session */
804   sessmedia = gst_rtsp_session_get_media (session, path, &matched);
805   if (!sessmedia)
806     goto not_found;
807
808   /* only aggregate control for now.. */
809   if (path[matched] != '\0')
810     goto no_aggregate;
811
812   g_free (path);
813
814   ctx->sessmedia = sessmedia;
815
816   /* we emit the signal before closing the connection */
817   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_TEARDOWN_REQUEST],
818       0, ctx);
819
820   /* make sure we unblock the backlog and don't accept new messages
821    * on the watch */
822   if (priv->watch != NULL)
823     gst_rtsp_watch_set_flushing (priv->watch, TRUE);
824
825   gst_rtsp_session_media_set_state (sessmedia, GST_STATE_NULL);
826
827   /* allow messages again so that we can send the reply */
828   if (priv->watch != NULL)
829     gst_rtsp_watch_set_flushing (priv->watch, FALSE);
830
831   /* unmanage the media in the session, returns false if all media session
832    * are torn down. */
833   keep_session = gst_rtsp_session_release_media (session, sessmedia);
834
835   /* construct the response now */
836   code = GST_RTSP_STS_OK;
837   gst_rtsp_message_init_response (ctx->response, code,
838       gst_rtsp_status_as_text (code), ctx->request);
839
840   send_message (client, ctx, ctx->response, TRUE);
841
842   if (!keep_session) {
843     /* remove the session */
844     gst_rtsp_session_pool_remove (priv->session_pool, session);
845   }
846
847   return TRUE;
848
849   /* ERRORS */
850 no_session:
851   {
852     GST_ERROR ("client %p: no session", client);
853     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
854     return FALSE;
855   }
856 no_uri:
857   {
858     GST_ERROR ("client %p: no uri supplied", client);
859     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
860     return FALSE;
861   }
862 not_found:
863   {
864     GST_ERROR ("client %p: no media for uri", client);
865     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
866     g_free (path);
867     return FALSE;
868   }
869 no_aggregate:
870   {
871     GST_ERROR ("client %p: no aggregate path %s", client, path);
872     send_generic_response (client,
873         GST_RTSP_STS_ONLY_AGGREGATE_OPERATION_ALLOWED, ctx);
874     g_free (path);
875     return FALSE;
876   }
877 }
878
879 static GstRTSPResult
880 default_params_set (GstRTSPClient * client, GstRTSPContext * ctx)
881 {
882   GstRTSPResult res;
883
884   res = gst_rtsp_params_set (client, ctx);
885
886   return res;
887 }
888
889 static GstRTSPResult
890 default_params_get (GstRTSPClient * client, GstRTSPContext * ctx)
891 {
892   GstRTSPResult res;
893
894   res = gst_rtsp_params_get (client, ctx);
895
896   return res;
897 }
898
899 static gboolean
900 handle_get_param_request (GstRTSPClient * client, GstRTSPContext * ctx)
901 {
902   GstRTSPResult res;
903   guint8 *data;
904   guint size;
905
906   res = gst_rtsp_message_get_body (ctx->request, &data, &size);
907   if (res != GST_RTSP_OK)
908     goto bad_request;
909
910   if (size == 0) {
911     /* no body, keep-alive request */
912     send_generic_response (client, GST_RTSP_STS_OK, ctx);
913   } else {
914     /* there is a body, handle the params */
915     res = GST_RTSP_CLIENT_GET_CLASS (client)->params_get (client, ctx);
916     if (res != GST_RTSP_OK)
917       goto bad_request;
918
919     send_message (client, ctx, ctx->response, FALSE);
920   }
921
922   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_GET_PARAMETER_REQUEST],
923       0, ctx);
924
925   return TRUE;
926
927   /* ERRORS */
928 bad_request:
929   {
930     GST_ERROR ("client %p: bad request", client);
931     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
932     return FALSE;
933   }
934 }
935
936 static gboolean
937 handle_set_param_request (GstRTSPClient * client, GstRTSPContext * ctx)
938 {
939   GstRTSPResult res;
940   guint8 *data;
941   guint size;
942
943   res = gst_rtsp_message_get_body (ctx->request, &data, &size);
944   if (res != GST_RTSP_OK)
945     goto bad_request;
946
947   if (size == 0) {
948     /* no body, keep-alive request */
949     send_generic_response (client, GST_RTSP_STS_OK, ctx);
950   } else {
951     /* there is a body, handle the params */
952     res = GST_RTSP_CLIENT_GET_CLASS (client)->params_set (client, ctx);
953     if (res != GST_RTSP_OK)
954       goto bad_request;
955
956     send_message (client, ctx, ctx->response, FALSE);
957   }
958
959   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_SET_PARAMETER_REQUEST],
960       0, ctx);
961
962   return TRUE;
963
964   /* ERRORS */
965 bad_request:
966   {
967     GST_ERROR ("client %p: bad request", client);
968     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
969     return FALSE;
970   }
971 }
972
973 static gboolean
974 handle_pause_request (GstRTSPClient * client, GstRTSPContext * ctx)
975 {
976   GstRTSPSession *session;
977   GstRTSPClientClass *klass;
978   GstRTSPSessionMedia *sessmedia;
979   GstRTSPStatusCode code;
980   GstRTSPState rtspstate;
981   gchar *path;
982   gint matched;
983
984   if (!(session = ctx->session))
985     goto no_session;
986
987   if (!ctx->uri)
988     goto no_uri;
989
990   klass = GST_RTSP_CLIENT_GET_CLASS (client);
991   path = klass->make_path_from_uri (client, ctx->uri);
992
993   /* get a handle to the configuration of the media in the session */
994   sessmedia = gst_rtsp_session_get_media (session, path, &matched);
995   if (!sessmedia)
996     goto not_found;
997
998   if (path[matched] != '\0')
999     goto no_aggregate;
1000
1001   g_free (path);
1002
1003   ctx->sessmedia = sessmedia;
1004
1005   rtspstate = gst_rtsp_session_media_get_rtsp_state (sessmedia);
1006   /* the session state must be playing or recording */
1007   if (rtspstate != GST_RTSP_STATE_PLAYING &&
1008       rtspstate != GST_RTSP_STATE_RECORDING)
1009     goto invalid_state;
1010
1011   /* then pause sending */
1012   gst_rtsp_session_media_set_state (sessmedia, GST_STATE_PAUSED);
1013
1014   /* construct the response now */
1015   code = GST_RTSP_STS_OK;
1016   gst_rtsp_message_init_response (ctx->response, code,
1017       gst_rtsp_status_as_text (code), ctx->request);
1018
1019   send_message (client, ctx, ctx->response, FALSE);
1020
1021   /* the state is now READY */
1022   gst_rtsp_session_media_set_rtsp_state (sessmedia, GST_RTSP_STATE_READY);
1023
1024   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_PAUSE_REQUEST], 0, ctx);
1025
1026   return TRUE;
1027
1028   /* ERRORS */
1029 no_session:
1030   {
1031     GST_ERROR ("client %p: no seesion", client);
1032     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
1033     return FALSE;
1034   }
1035 no_uri:
1036   {
1037     GST_ERROR ("client %p: no uri supplied", client);
1038     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
1039     return FALSE;
1040   }
1041 not_found:
1042   {
1043     GST_ERROR ("client %p: no media for uri", client);
1044     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
1045     g_free (path);
1046     return FALSE;
1047   }
1048 no_aggregate:
1049   {
1050     GST_ERROR ("client %p: no aggregate path %s", client, path);
1051     send_generic_response (client,
1052         GST_RTSP_STS_ONLY_AGGREGATE_OPERATION_ALLOWED, ctx);
1053     g_free (path);
1054     return FALSE;
1055   }
1056 invalid_state:
1057   {
1058     GST_ERROR ("client %p: not PLAYING or RECORDING", client);
1059     send_generic_response (client, GST_RTSP_STS_METHOD_NOT_VALID_IN_THIS_STATE,
1060         ctx);
1061     return FALSE;
1062   }
1063 }
1064
1065 /* convert @url and @path to a URL used as a content base for the factory
1066  * located at @path */
1067 static gchar *
1068 make_base_url (GstRTSPClient * client, GstRTSPUrl * url, const gchar * path)
1069 {
1070   GstRTSPUrl tmp;
1071   gchar *result;
1072   const gchar *trail;
1073
1074   /* check for trailing '/' and append one */
1075   trail = (path[strlen (path) - 1] != '/' ? "/" : "");
1076
1077   tmp = *url;
1078   tmp.user = NULL;
1079   tmp.passwd = NULL;
1080   tmp.abspath = g_strdup_printf ("%s%s", path, trail);
1081   tmp.query = NULL;
1082   result = gst_rtsp_url_get_request_uri (&tmp);
1083   g_free (tmp.abspath);
1084
1085   return result;
1086 }
1087
1088 static gboolean
1089 handle_play_request (GstRTSPClient * client, GstRTSPContext * ctx)
1090 {
1091   GstRTSPSession *session;
1092   GstRTSPClientClass *klass;
1093   GstRTSPSessionMedia *sessmedia;
1094   GstRTSPMedia *media;
1095   GstRTSPStatusCode code;
1096   GstRTSPUrl *uri;
1097   gchar *str;
1098   GstRTSPTimeRange *range;
1099   GstRTSPResult res;
1100   GstRTSPState rtspstate;
1101   GstRTSPRangeUnit unit = GST_RTSP_RANGE_NPT;
1102   gchar *path, *rtpinfo;
1103   gint matched;
1104
1105   if (!(session = ctx->session))
1106     goto no_session;
1107
1108   if (!(uri = ctx->uri))
1109     goto no_uri;
1110
1111   klass = GST_RTSP_CLIENT_GET_CLASS (client);
1112   path = klass->make_path_from_uri (client, uri);
1113
1114   /* get a handle to the configuration of the media in the session */
1115   sessmedia = gst_rtsp_session_get_media (session, path, &matched);
1116   if (!sessmedia)
1117     goto not_found;
1118
1119   if (path[matched] != '\0')
1120     goto no_aggregate;
1121
1122   g_free (path);
1123
1124   ctx->sessmedia = sessmedia;
1125   ctx->media = media = gst_rtsp_session_media_get_media (sessmedia);
1126
1127   /* the session state must be playing or ready */
1128   rtspstate = gst_rtsp_session_media_get_rtsp_state (sessmedia);
1129   if (rtspstate != GST_RTSP_STATE_PLAYING && rtspstate != GST_RTSP_STATE_READY)
1130     goto invalid_state;
1131
1132   /* in play we first unsuspend, media could be suspended from SDP or PAUSED */
1133   if (!gst_rtsp_media_unsuspend (media))
1134     goto unsuspend_failed;
1135
1136   /* parse the range header if we have one */
1137   res = gst_rtsp_message_get_header (ctx->request, GST_RTSP_HDR_RANGE, &str, 0);
1138   if (res == GST_RTSP_OK) {
1139     if (gst_rtsp_range_parse (str, &range) == GST_RTSP_OK) {
1140       /* we have a range, seek to the position */
1141       unit = range->unit;
1142       gst_rtsp_media_seek (media, range);
1143       gst_rtsp_range_free (range);
1144     }
1145   }
1146
1147   /* grab RTPInfo from the media now */
1148   rtpinfo = gst_rtsp_session_media_get_rtpinfo (sessmedia);
1149
1150   /* construct the response now */
1151   code = GST_RTSP_STS_OK;
1152   gst_rtsp_message_init_response (ctx->response, code,
1153       gst_rtsp_status_as_text (code), ctx->request);
1154
1155   /* add the RTP-Info header */
1156   if (rtpinfo)
1157     gst_rtsp_message_take_header (ctx->response, GST_RTSP_HDR_RTP_INFO,
1158         rtpinfo);
1159
1160   /* add the range */
1161   str = gst_rtsp_media_get_range_string (media, TRUE, unit);
1162   if (str)
1163     gst_rtsp_message_take_header (ctx->response, GST_RTSP_HDR_RANGE, str);
1164
1165   send_message (client, ctx, ctx->response, FALSE);
1166
1167   /* start playing after sending the response */
1168   gst_rtsp_session_media_set_state (sessmedia, GST_STATE_PLAYING);
1169
1170   gst_rtsp_session_media_set_rtsp_state (sessmedia, GST_RTSP_STATE_PLAYING);
1171
1172   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_PLAY_REQUEST], 0, ctx);
1173
1174   return TRUE;
1175
1176   /* ERRORS */
1177 no_session:
1178   {
1179     GST_ERROR ("client %p: no session", client);
1180     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
1181     return FALSE;
1182   }
1183 no_uri:
1184   {
1185     GST_ERROR ("client %p: no uri supplied", client);
1186     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
1187     return FALSE;
1188   }
1189 not_found:
1190   {
1191     GST_ERROR ("client %p: media not found", client);
1192     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
1193     return FALSE;
1194   }
1195 no_aggregate:
1196   {
1197     GST_ERROR ("client %p: no aggregate path %s", client, path);
1198     send_generic_response (client,
1199         GST_RTSP_STS_ONLY_AGGREGATE_OPERATION_ALLOWED, ctx);
1200     g_free (path);
1201     return FALSE;
1202   }
1203 invalid_state:
1204   {
1205     GST_ERROR ("client %p: not PLAYING or READY", client);
1206     send_generic_response (client, GST_RTSP_STS_METHOD_NOT_VALID_IN_THIS_STATE,
1207         ctx);
1208     return FALSE;
1209   }
1210 unsuspend_failed:
1211   {
1212     GST_ERROR ("client %p: unsuspend failed", client);
1213     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, ctx);
1214     return FALSE;
1215   }
1216 }
1217
1218 static void
1219 do_keepalive (GstRTSPSession * session)
1220 {
1221   GST_INFO ("keep session %p alive", session);
1222   gst_rtsp_session_touch (session);
1223 }
1224
1225 /* parse @transport and return a valid transport in @tr. only transports
1226  * supported by @stream are returned. Returns FALSE if no valid transport
1227  * was found. */
1228 static gboolean
1229 parse_transport (const char *transport, GstRTSPStream * stream,
1230     GstRTSPTransport * tr)
1231 {
1232   gint i;
1233   gboolean res;
1234   gchar **transports;
1235
1236   res = FALSE;
1237   gst_rtsp_transport_init (tr);
1238
1239   GST_DEBUG ("parsing transports %s", transport);
1240
1241   transports = g_strsplit (transport, ",", 0);
1242
1243   /* loop through the transports, try to parse */
1244   for (i = 0; transports[i]; i++) {
1245     res = gst_rtsp_transport_parse (transports[i], tr);
1246     if (res != GST_RTSP_OK) {
1247       /* no valid transport, search some more */
1248       GST_WARNING ("could not parse transport %s", transports[i]);
1249       goto next;
1250     }
1251
1252     /* we have a transport, see if it's supported */
1253     if (!gst_rtsp_stream_is_transport_supported (stream, tr)) {
1254       GST_WARNING ("unsupported transport %s", transports[i]);
1255       goto next;
1256     }
1257
1258     /* we have a valid transport */
1259     GST_INFO ("found valid transport %s", transports[i]);
1260     res = TRUE;
1261     break;
1262
1263   next:
1264     gst_rtsp_transport_init (tr);
1265   }
1266   g_strfreev (transports);
1267
1268   return res;
1269 }
1270
1271 static gboolean
1272 default_configure_client_media (GstRTSPClient * client, GstRTSPMedia * media,
1273     GstRTSPStream * stream, GstRTSPContext * ctx)
1274 {
1275   GstRTSPMessage *request = ctx->request;
1276   gchar *blocksize_str;
1277
1278   if (gst_rtsp_message_get_header (request, GST_RTSP_HDR_BLOCKSIZE,
1279           &blocksize_str, 0) == GST_RTSP_OK) {
1280     guint64 blocksize;
1281     gchar *end;
1282
1283     blocksize = g_ascii_strtoull (blocksize_str, &end, 10);
1284     if (end == blocksize_str)
1285       goto parse_failed;
1286
1287     /* we don't want to change the mtu when this media
1288      * can be shared because it impacts other clients */
1289     if (gst_rtsp_media_is_shared (media))
1290       goto done;
1291
1292     if (blocksize > G_MAXUINT)
1293       blocksize = G_MAXUINT;
1294
1295     gst_rtsp_stream_set_mtu (stream, blocksize);
1296   }
1297 done:
1298   return TRUE;
1299
1300   /* ERRORS */
1301 parse_failed:
1302   {
1303     GST_ERROR_OBJECT (client, "failed to parse blocksize");
1304     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
1305     return FALSE;
1306   }
1307 }
1308
1309 static gboolean
1310 default_configure_client_transport (GstRTSPClient * client,
1311     GstRTSPContext * ctx, GstRTSPTransport * ct)
1312 {
1313   GstRTSPClientPrivate *priv = client->priv;
1314
1315   /* we have a valid transport now, set the destination of the client. */
1316   if (ct->lower_transport == GST_RTSP_LOWER_TRANS_UDP_MCAST) {
1317     gboolean use_client_settings;
1318
1319     use_client_settings =
1320         gst_rtsp_auth_check (GST_RTSP_AUTH_CHECK_TRANSPORT_CLIENT_SETTINGS);
1321
1322     if (ct->destination && use_client_settings) {
1323       GstRTSPAddress *addr;
1324
1325       addr = gst_rtsp_stream_reserve_address (ctx->stream, ct->destination,
1326           ct->port.min, ct->port.max - ct->port.min + 1, ct->ttl);
1327
1328       if (addr == NULL)
1329         goto no_address;
1330
1331       gst_rtsp_address_free (addr);
1332     } else {
1333       GstRTSPAddress *addr;
1334       GSocketFamily family;
1335
1336       family = priv->is_ipv6 ? G_SOCKET_FAMILY_IPV6 : G_SOCKET_FAMILY_IPV4;
1337
1338       addr = gst_rtsp_stream_get_multicast_address (ctx->stream, family);
1339       if (addr == NULL)
1340         goto no_address;
1341
1342       g_free (ct->destination);
1343       ct->destination = g_strdup (addr->address);
1344       ct->port.min = addr->port;
1345       ct->port.max = addr->port + addr->n_ports - 1;
1346       ct->ttl = addr->ttl;
1347
1348       gst_rtsp_address_free (addr);
1349     }
1350   } else {
1351     GstRTSPUrl *url;
1352
1353     url = gst_rtsp_connection_get_url (priv->connection);
1354     g_free (ct->destination);
1355     ct->destination = g_strdup (url->host);
1356
1357     if (ct->lower_transport & GST_RTSP_LOWER_TRANS_TCP) {
1358       GSocket *sock;
1359       GSocketAddress *addr;
1360
1361       sock = gst_rtsp_connection_get_read_socket (priv->connection);
1362       if ((addr = g_socket_get_remote_address (sock, NULL))) {
1363         /* our read port is the sender port of client */
1364         ct->client_port.min =
1365             g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (addr));
1366         g_object_unref (addr);
1367       }
1368       if ((addr = g_socket_get_local_address (sock, NULL))) {
1369         ct->server_port.max =
1370             g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (addr));
1371         g_object_unref (addr);
1372       }
1373       sock = gst_rtsp_connection_get_write_socket (priv->connection);
1374       if ((addr = g_socket_get_remote_address (sock, NULL))) {
1375         /* our write port is the receiver port of client */
1376         ct->client_port.max =
1377             g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (addr));
1378         g_object_unref (addr);
1379       }
1380       if ((addr = g_socket_get_local_address (sock, NULL))) {
1381         ct->server_port.min =
1382             g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (addr));
1383         g_object_unref (addr);
1384       }
1385       /* check if the client selected channels for TCP */
1386       if (ct->interleaved.min == -1 || ct->interleaved.max == -1) {
1387         gst_rtsp_session_media_alloc_channels (ctx->sessmedia,
1388             &ct->interleaved);
1389       }
1390     }
1391   }
1392   return TRUE;
1393
1394   /* ERRORS */
1395 no_address:
1396   {
1397     GST_ERROR_OBJECT (client, "failed to acquire address for stream");
1398     return FALSE;
1399   }
1400 }
1401
1402 static GstRTSPTransport *
1403 make_server_transport (GstRTSPClient * client, GstRTSPContext * ctx,
1404     GstRTSPTransport * ct)
1405 {
1406   GstRTSPTransport *st;
1407   GInetAddress *addr;
1408   GSocketFamily family;
1409
1410   /* prepare the server transport */
1411   gst_rtsp_transport_new (&st);
1412
1413   st->trans = ct->trans;
1414   st->profile = ct->profile;
1415   st->lower_transport = ct->lower_transport;
1416
1417   addr = g_inet_address_new_from_string (ct->destination);
1418
1419   if (!addr) {
1420     GST_ERROR ("failed to get inet addr from client destination");
1421     family = G_SOCKET_FAMILY_IPV4;
1422   } else {
1423     family = g_inet_address_get_family (addr);
1424     g_object_unref (addr);
1425     addr = NULL;
1426   }
1427
1428   switch (st->lower_transport) {
1429     case GST_RTSP_LOWER_TRANS_UDP:
1430       st->client_port = ct->client_port;
1431       gst_rtsp_stream_get_server_port (ctx->stream, &st->server_port, family);
1432       break;
1433     case GST_RTSP_LOWER_TRANS_UDP_MCAST:
1434       st->port = ct->port;
1435       st->destination = g_strdup (ct->destination);
1436       st->ttl = ct->ttl;
1437       break;
1438     case GST_RTSP_LOWER_TRANS_TCP:
1439       st->interleaved = ct->interleaved;
1440       st->client_port = ct->client_port;
1441       st->server_port = ct->server_port;
1442     default:
1443       break;
1444   }
1445
1446   gst_rtsp_stream_get_ssrc (ctx->stream, &st->ssrc);
1447
1448   return st;
1449 }
1450
1451 #define AES_128_KEY_LEN 16
1452 #define AES_256_KEY_LEN 32
1453
1454 #define HMAC_32_KEY_LEN 4
1455 #define HMAC_80_KEY_LEN 10
1456
1457 static gboolean
1458 mikey_apply_policy (GstCaps * caps, GstMIKEYMessage * msg, guint8 policy)
1459 {
1460   const gchar *srtp_cipher;
1461   const gchar *srtp_auth;
1462   const GstMIKEYPayload *sp;
1463   guint i;
1464
1465   /* loop over Security policy until we find one containing policy */
1466   for (i = 0;; i++) {
1467     if ((sp = gst_mikey_message_find_payload (msg, GST_MIKEY_PT_SP, i)) == NULL)
1468       break;
1469
1470     if (((GstMIKEYPayloadSP *) sp)->policy == policy)
1471       break;
1472   }
1473
1474   /* the default ciphers */
1475   srtp_cipher = "aes-128-icm";
1476   srtp_auth = "hmac-sha1-80";
1477
1478   /* now override the defaults with what is in the Security Policy */
1479   if (sp != NULL) {
1480     guint len;
1481
1482     /* collect all the params and go over them */
1483     len = gst_mikey_payload_sp_get_n_params (sp);
1484     for (i = 0; i < len; i++) {
1485       const GstMIKEYPayloadSPParam *param =
1486           gst_mikey_payload_sp_get_param (sp, i);
1487
1488       switch (param->type) {
1489         case GST_MIKEY_SP_SRTP_ENC_ALG:
1490           switch (param->val[0]) {
1491             case 0:
1492               srtp_cipher = "null";
1493               break;
1494             case 2:
1495             case 1:
1496               srtp_cipher = "aes-128-icm";
1497               break;
1498             default:
1499               break;
1500           }
1501           break;
1502         case GST_MIKEY_SP_SRTP_ENC_KEY_LEN:
1503           switch (param->val[0]) {
1504             case AES_128_KEY_LEN:
1505               srtp_cipher = "aes-128-icm";
1506               break;
1507             case AES_256_KEY_LEN:
1508               srtp_cipher = "aes-256-icm";
1509               break;
1510             default:
1511               break;
1512           }
1513           break;
1514         case GST_MIKEY_SP_SRTP_AUTH_ALG:
1515           switch (param->val[0]) {
1516             case 0:
1517               srtp_auth = "null";
1518               break;
1519             case 2:
1520             case 1:
1521               srtp_auth = "hmac-sha1-80";
1522               break;
1523             default:
1524               break;
1525           }
1526           break;
1527         case GST_MIKEY_SP_SRTP_AUTH_KEY_LEN:
1528           switch (param->val[0]) {
1529             case HMAC_32_KEY_LEN:
1530               srtp_auth = "hmac-sha1-32";
1531               break;
1532             case HMAC_80_KEY_LEN:
1533               srtp_auth = "hmac-sha1-80";
1534               break;
1535             default:
1536               break;
1537           }
1538           break;
1539         case GST_MIKEY_SP_SRTP_SRTP_ENC:
1540           break;
1541         case GST_MIKEY_SP_SRTP_SRTCP_ENC:
1542           break;
1543         default:
1544           break;
1545       }
1546     }
1547   }
1548   /* now configure the SRTP parameters */
1549   gst_caps_set_simple (caps,
1550       "srtp-cipher", G_TYPE_STRING, srtp_cipher,
1551       "srtp-auth", G_TYPE_STRING, srtp_auth,
1552       "srtcp-cipher", G_TYPE_STRING, srtp_cipher,
1553       "srtcp-auth", G_TYPE_STRING, srtp_auth, NULL);
1554
1555   return TRUE;
1556 }
1557
1558 static gboolean
1559 handle_mikey_data (GstRTSPClient * client, GstRTSPContext * ctx,
1560     guint8 * data, gsize size)
1561 {
1562   GstMIKEYMessage *msg;
1563   guint i, n_cs;
1564   GstCaps *caps = NULL;
1565   GstMIKEYPayloadKEMAC *kemac;
1566   const GstMIKEYPayloadKeyData *pkd;
1567   GstBuffer *key;
1568
1569   /* the MIKEY message contains a CSB or crypto session bundle. It is a
1570    * set of Crypto Sessions protected with the same master key.
1571    * In the context of SRTP, an RTP and its RTCP stream is part of a
1572    * crypto session */
1573   if ((msg = gst_mikey_message_new_from_data (data, size, NULL, NULL)) == NULL)
1574     goto parse_failed;
1575
1576   /* we can only handle SRTP crypto sessions for now */
1577   if (msg->map_type != GST_MIKEY_MAP_TYPE_SRTP)
1578     goto invalid_map_type;
1579
1580   /* get the number of crypto sessions. This maps SSRC to its
1581    * security parameters */
1582   n_cs = gst_mikey_message_get_n_cs (msg);
1583   if (n_cs == 0)
1584     goto no_crypto_sessions;
1585
1586   /* we also need keys */
1587   if (!(kemac = (GstMIKEYPayloadKEMAC *) gst_mikey_message_find_payload
1588           (msg, GST_MIKEY_PT_KEMAC, 0)))
1589     goto no_keys;
1590
1591   /* we don't support encrypted keys */
1592   if (kemac->enc_alg != GST_MIKEY_ENC_NULL
1593       || kemac->mac_alg != GST_MIKEY_MAC_NULL)
1594     goto unsupported_encryption;
1595
1596   /* get Key data sub-payload */
1597   pkd = (const GstMIKEYPayloadKeyData *)
1598       gst_mikey_payload_kemac_get_sub (&kemac->pt, 0);
1599
1600   key =
1601       gst_buffer_new_wrapped (g_memdup (pkd->key_data, pkd->key_len),
1602       pkd->key_len);
1603
1604   /* go over all crypto sessions and create the security policy for each
1605    * SSRC */
1606   for (i = 0; i < n_cs; i++) {
1607     const GstMIKEYMapSRTP *map = gst_mikey_message_get_cs_srtp (msg, i);
1608
1609     caps = gst_caps_new_simple ("application/x-srtp",
1610         "ssrc", G_TYPE_UINT, map->ssrc,
1611         "roc", G_TYPE_UINT, map->roc, "srtp-key", GST_TYPE_BUFFER, key, NULL);
1612     mikey_apply_policy (caps, msg, map->policy);
1613
1614     gst_rtsp_stream_update_crypto (ctx->stream, map->ssrc, caps);
1615     gst_caps_unref (caps);
1616   }
1617   gst_mikey_message_unref (msg);
1618   gst_buffer_unref (key);
1619
1620   return TRUE;
1621
1622   /* ERRORS */
1623 parse_failed:
1624   {
1625     GST_DEBUG_OBJECT (client, "failed to parse MIKEY message");
1626     return FALSE;
1627   }
1628 invalid_map_type:
1629   {
1630     GST_DEBUG_OBJECT (client, "invalid map type %d", msg->map_type);
1631     goto cleanup_message;
1632   }
1633 no_crypto_sessions:
1634   {
1635     GST_DEBUG_OBJECT (client, "no crypto sessions");
1636     goto cleanup_message;
1637   }
1638 no_keys:
1639   {
1640     GST_DEBUG_OBJECT (client, "no keys found");
1641     goto cleanup_message;
1642   }
1643 unsupported_encryption:
1644   {
1645     GST_DEBUG_OBJECT (client, "unsupported key encryption");
1646     goto cleanup_message;
1647   }
1648 cleanup_message:
1649   {
1650     gst_mikey_message_unref (msg);
1651     return FALSE;
1652   }
1653 }
1654
1655 #define IS_STRIP_CHAR(c) (g_ascii_isspace ((guchar)(c)) || ((c) == '\"'))
1656
1657 static void
1658 strip_chars (gchar * str)
1659 {
1660   gchar *s;
1661   gsize len;
1662
1663   len = strlen (str);
1664   while (len--) {
1665     if (!IS_STRIP_CHAR (str[len]))
1666       break;
1667     str[len] = '\0';
1668   }
1669   for (s = str; *s && IS_STRIP_CHAR (*s); s++);
1670   memmove (str, s, len + 1);
1671 }
1672
1673 /* KeyMgmt = "KeyMgmt" ":" key-mgmt-spec 0*("," key-mgmt-spec)
1674  * key-mgmt-spec = "prot" "=" KMPID ";" ["uri" "=" %x22 URI %x22 ";"]
1675  */
1676 static gboolean
1677 handle_keymgmt (GstRTSPClient * client, GstRTSPContext * ctx, gchar * keymgmt)
1678 {
1679   gchar **specs;
1680   gint i, j;
1681
1682   specs = g_strsplit (keymgmt, ",", 0);
1683   for (i = 0; specs[i]; i++) {
1684     gchar **split;
1685
1686     split = g_strsplit (specs[i], ";", 0);
1687     for (j = 0; split[j]; j++) {
1688       g_strstrip (split[j]);
1689       if (g_str_has_prefix (split[j], "prot=")) {
1690         g_strstrip (split[j] + 5);
1691         if (!g_str_equal (split[j] + 5, "mikey"))
1692           break;
1693         GST_DEBUG ("found mikey");
1694       } else if (g_str_has_prefix (split[j], "uri=")) {
1695         strip_chars (split[j] + 4);
1696         GST_DEBUG ("found uri '%s'", split[j] + 4);
1697       } else if (g_str_has_prefix (split[j], "data=")) {
1698         guchar *data;
1699         gsize size;
1700         strip_chars (split[j] + 5);
1701         GST_DEBUG ("found data '%s'", split[j] + 5);
1702         data = g_base64_decode_inplace (split[j] + 5, &size);
1703         handle_mikey_data (client, ctx, data, size);
1704       }
1705     }
1706     g_strfreev (split);
1707   }
1708   g_strfreev (specs);
1709   return TRUE;
1710 }
1711
1712 static gboolean
1713 handle_setup_request (GstRTSPClient * client, GstRTSPContext * ctx)
1714 {
1715   GstRTSPClientPrivate *priv = client->priv;
1716   GstRTSPResult res;
1717   GstRTSPUrl *uri;
1718   gchar *transport, *keymgmt;
1719   GstRTSPTransport *ct, *st;
1720   GstRTSPStatusCode code;
1721   GstRTSPSession *session;
1722   GstRTSPStreamTransport *trans;
1723   gchar *trans_str;
1724   GstRTSPSessionMedia *sessmedia;
1725   GstRTSPMedia *media;
1726   GstRTSPStream *stream;
1727   GstRTSPState rtspstate;
1728   GstRTSPClientClass *klass;
1729   gchar *path, *control = NULL;
1730   gint matched;
1731   gboolean new_session = FALSE;
1732
1733   if (!ctx->uri)
1734     goto no_uri;
1735
1736   uri = ctx->uri;
1737   klass = GST_RTSP_CLIENT_GET_CLASS (client);
1738   path = klass->make_path_from_uri (client, uri);
1739
1740   /* parse the transport */
1741   res =
1742       gst_rtsp_message_get_header (ctx->request, GST_RTSP_HDR_TRANSPORT,
1743       &transport, 0);
1744   if (res != GST_RTSP_OK)
1745     goto no_transport;
1746
1747   /* we create the session after parsing stuff so that we don't make
1748    * a session for malformed requests */
1749   if (priv->session_pool == NULL)
1750     goto no_pool;
1751
1752   session = ctx->session;
1753
1754   if (session) {
1755     g_object_ref (session);
1756     /* get a handle to the configuration of the media in the session, this can
1757      * return NULL if this is a new url to manage in this session. */
1758     sessmedia = gst_rtsp_session_get_media (session, path, &matched);
1759   } else {
1760     /* we need a new media configuration in this session */
1761     sessmedia = NULL;
1762   }
1763
1764   /* we have no session media, find one and manage it */
1765   if (sessmedia == NULL) {
1766     /* get a handle to the configuration of the media in the session */
1767     media = find_media (client, ctx, path, &matched);
1768   } else {
1769     if ((media = gst_rtsp_session_media_get_media (sessmedia)))
1770       g_object_ref (media);
1771     else
1772       goto media_not_found;
1773   }
1774   /* no media, not found then */
1775   if (media == NULL)
1776     goto media_not_found_no_reply;
1777
1778   if (path[matched] == '\0') {
1779     if (gst_rtsp_media_n_streams (media) == 1) {
1780       stream = gst_rtsp_media_get_stream (media, 0);
1781     } else {
1782       goto control_not_found;
1783     }
1784   } else {
1785     /* path is what matched. */
1786     path[matched] = '\0';
1787     /* control is remainder */
1788     control = &path[matched + 1];
1789
1790     /* find the stream now using the control part */
1791     stream = gst_rtsp_media_find_stream (media, control);
1792   }
1793
1794   if (stream == NULL)
1795     goto stream_not_found;
1796
1797   /* now we have a uri identifying a valid media and stream */
1798   ctx->stream = stream;
1799   ctx->media = media;
1800
1801   if (session == NULL) {
1802     /* create a session if this fails we probably reached our session limit or
1803      * something. */
1804     if (!(session = gst_rtsp_session_pool_create (priv->session_pool)))
1805       goto service_unavailable;
1806
1807     /* make sure this client is closed when the session is closed */
1808     client_watch_session (client, session);
1809
1810     new_session = TRUE;
1811     /* signal new session */
1812     g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_NEW_SESSION], 0,
1813         session);
1814
1815     ctx->session = session;
1816   }
1817
1818   if (!klass->configure_client_media (client, media, stream, ctx))
1819     goto configure_media_failed_no_reply;
1820
1821   gst_rtsp_transport_new (&ct);
1822
1823   /* parse and find a usable supported transport */
1824   if (!parse_transport (transport, stream, ct))
1825     goto unsupported_transports;
1826
1827   /* parse the keymgmt */
1828   if (gst_rtsp_message_get_header (ctx->request, GST_RTSP_HDR_KEYMGMT,
1829           &keymgmt, 0) == GST_RTSP_OK) {
1830     if (!handle_keymgmt (client, ctx, keymgmt))
1831       goto keymgmt_error;
1832   }
1833
1834   if (sessmedia == NULL) {
1835     /* manage the media in our session now, if not done already  */
1836     sessmedia = gst_rtsp_session_manage_media (session, path, media);
1837     /* if we stil have no media, error */
1838     if (sessmedia == NULL)
1839       goto sessmedia_unavailable;
1840
1841     /* don't cache media anymore */
1842     clean_cached_media (client, FALSE);
1843   } else {
1844     g_object_unref (media);
1845   }
1846
1847   ctx->sessmedia = sessmedia;
1848
1849   /* update the client transport */
1850   if (!klass->configure_client_transport (client, ctx, ct))
1851     goto unsupported_client_transport;
1852
1853   /* set in the session media transport */
1854   trans = gst_rtsp_session_media_set_transport (sessmedia, stream, ct);
1855
1856   ctx->trans = trans;
1857
1858   /* configure the url used to set this transport, this we will use when
1859    * generating the response for the PLAY request */
1860   gst_rtsp_stream_transport_set_url (trans, uri);
1861   /* configure keepalive for this transport */
1862   gst_rtsp_stream_transport_set_keepalive (trans,
1863       (GstRTSPKeepAliveFunc) do_keepalive, session, NULL);
1864
1865   if (ct->lower_transport == GST_RTSP_LOWER_TRANS_TCP) {
1866     /* our callbacks to send data on this TCP connection */
1867     gst_rtsp_stream_transport_set_callbacks (trans,
1868         (GstRTSPSendFunc) do_send_data,
1869         (GstRTSPSendFunc) do_send_data, client, NULL);
1870
1871     g_hash_table_insert (priv->transports,
1872         GINT_TO_POINTER (ct->interleaved.min), trans);
1873     g_object_ref (trans);
1874     g_hash_table_insert (priv->transports,
1875         GINT_TO_POINTER (ct->interleaved.max), trans);
1876     g_object_ref (trans);
1877   }
1878
1879   /* create and serialize the server transport */
1880   st = make_server_transport (client, ctx, ct);
1881   trans_str = gst_rtsp_transport_as_text (st);
1882   gst_rtsp_transport_free (st);
1883
1884   /* construct the response now */
1885   code = GST_RTSP_STS_OK;
1886   gst_rtsp_message_init_response (ctx->response, code,
1887       gst_rtsp_status_as_text (code), ctx->request);
1888
1889   gst_rtsp_message_add_header (ctx->response, GST_RTSP_HDR_TRANSPORT,
1890       trans_str);
1891   g_free (trans_str);
1892
1893   send_message (client, ctx, ctx->response, FALSE);
1894
1895   /* update the state */
1896   rtspstate = gst_rtsp_session_media_get_rtsp_state (sessmedia);
1897   switch (rtspstate) {
1898     case GST_RTSP_STATE_PLAYING:
1899     case GST_RTSP_STATE_RECORDING:
1900     case GST_RTSP_STATE_READY:
1901       /* no state change */
1902       break;
1903     default:
1904       gst_rtsp_session_media_set_rtsp_state (sessmedia, GST_RTSP_STATE_READY);
1905       break;
1906   }
1907   g_object_unref (session);
1908   g_free (path);
1909
1910   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_SETUP_REQUEST], 0, ctx);
1911
1912   return TRUE;
1913
1914   /* ERRORS */
1915 no_uri:
1916   {
1917     GST_ERROR ("client %p: no uri", client);
1918     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
1919     return FALSE;
1920   }
1921 no_transport:
1922   {
1923     GST_ERROR ("client %p: no transport", client);
1924     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, ctx);
1925     goto cleanup_path;
1926   }
1927 no_pool:
1928   {
1929     GST_ERROR ("client %p: no session pool configured", client);
1930     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
1931     goto cleanup_path;
1932   }
1933 media_not_found_no_reply:
1934   {
1935     GST_ERROR ("client %p: media '%s' not found", client, path);
1936     /* error reply is already sent */
1937     goto cleanup_path;
1938   }
1939 media_not_found:
1940   {
1941     GST_ERROR ("client %p: media '%s' not found", client, path);
1942     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
1943     goto cleanup_path;
1944   }
1945 control_not_found:
1946   {
1947     GST_ERROR ("client %p: no control in path '%s'", client, path);
1948     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
1949     g_object_unref (media);
1950     goto cleanup_path;
1951   }
1952 stream_not_found:
1953   {
1954     GST_ERROR ("client %p: stream '%s' not found", client,
1955         GST_STR_NULL (control));
1956     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
1957     g_object_unref (media);
1958     goto cleanup_path;
1959   }
1960 service_unavailable:
1961   {
1962     GST_ERROR ("client %p: can't create session", client);
1963     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, ctx);
1964     g_object_unref (media);
1965     goto cleanup_path;
1966   }
1967 sessmedia_unavailable:
1968   {
1969     GST_ERROR ("client %p: can't create session media", client);
1970     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, ctx);
1971     g_object_unref (media);
1972     goto cleanup_session;
1973   }
1974 configure_media_failed_no_reply:
1975   {
1976     GST_ERROR ("client %p: configure_media failed", client);
1977     /* error reply is already sent */
1978     goto cleanup_session;
1979   }
1980 unsupported_transports:
1981   {
1982     GST_ERROR ("client %p: unsupported transports", client);
1983     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, ctx);
1984     goto cleanup_transport;
1985   }
1986 unsupported_client_transport:
1987   {
1988     GST_ERROR ("client %p: unsupported client transport", client);
1989     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, ctx);
1990     goto cleanup_transport;
1991   }
1992 keymgmt_error:
1993   {
1994     GST_ERROR ("client %p: keymgmt error", client);
1995     send_generic_response (client, GST_RTSP_STS_KEY_MANAGEMENT_FAILURE, ctx);
1996     goto cleanup_transport;
1997   }
1998   {
1999   cleanup_transport:
2000     gst_rtsp_transport_free (ct);
2001   cleanup_session:
2002     if (new_session)
2003       gst_rtsp_session_pool_remove (priv->session_pool, session);
2004     g_object_unref (session);
2005   cleanup_path:
2006     g_free (path);
2007     return FALSE;
2008   }
2009 }
2010
2011 static GstSDPMessage *
2012 create_sdp (GstRTSPClient * client, GstRTSPMedia * media)
2013 {
2014   GstRTSPClientPrivate *priv = client->priv;
2015   GstSDPMessage *sdp;
2016   GstSDPInfo info;
2017   const gchar *proto;
2018   guint64 session_id_tmp;
2019   gchar session_id[21];
2020
2021   gst_sdp_message_new (&sdp);
2022
2023   /* some standard things first */
2024   gst_sdp_message_set_version (sdp, "0");
2025
2026   if (priv->is_ipv6)
2027     proto = "IP6";
2028   else
2029     proto = "IP4";
2030
2031   session_id_tmp = (((guint64) g_random_int ()) << 32) | g_random_int ();
2032   g_snprintf (session_id, sizeof (session_id), "%" G_GUINT64_FORMAT,
2033       session_id_tmp);
2034
2035   gst_sdp_message_set_origin (sdp, "-", session_id, "1", "IN", proto,
2036       priv->server_ip);
2037
2038   gst_sdp_message_set_session_name (sdp, "Session streamed with GStreamer");
2039   gst_sdp_message_set_information (sdp, "rtsp-server");
2040   gst_sdp_message_add_time (sdp, "0", "0", NULL);
2041   gst_sdp_message_add_attribute (sdp, "tool", "GStreamer");
2042   gst_sdp_message_add_attribute (sdp, "type", "broadcast");
2043   gst_sdp_message_add_attribute (sdp, "control", "*");
2044
2045   info.is_ipv6 = priv->is_ipv6;
2046   info.server_ip = priv->server_ip;
2047
2048   /* create an SDP for the media object */
2049   if (!gst_rtsp_media_setup_sdp (media, sdp, &info))
2050     goto no_sdp;
2051
2052   return sdp;
2053
2054   /* ERRORS */
2055 no_sdp:
2056   {
2057     GST_ERROR ("client %p: could not create SDP", client);
2058     gst_sdp_message_free (sdp);
2059     return NULL;
2060   }
2061 }
2062
2063 /* for the describe we must generate an SDP */
2064 static gboolean
2065 handle_describe_request (GstRTSPClient * client, GstRTSPContext * ctx)
2066 {
2067   GstRTSPClientPrivate *priv = client->priv;
2068   GstRTSPResult res;
2069   GstSDPMessage *sdp;
2070   guint i;
2071   gchar *path, *str;
2072   GstRTSPMedia *media;
2073   GstRTSPClientClass *klass;
2074
2075   klass = GST_RTSP_CLIENT_GET_CLASS (client);
2076
2077   if (!ctx->uri)
2078     goto no_uri;
2079
2080   /* check what kind of format is accepted, we don't really do anything with it
2081    * and always return SDP for now. */
2082   for (i = 0;; i++) {
2083     gchar *accept;
2084
2085     res =
2086         gst_rtsp_message_get_header (ctx->request, GST_RTSP_HDR_ACCEPT,
2087         &accept, i);
2088     if (res == GST_RTSP_ENOTIMPL)
2089       break;
2090
2091     if (g_ascii_strcasecmp (accept, "application/sdp") == 0)
2092       break;
2093   }
2094
2095   if (!priv->mount_points)
2096     goto no_mount_points;
2097
2098   if (!(path = gst_rtsp_mount_points_make_path (priv->mount_points, ctx->uri)))
2099     goto no_path;
2100
2101   /* find the media object for the uri */
2102   if (!(media = find_media (client, ctx, path, NULL)))
2103     goto no_media;
2104
2105   /* create an SDP for the media object on this client */
2106   if (!(sdp = klass->create_sdp (client, media)))
2107     goto no_sdp;
2108
2109   /* we suspend after the describe */
2110   gst_rtsp_media_suspend (media);
2111   g_object_unref (media);
2112
2113   gst_rtsp_message_init_response (ctx->response, GST_RTSP_STS_OK,
2114       gst_rtsp_status_as_text (GST_RTSP_STS_OK), ctx->request);
2115
2116   gst_rtsp_message_add_header (ctx->response, GST_RTSP_HDR_CONTENT_TYPE,
2117       "application/sdp");
2118
2119   /* content base for some clients that might screw up creating the setup uri */
2120   str = make_base_url (client, ctx->uri, path);
2121   g_free (path);
2122
2123   GST_INFO ("adding content-base: %s", str);
2124   gst_rtsp_message_take_header (ctx->response, GST_RTSP_HDR_CONTENT_BASE, str);
2125
2126   /* add SDP to the response body */
2127   str = gst_sdp_message_as_text (sdp);
2128   gst_rtsp_message_take_body (ctx->response, (guint8 *) str, strlen (str));
2129   gst_sdp_message_free (sdp);
2130
2131   send_message (client, ctx, ctx->response, FALSE);
2132
2133   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_DESCRIBE_REQUEST],
2134       0, ctx);
2135
2136   return TRUE;
2137
2138   /* ERRORS */
2139 no_uri:
2140   {
2141     GST_ERROR ("client %p: no uri", client);
2142     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
2143     return FALSE;
2144   }
2145 no_mount_points:
2146   {
2147     GST_ERROR ("client %p: no mount points configured", client);
2148     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
2149     return FALSE;
2150   }
2151 no_path:
2152   {
2153     GST_ERROR ("client %p: can't find path for url", client);
2154     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
2155     return FALSE;
2156   }
2157 no_media:
2158   {
2159     GST_ERROR ("client %p: no media", client);
2160     g_free (path);
2161     /* error reply is already sent */
2162     return FALSE;
2163   }
2164 no_sdp:
2165   {
2166     GST_ERROR ("client %p: can't create SDP", client);
2167     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, ctx);
2168     g_free (path);
2169     g_object_unref (media);
2170     return FALSE;
2171   }
2172 }
2173
2174 static gboolean
2175 handle_options_request (GstRTSPClient * client, GstRTSPContext * ctx)
2176 {
2177   GstRTSPMethod options;
2178   gchar *str;
2179
2180   options = GST_RTSP_DESCRIBE |
2181       GST_RTSP_OPTIONS |
2182       GST_RTSP_PAUSE |
2183       GST_RTSP_PLAY |
2184       GST_RTSP_SETUP |
2185       GST_RTSP_GET_PARAMETER | GST_RTSP_SET_PARAMETER | GST_RTSP_TEARDOWN;
2186
2187   str = gst_rtsp_options_as_text (options);
2188
2189   gst_rtsp_message_init_response (ctx->response, GST_RTSP_STS_OK,
2190       gst_rtsp_status_as_text (GST_RTSP_STS_OK), ctx->request);
2191
2192   gst_rtsp_message_add_header (ctx->response, GST_RTSP_HDR_PUBLIC, str);
2193   g_free (str);
2194
2195   send_message (client, ctx, ctx->response, FALSE);
2196
2197   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_OPTIONS_REQUEST],
2198       0, ctx);
2199
2200   return TRUE;
2201 }
2202
2203 /* remove duplicate and trailing '/' */
2204 static void
2205 sanitize_uri (GstRTSPUrl * uri)
2206 {
2207   gint i, len;
2208   gchar *s, *d;
2209   gboolean have_slash, prev_slash;
2210
2211   s = d = uri->abspath;
2212   len = strlen (uri->abspath);
2213
2214   prev_slash = FALSE;
2215
2216   for (i = 0; i < len; i++) {
2217     have_slash = s[i] == '/';
2218     *d = s[i];
2219     if (!have_slash || !prev_slash)
2220       d++;
2221     prev_slash = have_slash;
2222   }
2223   len = d - uri->abspath;
2224   /* don't remove the first slash if that's the only thing left */
2225   if (len > 1 && *(d - 1) == '/')
2226     d--;
2227   *d = '\0';
2228 }
2229
2230 /* is called when the session is removed from its session pool. */
2231 static void
2232 client_session_removed (GstRTSPSessionPool * pool, GstRTSPSession * session,
2233     GstRTSPClient * client)
2234 {
2235   GstRTSPClientPrivate *priv = client->priv;
2236
2237   GST_INFO ("client %p: session %p removed", client, session);
2238
2239   g_mutex_lock (&priv->lock);
2240   if (priv->watch != NULL)
2241     gst_rtsp_watch_set_send_backlog (priv->watch, 0, 0);
2242   client_unwatch_session (client, session, NULL);
2243   if (priv->watch != NULL)
2244     gst_rtsp_watch_set_send_backlog (priv->watch, 0, WATCH_BACKLOG_SIZE);
2245   g_mutex_unlock (&priv->lock);
2246 }
2247
2248 /* Returns TRUE if there are no Require headers, otherwise returns FALSE
2249  * and also returns a newly-allocated string of (comma-separated) unsupported
2250  * options in the unsupported_reqs variable .
2251  *
2252  * There may be multiple Require headers, but we must send one single
2253  * Unsupported header with all the unsupported options as response. If
2254  * an incoming Require header contained a comma-separated list of options
2255  * GstRtspConnection will already have split that list up into multiple
2256  * headers.
2257  *
2258  * TODO: allow the application to decide what features are supported
2259  */
2260 static gboolean
2261 check_request_requirements (GstRTSPMessage * msg, gchar ** unsupported_reqs)
2262 {
2263   GstRTSPResult res;
2264   GPtrArray *arr = NULL;
2265   gchar *reqs = NULL;
2266   gint i;
2267
2268   i = 0;
2269   do {
2270     res = gst_rtsp_message_get_header (msg, GST_RTSP_HDR_REQUIRE, &reqs, i++);
2271
2272     if (res == GST_RTSP_ENOTIMPL)
2273       break;
2274
2275     if (arr == NULL)
2276       arr = g_ptr_array_new_with_free_func ((GDestroyNotify) g_free);
2277
2278     g_ptr_array_add (arr, g_strdup (reqs));
2279   }
2280   while (TRUE);
2281
2282   /* if we don't have any Require headers at all, all is fine */
2283   if (i == 1)
2284     return TRUE;
2285
2286   /* otherwise we've now processed at all the Require headers */
2287   g_ptr_array_add (arr, NULL);
2288
2289   /* for now we don't commit to supporting anything, so will just report
2290    * all of the required options as unsupported */
2291   *unsupported_reqs = g_strjoinv (", ", (gchar **) arr->pdata);
2292
2293   g_ptr_array_unref (arr);
2294   return FALSE;
2295 }
2296
2297 static void
2298 handle_request (GstRTSPClient * client, GstRTSPMessage * request)
2299 {
2300   GstRTSPClientPrivate *priv = client->priv;
2301   GstRTSPMethod method;
2302   const gchar *uristr;
2303   GstRTSPUrl *uri = NULL;
2304   GstRTSPVersion version;
2305   GstRTSPResult res;
2306   GstRTSPSession *session = NULL;
2307   GstRTSPContext sctx = { NULL }, *ctx;
2308   GstRTSPMessage response = { 0 };
2309   gchar *unsupported_reqs = NULL;
2310   gchar *sessid;
2311
2312   if (!(ctx = gst_rtsp_context_get_current ())) {
2313     ctx = &sctx;
2314     ctx->auth = priv->auth;
2315     gst_rtsp_context_push_current (ctx);
2316   }
2317
2318   ctx->conn = priv->connection;
2319   ctx->client = client;
2320   ctx->request = request;
2321   ctx->response = &response;
2322
2323   if (gst_debug_category_get_threshold (rtsp_client_debug) >= GST_LEVEL_LOG) {
2324     gst_rtsp_message_dump (request);
2325   }
2326
2327   gst_rtsp_message_parse_request (request, &method, &uristr, &version);
2328
2329   GST_INFO ("client %p: received a request %s %s %s", client,
2330       gst_rtsp_method_as_text (method), uristr,
2331       gst_rtsp_version_as_text (version));
2332
2333   /* we can only handle 1.0 requests */
2334   if (version != GST_RTSP_VERSION_1_0)
2335     goto not_supported;
2336
2337   ctx->method = method;
2338
2339   /* we always try to parse the url first */
2340   if (strcmp (uristr, "*") == 0) {
2341     /* special case where we have * as uri, keep uri = NULL */
2342   } else if (gst_rtsp_url_parse (uristr, &uri) != GST_RTSP_OK) {
2343     /* check if the uristr is an absolute path <=> scheme and host information
2344      * is missing */
2345     gchar *scheme;
2346
2347     scheme = g_uri_parse_scheme (uristr);
2348     if (scheme == NULL && g_str_has_prefix (uristr, "/")) {
2349       gchar *absolute_uristr = NULL;
2350
2351       GST_WARNING_OBJECT (client, "request doesn't contain absolute url");
2352       if (priv->server_ip == NULL) {
2353         GST_WARNING_OBJECT (client, "host information missing");
2354         goto bad_request;
2355       }
2356
2357       absolute_uristr =
2358           g_strdup_printf ("rtsp://%s%s", priv->server_ip, uristr);
2359
2360       GST_DEBUG_OBJECT (client, "absolute url: %s", absolute_uristr);
2361       if (gst_rtsp_url_parse (absolute_uristr, &uri) != GST_RTSP_OK) {
2362         g_free (absolute_uristr);
2363         goto bad_request;
2364       }
2365       g_free (absolute_uristr);
2366     } else {
2367       g_free (scheme);
2368       goto bad_request;
2369     }
2370   }
2371
2372   /* get the session if there is any */
2373   res = gst_rtsp_message_get_header (request, GST_RTSP_HDR_SESSION, &sessid, 0);
2374   if (res == GST_RTSP_OK) {
2375     if (priv->session_pool == NULL)
2376       goto no_pool;
2377
2378     /* we had a session in the request, find it again */
2379     if (!(session = gst_rtsp_session_pool_find (priv->session_pool, sessid)))
2380       goto session_not_found;
2381
2382     /* we add the session to the client list of watched sessions. When a session
2383      * disappears because it times out, we will be notified. If all sessions are
2384      * gone, we will close the connection */
2385     client_watch_session (client, session);
2386   }
2387
2388   /* sanitize the uri */
2389   if (uri)
2390     sanitize_uri (uri);
2391   ctx->uri = uri;
2392   ctx->session = session;
2393
2394   if (!gst_rtsp_auth_check (GST_RTSP_AUTH_CHECK_URL))
2395     goto not_authorized;
2396
2397   /* handle any 'Require' headers */
2398   if (!check_request_requirements (ctx->request, &unsupported_reqs))
2399     goto unsupported_requirement;
2400
2401   /* the backlog must be unlimited while processing requests.
2402    * the causes of this are two cases of deadlocks while streaming over TCP:
2403    *
2404    * 1. consider the scenario where the media pipeline's streaming thread
2405    * is blocking in the appsink (taking the appsink's preroll lock) because
2406    * the backlog is full. when a PAUSE request is received by the RTSP
2407    * client thread then the the state of the session media ought to change
2408    * to PAUSED. while most elements in the pipeline can change state this
2409    * can never happen for the appsink since its preroll lock is taken by
2410    * another thread.
2411    *
2412    * 2. consider the scenario where the media pipeline's streaming thread
2413    * is blocking in the appsink new_sample callback (taking the send lock
2414    * in RTSP client) because the backlog is full. when e.g. a GET request
2415    * is received by the RTSP client thread then a response ought to be sent
2416    * but this can never happen since it requires taking the send lock
2417    * already taken by another thread.
2418    *
2419    * the reason that the backlog is never emptied is that the source used
2420    * for dequeing messages from the backlog is never dispatched because it
2421    * is attached to the same mainloop as the source receving RTSP requests and
2422    * therefore run by the RTSP client thread which is alreayd blocking.
2423    *
2424    * without significant changes the easiest way to cope with this is to
2425    * not block indefinitely when the backlog is full, but rather let the
2426    * backlog grow in size. this in effect means that there can not be any
2427    * upper boundary on its size.
2428    */
2429   if (priv->watch != NULL)
2430     gst_rtsp_watch_set_send_backlog (priv->watch, 0, 0);
2431
2432   /* now see what is asked and dispatch to a dedicated handler */
2433   switch (method) {
2434     case GST_RTSP_OPTIONS:
2435       handle_options_request (client, ctx);
2436       break;
2437     case GST_RTSP_DESCRIBE:
2438       handle_describe_request (client, ctx);
2439       break;
2440     case GST_RTSP_SETUP:
2441       handle_setup_request (client, ctx);
2442       break;
2443     case GST_RTSP_PLAY:
2444       handle_play_request (client, ctx);
2445       break;
2446     case GST_RTSP_PAUSE:
2447       handle_pause_request (client, ctx);
2448       break;
2449     case GST_RTSP_TEARDOWN:
2450       handle_teardown_request (client, ctx);
2451       break;
2452     case GST_RTSP_SET_PARAMETER:
2453       handle_set_param_request (client, ctx);
2454       break;
2455     case GST_RTSP_GET_PARAMETER:
2456       handle_get_param_request (client, ctx);
2457       break;
2458     case GST_RTSP_ANNOUNCE:
2459     case GST_RTSP_RECORD:
2460     case GST_RTSP_REDIRECT:
2461       if (priv->watch != NULL)
2462         gst_rtsp_watch_set_send_backlog (priv->watch, 0, WATCH_BACKLOG_SIZE);
2463       goto not_implemented;
2464     case GST_RTSP_INVALID:
2465     default:
2466       if (priv->watch != NULL)
2467         gst_rtsp_watch_set_send_backlog (priv->watch, 0, WATCH_BACKLOG_SIZE);
2468       goto bad_request;
2469   }
2470
2471   if (priv->watch != NULL)
2472     gst_rtsp_watch_set_send_backlog (priv->watch, 0, WATCH_BACKLOG_SIZE);
2473
2474 done:
2475   if (ctx == &sctx)
2476     gst_rtsp_context_pop_current (ctx);
2477   if (session)
2478     g_object_unref (session);
2479   if (uri)
2480     gst_rtsp_url_free (uri);
2481   return;
2482
2483   /* ERRORS */
2484 not_supported:
2485   {
2486     GST_ERROR ("client %p: version %d not supported", client, version);
2487     send_generic_response (client, GST_RTSP_STS_RTSP_VERSION_NOT_SUPPORTED,
2488         ctx);
2489     goto done;
2490   }
2491 bad_request:
2492   {
2493     GST_ERROR ("client %p: bad request", client);
2494     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
2495     goto done;
2496   }
2497 no_pool:
2498   {
2499     GST_ERROR ("client %p: no pool configured", client);
2500     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
2501     goto done;
2502   }
2503 session_not_found:
2504   {
2505     GST_ERROR ("client %p: session not found", client);
2506     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
2507     goto done;
2508   }
2509 not_authorized:
2510   {
2511     GST_ERROR ("client %p: not allowed", client);
2512     /* error reply is already sent */
2513     goto done;
2514   }
2515 unsupported_requirement:
2516   {
2517     GST_ERROR ("client %p: Required option is not supported (%s)", client,
2518         unsupported_reqs);
2519     send_option_not_supported_response (client, ctx, unsupported_reqs);
2520     g_free (unsupported_reqs);
2521     goto done;
2522   }
2523 not_implemented:
2524   {
2525     GST_ERROR ("client %p: method %d not implemented", client, method);
2526     send_generic_response (client, GST_RTSP_STS_NOT_IMPLEMENTED, ctx);
2527     goto done;
2528   }
2529 }
2530
2531
2532 static void
2533 handle_response (GstRTSPClient * client, GstRTSPMessage * response)
2534 {
2535   GstRTSPClientPrivate *priv = client->priv;
2536   GstRTSPResult res;
2537   GstRTSPSession *session = NULL;
2538   GstRTSPContext sctx = { NULL }, *ctx;
2539   gchar *sessid;
2540
2541   if (!(ctx = gst_rtsp_context_get_current ())) {
2542     ctx = &sctx;
2543     ctx->auth = priv->auth;
2544     gst_rtsp_context_push_current (ctx);
2545   }
2546
2547   ctx->conn = priv->connection;
2548   ctx->client = client;
2549   ctx->request = NULL;
2550   ctx->uri = NULL;
2551   ctx->method = GST_RTSP_INVALID;
2552   ctx->response = response;
2553
2554   if (gst_debug_category_get_threshold (rtsp_client_debug) >= GST_LEVEL_LOG) {
2555     gst_rtsp_message_dump (response);
2556   }
2557
2558   GST_INFO ("client %p: received a response", client);
2559
2560   /* get the session if there is any */
2561   res =
2562       gst_rtsp_message_get_header (response, GST_RTSP_HDR_SESSION, &sessid, 0);
2563   if (res == GST_RTSP_OK) {
2564     if (priv->session_pool == NULL)
2565       goto no_pool;
2566
2567     /* we had a session in the request, find it again */
2568     if (!(session = gst_rtsp_session_pool_find (priv->session_pool, sessid)))
2569       goto session_not_found;
2570
2571     /* we add the session to the client list of watched sessions. When a session
2572      * disappears because it times out, we will be notified. If all sessions are
2573      * gone, we will close the connection */
2574     client_watch_session (client, session);
2575   }
2576
2577   ctx->session = session;
2578
2579   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_HANDLE_RESPONSE],
2580       0, ctx);
2581
2582 done:
2583   if (ctx == &sctx)
2584     gst_rtsp_context_pop_current (ctx);
2585   if (session)
2586     g_object_unref (session);
2587   return;
2588
2589 no_pool:
2590   {
2591     GST_ERROR ("client %p: no pool configured", client);
2592     goto done;
2593   }
2594 session_not_found:
2595   {
2596     GST_ERROR ("client %p: session not found", client);
2597     goto done;
2598   }
2599 }
2600
2601 static void
2602 handle_data (GstRTSPClient * client, GstRTSPMessage * message)
2603 {
2604   GstRTSPClientPrivate *priv = client->priv;
2605   GstRTSPResult res;
2606   guint8 channel;
2607   guint8 *data;
2608   guint size;
2609   GstBuffer *buffer;
2610   GstRTSPStreamTransport *trans;
2611
2612   /* find the stream for this message */
2613   res = gst_rtsp_message_parse_data (message, &channel);
2614   if (res != GST_RTSP_OK)
2615     return;
2616
2617   gst_rtsp_message_get_body (message, &data, &size);
2618   if (size < 2)
2619     goto invalid_length;
2620
2621   gst_rtsp_message_steal_body (message, &data, &size);
2622
2623   /* Strip trailing \0 */
2624   buffer = gst_buffer_new_wrapped (data, size - 1);
2625
2626   trans =
2627       g_hash_table_lookup (priv->transports, GINT_TO_POINTER ((gint) channel));
2628   if (trans) {
2629     /* dispatch to the stream based on the channel number */
2630     gst_rtsp_stream_transport_recv_data (trans, channel, buffer);
2631   } else {
2632     gst_buffer_unref (buffer);
2633   }
2634 invalid_length:
2635   {
2636     GST_DEBUG ("client %p: Short message received, ignoring", client);
2637     return;
2638   }
2639 }
2640
2641 /**
2642  * gst_rtsp_client_set_session_pool:
2643  * @client: a #GstRTSPClient
2644  * @pool: (transfer none): a #GstRTSPSessionPool
2645  *
2646  * Set @pool as the sessionpool for @client which it will use to find
2647  * or allocate sessions. the sessionpool is usually inherited from the server
2648  * that created the client but can be overridden later.
2649  */
2650 void
2651 gst_rtsp_client_set_session_pool (GstRTSPClient * client,
2652     GstRTSPSessionPool * pool)
2653 {
2654   GstRTSPSessionPool *old;
2655   GstRTSPClientPrivate *priv;
2656
2657   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2658
2659   priv = client->priv;
2660
2661   if (pool)
2662     g_object_ref (pool);
2663
2664   g_mutex_lock (&priv->lock);
2665   old = priv->session_pool;
2666   priv->session_pool = pool;
2667
2668   if (priv->session_removed_id) {
2669     g_signal_handler_disconnect (old, priv->session_removed_id);
2670     priv->session_removed_id = 0;
2671   }
2672   g_mutex_unlock (&priv->lock);
2673
2674   /* FIXME, should remove all sessions from the old pool for this client */
2675   if (old)
2676     g_object_unref (old);
2677 }
2678
2679 /**
2680  * gst_rtsp_client_get_session_pool:
2681  * @client: a #GstRTSPClient
2682  *
2683  * Get the #GstRTSPSessionPool object that @client uses to manage its sessions.
2684  *
2685  * Returns: (transfer full): a #GstRTSPSessionPool, unref after usage.
2686  */
2687 GstRTSPSessionPool *
2688 gst_rtsp_client_get_session_pool (GstRTSPClient * client)
2689 {
2690   GstRTSPClientPrivate *priv;
2691   GstRTSPSessionPool *result;
2692
2693   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2694
2695   priv = client->priv;
2696
2697   g_mutex_lock (&priv->lock);
2698   if ((result = priv->session_pool))
2699     g_object_ref (result);
2700   g_mutex_unlock (&priv->lock);
2701
2702   return result;
2703 }
2704
2705 /**
2706  * gst_rtsp_client_set_mount_points:
2707  * @client: a #GstRTSPClient
2708  * @mounts: (transfer none): a #GstRTSPMountPoints
2709  *
2710  * Set @mounts as the mount points for @client which it will use to map urls
2711  * to media streams. These mount points are usually inherited from the server that
2712  * created the client but can be overriden later.
2713  */
2714 void
2715 gst_rtsp_client_set_mount_points (GstRTSPClient * client,
2716     GstRTSPMountPoints * mounts)
2717 {
2718   GstRTSPClientPrivate *priv;
2719   GstRTSPMountPoints *old;
2720
2721   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2722
2723   priv = client->priv;
2724
2725   if (mounts)
2726     g_object_ref (mounts);
2727
2728   g_mutex_lock (&priv->lock);
2729   old = priv->mount_points;
2730   priv->mount_points = mounts;
2731   g_mutex_unlock (&priv->lock);
2732
2733   if (old)
2734     g_object_unref (old);
2735 }
2736
2737 /**
2738  * gst_rtsp_client_get_mount_points:
2739  * @client: a #GstRTSPClient
2740  *
2741  * Get the #GstRTSPMountPoints object that @client uses to manage its sessions.
2742  *
2743  * Returns: (transfer full): a #GstRTSPMountPoints, unref after usage.
2744  */
2745 GstRTSPMountPoints *
2746 gst_rtsp_client_get_mount_points (GstRTSPClient * client)
2747 {
2748   GstRTSPClientPrivate *priv;
2749   GstRTSPMountPoints *result;
2750
2751   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2752
2753   priv = client->priv;
2754
2755   g_mutex_lock (&priv->lock);
2756   if ((result = priv->mount_points))
2757     g_object_ref (result);
2758   g_mutex_unlock (&priv->lock);
2759
2760   return result;
2761 }
2762
2763 /**
2764  * gst_rtsp_client_set_auth:
2765  * @client: a #GstRTSPClient
2766  * @auth: (transfer none): a #GstRTSPAuth
2767  *
2768  * configure @auth to be used as the authentication manager of @client.
2769  */
2770 void
2771 gst_rtsp_client_set_auth (GstRTSPClient * client, GstRTSPAuth * auth)
2772 {
2773   GstRTSPClientPrivate *priv;
2774   GstRTSPAuth *old;
2775
2776   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2777
2778   priv = client->priv;
2779
2780   if (auth)
2781     g_object_ref (auth);
2782
2783   g_mutex_lock (&priv->lock);
2784   old = priv->auth;
2785   priv->auth = auth;
2786   g_mutex_unlock (&priv->lock);
2787
2788   if (old)
2789     g_object_unref (old);
2790 }
2791
2792
2793 /**
2794  * gst_rtsp_client_get_auth:
2795  * @client: a #GstRTSPClient
2796  *
2797  * Get the #GstRTSPAuth used as the authentication manager of @client.
2798  *
2799  * Returns: (transfer full): the #GstRTSPAuth of @client. g_object_unref() after
2800  * usage.
2801  */
2802 GstRTSPAuth *
2803 gst_rtsp_client_get_auth (GstRTSPClient * client)
2804 {
2805   GstRTSPClientPrivate *priv;
2806   GstRTSPAuth *result;
2807
2808   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2809
2810   priv = client->priv;
2811
2812   g_mutex_lock (&priv->lock);
2813   if ((result = priv->auth))
2814     g_object_ref (result);
2815   g_mutex_unlock (&priv->lock);
2816
2817   return result;
2818 }
2819
2820 /**
2821  * gst_rtsp_client_set_thread_pool:
2822  * @client: a #GstRTSPClient
2823  * @pool: (transfer none): a #GstRTSPThreadPool
2824  *
2825  * configure @pool to be used as the thread pool of @client.
2826  */
2827 void
2828 gst_rtsp_client_set_thread_pool (GstRTSPClient * client,
2829     GstRTSPThreadPool * pool)
2830 {
2831   GstRTSPClientPrivate *priv;
2832   GstRTSPThreadPool *old;
2833
2834   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2835
2836   priv = client->priv;
2837
2838   if (pool)
2839     g_object_ref (pool);
2840
2841   g_mutex_lock (&priv->lock);
2842   old = priv->thread_pool;
2843   priv->thread_pool = pool;
2844   g_mutex_unlock (&priv->lock);
2845
2846   if (old)
2847     g_object_unref (old);
2848 }
2849
2850 /**
2851  * gst_rtsp_client_get_thread_pool:
2852  * @client: a #GstRTSPClient
2853  *
2854  * Get the #GstRTSPThreadPool used as the thread pool of @client.
2855  *
2856  * Returns: (transfer full): the #GstRTSPThreadPool of @client. g_object_unref() after
2857  * usage.
2858  */
2859 GstRTSPThreadPool *
2860 gst_rtsp_client_get_thread_pool (GstRTSPClient * client)
2861 {
2862   GstRTSPClientPrivate *priv;
2863   GstRTSPThreadPool *result;
2864
2865   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2866
2867   priv = client->priv;
2868
2869   g_mutex_lock (&priv->lock);
2870   if ((result = priv->thread_pool))
2871     g_object_ref (result);
2872   g_mutex_unlock (&priv->lock);
2873
2874   return result;
2875 }
2876
2877 /**
2878  * gst_rtsp_client_set_connection:
2879  * @client: a #GstRTSPClient
2880  * @conn: (transfer full): a #GstRTSPConnection
2881  *
2882  * Set the #GstRTSPConnection of @client. This function takes ownership of
2883  * @conn.
2884  *
2885  * Returns: %TRUE on success.
2886  */
2887 gboolean
2888 gst_rtsp_client_set_connection (GstRTSPClient * client,
2889     GstRTSPConnection * conn)
2890 {
2891   GstRTSPClientPrivate *priv;
2892   GSocket *read_socket;
2893   GSocketAddress *address;
2894   GstRTSPUrl *url;
2895   GError *error = NULL;
2896
2897   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), FALSE);
2898   g_return_val_if_fail (conn != NULL, FALSE);
2899
2900   priv = client->priv;
2901
2902   read_socket = gst_rtsp_connection_get_read_socket (conn);
2903
2904   if (!(address = g_socket_get_local_address (read_socket, &error)))
2905     goto no_address;
2906
2907   g_free (priv->server_ip);
2908   /* keep the original ip that the client connected to */
2909   if (G_IS_INET_SOCKET_ADDRESS (address)) {
2910     GInetAddress *iaddr;
2911
2912     iaddr = g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (address));
2913
2914     /* socket might be ipv6 but adress still ipv4 */
2915     priv->is_ipv6 = g_inet_address_get_family (iaddr) == G_SOCKET_FAMILY_IPV6;
2916     priv->server_ip = g_inet_address_to_string (iaddr);
2917     g_object_unref (address);
2918   } else {
2919     priv->is_ipv6 = g_socket_get_family (read_socket) == G_SOCKET_FAMILY_IPV6;
2920     priv->server_ip = g_strdup ("unknown");
2921   }
2922
2923   GST_INFO ("client %p connected to server ip %s, ipv6 = %d", client,
2924       priv->server_ip, priv->is_ipv6);
2925
2926   url = gst_rtsp_connection_get_url (conn);
2927   GST_INFO ("added new client %p ip %s:%d", client, url->host, url->port);
2928
2929   priv->connection = conn;
2930
2931   return TRUE;
2932
2933   /* ERRORS */
2934 no_address:
2935   {
2936     GST_ERROR ("could not get local address %s", error->message);
2937     g_error_free (error);
2938     return FALSE;
2939   }
2940 }
2941
2942 /**
2943  * gst_rtsp_client_get_connection:
2944  * @client: a #GstRTSPClient
2945  *
2946  * Get the #GstRTSPConnection of @client.
2947  *
2948  * Returns: (transfer none): the #GstRTSPConnection of @client.
2949  * The connection object returned remains valid until the client is freed.
2950  */
2951 GstRTSPConnection *
2952 gst_rtsp_client_get_connection (GstRTSPClient * client)
2953 {
2954   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2955
2956   return client->priv->connection;
2957 }
2958
2959 /**
2960  * gst_rtsp_client_set_send_func:
2961  * @client: a #GstRTSPClient
2962  * @func: (scope notified): a #GstRTSPClientSendFunc
2963  * @user_data: (closure): user data passed to @func
2964  * @notify: (allow-none): called when @user_data is no longer in use
2965  *
2966  * Set @func as the callback that will be called when a new message needs to be
2967  * sent to the client. @user_data is passed to @func and @notify is called when
2968  * @user_data is no longer in use.
2969  *
2970  * By default, the client will send the messages on the #GstRTSPConnection that
2971  * was configured with gst_rtsp_client_attach() was called.
2972  */
2973 void
2974 gst_rtsp_client_set_send_func (GstRTSPClient * client,
2975     GstRTSPClientSendFunc func, gpointer user_data, GDestroyNotify notify)
2976 {
2977   GstRTSPClientPrivate *priv;
2978   GDestroyNotify old_notify;
2979   gpointer old_data;
2980
2981   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2982
2983   priv = client->priv;
2984
2985   g_mutex_lock (&priv->send_lock);
2986   priv->send_func = func;
2987   old_notify = priv->send_notify;
2988   old_data = priv->send_data;
2989   priv->send_notify = notify;
2990   priv->send_data = user_data;
2991   g_mutex_unlock (&priv->send_lock);
2992
2993   if (old_notify)
2994     old_notify (old_data);
2995 }
2996
2997 /**
2998  * gst_rtsp_client_handle_message:
2999  * @client: a #GstRTSPClient
3000  * @message: (transfer none): an #GstRTSPMessage
3001  *
3002  * Let the client handle @message.
3003  *
3004  * Returns: a #GstRTSPResult.
3005  */
3006 GstRTSPResult
3007 gst_rtsp_client_handle_message (GstRTSPClient * client,
3008     GstRTSPMessage * message)
3009 {
3010   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), GST_RTSP_EINVAL);
3011   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
3012
3013   switch (message->type) {
3014     case GST_RTSP_MESSAGE_REQUEST:
3015       handle_request (client, message);
3016       break;
3017     case GST_RTSP_MESSAGE_RESPONSE:
3018       handle_response (client, message);
3019       break;
3020     case GST_RTSP_MESSAGE_DATA:
3021       handle_data (client, message);
3022       break;
3023     default:
3024       break;
3025   }
3026   return GST_RTSP_OK;
3027 }
3028
3029 /**
3030  * gst_rtsp_client_send_message:
3031  * @client: a #GstRTSPClient
3032  * @session: (allow-none) (transfer none): a #GstRTSPSession to send
3033  *   the message to or %NULL
3034  * @message: (transfer none): The #GstRTSPMessage to send
3035  *
3036  * Send a message message to the remote end. @message must be a
3037  * #GST_RTSP_MESSAGE_REQUEST or a #GST_RTSP_MESSAGE_RESPONSE.
3038  */
3039 GstRTSPResult
3040 gst_rtsp_client_send_message (GstRTSPClient * client, GstRTSPSession * session,
3041     GstRTSPMessage * message)
3042 {
3043   GstRTSPContext sctx = { NULL }
3044   , *ctx;
3045   GstRTSPClientPrivate *priv;
3046
3047   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), GST_RTSP_EINVAL);
3048   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
3049   g_return_val_if_fail (message->type == GST_RTSP_MESSAGE_REQUEST ||
3050       message->type == GST_RTSP_MESSAGE_RESPONSE, GST_RTSP_EINVAL);
3051
3052   priv = client->priv;
3053
3054   if (!(ctx = gst_rtsp_context_get_current ())) {
3055     ctx = &sctx;
3056     ctx->auth = priv->auth;
3057     gst_rtsp_context_push_current (ctx);
3058   }
3059
3060   ctx->conn = priv->connection;
3061   ctx->client = client;
3062   ctx->session = session;
3063
3064   send_message (client, ctx, message, FALSE);
3065
3066   if (ctx == &sctx)
3067     gst_rtsp_context_pop_current (ctx);
3068
3069   return GST_RTSP_OK;
3070 }
3071
3072 static GstRTSPResult
3073 do_send_message (GstRTSPClient * client, GstRTSPMessage * message,
3074     gboolean close, gpointer user_data)
3075 {
3076   GstRTSPClientPrivate *priv = client->priv;
3077   GstRTSPResult ret;
3078   GTimeVal time;
3079
3080   time.tv_sec = 1;
3081   time.tv_usec = 0;
3082
3083   do {
3084     /* send the response and store the seq number so we can wait until it's
3085      * written to the client to close the connection */
3086     ret =
3087         gst_rtsp_watch_send_message (priv->watch, message,
3088         close ? &priv->close_seq : NULL);
3089     if (ret == GST_RTSP_OK)
3090       break;
3091
3092     if (ret != GST_RTSP_ENOMEM)
3093       goto error;
3094
3095     /* drop backlog */
3096     if (priv->drop_backlog)
3097       break;
3098
3099     /* queue was full, wait for more space */
3100     GST_DEBUG_OBJECT (client, "waiting for backlog");
3101     ret = gst_rtsp_watch_wait_backlog (priv->watch, &time);
3102     GST_DEBUG_OBJECT (client, "Resend due to backlog full");
3103   } while (ret != GST_RTSP_EINTR);
3104
3105   return ret;
3106
3107   /* ERRORS */
3108 error:
3109   {
3110     GST_DEBUG_OBJECT (client, "got error %d", ret);
3111     return ret;
3112   }
3113 }
3114
3115 static GstRTSPResult
3116 message_received (GstRTSPWatch * watch, GstRTSPMessage * message,
3117     gpointer user_data)
3118 {
3119   return gst_rtsp_client_handle_message (GST_RTSP_CLIENT (user_data), message);
3120 }
3121
3122 static GstRTSPResult
3123 message_sent (GstRTSPWatch * watch, guint cseq, gpointer user_data)
3124 {
3125   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3126   GstRTSPClientPrivate *priv = client->priv;
3127
3128   if (priv->close_seq && priv->close_seq == cseq) {
3129     GST_INFO ("client %p: send close message", client);
3130     priv->close_seq = 0;
3131     gst_rtsp_client_close (client);
3132   }
3133
3134   return GST_RTSP_OK;
3135 }
3136
3137 static GstRTSPResult
3138 closed (GstRTSPWatch * watch, gpointer user_data)
3139 {
3140   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3141   GstRTSPClientPrivate *priv = client->priv;
3142   const gchar *tunnelid;
3143
3144   GST_INFO ("client %p: connection closed", client);
3145
3146   if ((tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection))) {
3147     g_mutex_lock (&tunnels_lock);
3148     /* remove from tunnelids */
3149     g_hash_table_remove (tunnels, tunnelid);
3150     g_mutex_unlock (&tunnels_lock);
3151   }
3152
3153   gst_rtsp_watch_set_flushing (watch, TRUE);
3154   g_mutex_lock (&priv->watch_lock);
3155   gst_rtsp_client_set_send_func (client, NULL, NULL, NULL);
3156   g_mutex_unlock (&priv->watch_lock);
3157
3158   return GST_RTSP_OK;
3159 }
3160
3161 static GstRTSPResult
3162 error (GstRTSPWatch * watch, GstRTSPResult result, gpointer user_data)
3163 {
3164   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3165   gchar *str;
3166
3167   str = gst_rtsp_strresult (result);
3168   GST_INFO ("client %p: received an error %s", client, str);
3169   g_free (str);
3170
3171   return GST_RTSP_OK;
3172 }
3173
3174 static GstRTSPResult
3175 error_full (GstRTSPWatch * watch, GstRTSPResult result,
3176     GstRTSPMessage * message, guint id, gpointer user_data)
3177 {
3178   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3179   gchar *str;
3180
3181   str = gst_rtsp_strresult (result);
3182   GST_INFO
3183       ("client %p: error when handling message %p with id %d: %s",
3184       client, message, id, str);
3185   g_free (str);
3186
3187   return GST_RTSP_OK;
3188 }
3189
3190 static gboolean
3191 remember_tunnel (GstRTSPClient * client)
3192 {
3193   GstRTSPClientPrivate *priv = client->priv;
3194   const gchar *tunnelid;
3195
3196   /* store client in the pending tunnels */
3197   tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection);
3198   if (tunnelid == NULL)
3199     goto no_tunnelid;
3200
3201   GST_INFO ("client %p: inserting tunnel session %s", client, tunnelid);
3202
3203   /* we can't have two clients connecting with the same tunnelid */
3204   g_mutex_lock (&tunnels_lock);
3205   if (g_hash_table_lookup (tunnels, tunnelid))
3206     goto tunnel_existed;
3207
3208   g_hash_table_insert (tunnels, g_strdup (tunnelid), g_object_ref (client));
3209   g_mutex_unlock (&tunnels_lock);
3210
3211   return TRUE;
3212
3213   /* ERRORS */
3214 no_tunnelid:
3215   {
3216     GST_ERROR ("client %p: no tunnelid provided", client);
3217     return FALSE;
3218   }
3219 tunnel_existed:
3220   {
3221     g_mutex_unlock (&tunnels_lock);
3222     GST_ERROR ("client %p: tunnel session %s already existed", client,
3223         tunnelid);
3224     return FALSE;
3225   }
3226 }
3227
3228 static GstRTSPResult
3229 tunnel_lost (GstRTSPWatch * watch, gpointer user_data)
3230 {
3231   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3232   GstRTSPClientPrivate *priv = client->priv;
3233
3234   GST_WARNING ("client %p: tunnel lost (connection %p)", client,
3235       priv->connection);
3236
3237   /* ignore error, it'll only be a problem when the client does a POST again */
3238   remember_tunnel (client);
3239
3240   return GST_RTSP_OK;
3241 }
3242
3243 static gboolean
3244 handle_tunnel (GstRTSPClient * client)
3245 {
3246   GstRTSPClientPrivate *priv = client->priv;
3247   GstRTSPClient *oclient;
3248   GstRTSPClientPrivate *opriv;
3249   const gchar *tunnelid;
3250
3251   tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection);
3252   if (tunnelid == NULL)
3253     goto no_tunnelid;
3254
3255   /* check for previous tunnel */
3256   g_mutex_lock (&tunnels_lock);
3257   oclient = g_hash_table_lookup (tunnels, tunnelid);
3258
3259   if (oclient == NULL) {
3260     /* no previous tunnel, remember tunnel */
3261     g_hash_table_insert (tunnels, g_strdup (tunnelid), g_object_ref (client));
3262     g_mutex_unlock (&tunnels_lock);
3263
3264     GST_INFO ("client %p: no previous tunnel found, remembering tunnel (%p)",
3265         client, priv->connection);
3266   } else {
3267     /* merge both tunnels into the first client */
3268     /* remove the old client from the table. ref before because removing it will
3269      * remove the ref to it. */
3270     g_object_ref (oclient);
3271     g_hash_table_remove (tunnels, tunnelid);
3272     g_mutex_unlock (&tunnels_lock);
3273
3274     opriv = oclient->priv;
3275
3276     g_mutex_lock (&opriv->watch_lock);
3277     if (opriv->watch == NULL)
3278       goto tunnel_closed;
3279
3280     GST_INFO ("client %p: found previous tunnel %p (old %p, new %p)", client,
3281         oclient, opriv->connection, priv->connection);
3282
3283     gst_rtsp_connection_do_tunnel (opriv->connection, priv->connection);
3284     gst_rtsp_watch_reset (priv->watch);
3285     gst_rtsp_watch_reset (opriv->watch);
3286     g_mutex_unlock (&opriv->watch_lock);
3287     g_object_unref (oclient);
3288
3289     /* the old client owns the tunnel now, the new one will be freed */
3290     g_source_destroy ((GSource *) priv->watch);
3291     priv->watch = NULL;
3292     gst_rtsp_client_set_send_func (client, NULL, NULL, NULL);
3293   }
3294
3295   return TRUE;
3296
3297   /* ERRORS */
3298 no_tunnelid:
3299   {
3300     GST_ERROR ("client %p: no tunnelid provided", client);
3301     return FALSE;
3302   }
3303 tunnel_closed:
3304   {
3305     GST_ERROR ("client %p: tunnel session %s was closed", client, tunnelid);
3306     g_mutex_unlock (&opriv->watch_lock);
3307     g_object_unref (oclient);
3308     return FALSE;
3309   }
3310 }
3311
3312 static GstRTSPStatusCode
3313 tunnel_get (GstRTSPWatch * watch, gpointer user_data)
3314 {
3315   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3316
3317   GST_INFO ("client %p: tunnel get (connection %p)", client,
3318       client->priv->connection);
3319
3320   if (!handle_tunnel (client)) {
3321     return GST_RTSP_STS_SERVICE_UNAVAILABLE;
3322   }
3323
3324   return GST_RTSP_STS_OK;
3325 }
3326
3327 static GstRTSPResult
3328 tunnel_post (GstRTSPWatch * watch, gpointer user_data)
3329 {
3330   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3331
3332   GST_INFO ("client %p: tunnel post (connection %p)", client,
3333       client->priv->connection);
3334
3335   if (!handle_tunnel (client)) {
3336     return GST_RTSP_ERROR;
3337   }
3338
3339   return GST_RTSP_OK;
3340 }
3341
3342 static GstRTSPResult
3343 tunnel_http_response (GstRTSPWatch * watch, GstRTSPMessage * request,
3344     GstRTSPMessage * response, gpointer user_data)
3345 {
3346   GstRTSPClientClass *klass;
3347
3348   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3349   klass = GST_RTSP_CLIENT_GET_CLASS (client);
3350
3351   if (klass->tunnel_http_response) {
3352     klass->tunnel_http_response (client, request, response);
3353   }
3354
3355   return GST_RTSP_OK;
3356 }
3357
3358 static GstRTSPWatchFuncs watch_funcs = {
3359   message_received,
3360   message_sent,
3361   closed,
3362   error,
3363   tunnel_get,
3364   tunnel_post,
3365   error_full,
3366   tunnel_lost,
3367   tunnel_http_response
3368 };
3369
3370 static void
3371 client_watch_notify (GstRTSPClient * client)
3372 {
3373   GstRTSPClientPrivate *priv = client->priv;
3374
3375   GST_INFO ("client %p: watch destroyed", client);
3376   priv->watch = NULL;
3377   /* remove all sessions and so drop the extra client ref */
3378   gst_rtsp_client_session_filter (client, cleanup_session, NULL);
3379   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_CLOSED], 0, NULL);
3380   g_object_unref (client);
3381 }
3382
3383 /**
3384  * gst_rtsp_client_attach:
3385  * @client: a #GstRTSPClient
3386  * @context: (allow-none): a #GMainContext
3387  *
3388  * Attaches @client to @context. When the mainloop for @context is run, the
3389  * client will be dispatched. When @context is %NULL, the default context will be
3390  * used).
3391  *
3392  * This function should be called when the client properties and urls are fully
3393  * configured and the client is ready to start.
3394  *
3395  * Returns: the ID (greater than 0) for the source within the GMainContext.
3396  */
3397 guint
3398 gst_rtsp_client_attach (GstRTSPClient * client, GMainContext * context)
3399 {
3400   GstRTSPClientPrivate *priv;
3401   guint res;
3402
3403   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), 0);
3404   priv = client->priv;
3405   g_return_val_if_fail (priv->connection != NULL, 0);
3406   g_return_val_if_fail (priv->watch == NULL, 0);
3407
3408   /* make sure noone will free the context before the watch is destroyed */
3409   priv->watch_context = g_main_context_ref (context);
3410
3411   /* create watch for the connection and attach */
3412   priv->watch = gst_rtsp_watch_new (priv->connection, &watch_funcs,
3413       g_object_ref (client), (GDestroyNotify) client_watch_notify);
3414   gst_rtsp_client_set_send_func (client, do_send_message, priv->watch,
3415       (GDestroyNotify) gst_rtsp_watch_unref);
3416
3417   gst_rtsp_watch_set_send_backlog (priv->watch, 0, WATCH_BACKLOG_SIZE);
3418
3419   GST_INFO ("client %p: attaching to context %p", client, context);
3420   res = gst_rtsp_watch_attach (priv->watch, context);
3421
3422   return res;
3423 }
3424
3425 /**
3426  * gst_rtsp_client_session_filter:
3427  * @client: a #GstRTSPClient
3428  * @func: (scope call) (allow-none): a callback
3429  * @user_data: user data passed to @func
3430  *
3431  * Call @func for each session managed by @client. The result value of @func
3432  * determines what happens to the session. @func will be called with @client
3433  * locked so no further actions on @client can be performed from @func.
3434  *
3435  * If @func returns #GST_RTSP_FILTER_REMOVE, the session will be removed from
3436  * @client.
3437  *
3438  * If @func returns #GST_RTSP_FILTER_KEEP, the session will remain in @client.
3439  *
3440  * If @func returns #GST_RTSP_FILTER_REF, the session will remain in @client but
3441  * will also be added with an additional ref to the result #GList of this
3442  * function..
3443  *
3444  * When @func is %NULL, #GST_RTSP_FILTER_REF will be assumed for each session.
3445  *
3446  * Returns: (element-type GstRTSPSession) (transfer full): a #GList with all
3447  * sessions for which @func returned #GST_RTSP_FILTER_REF. After usage, each
3448  * element in the #GList should be unreffed before the list is freed.
3449  */
3450 GList *
3451 gst_rtsp_client_session_filter (GstRTSPClient * client,
3452     GstRTSPClientSessionFilterFunc func, gpointer user_data)
3453 {
3454   GstRTSPClientPrivate *priv;
3455   GList *result, *walk, *next;
3456   GHashTable *visited;
3457   guint cookie;
3458
3459   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
3460
3461   priv = client->priv;
3462
3463   result = NULL;
3464   if (func)
3465     visited = g_hash_table_new_full (NULL, NULL, g_object_unref, NULL);
3466
3467   g_mutex_lock (&priv->lock);
3468 restart:
3469   cookie = priv->sessions_cookie;
3470   for (walk = priv->sessions; walk; walk = next) {
3471     GstRTSPSession *sess = walk->data;
3472     GstRTSPFilterResult res;
3473     gboolean changed;
3474
3475     next = g_list_next (walk);
3476
3477     if (func) {
3478       /* only visit each session once */
3479       if (g_hash_table_contains (visited, sess))
3480         continue;
3481
3482       g_hash_table_add (visited, g_object_ref (sess));
3483       g_mutex_unlock (&priv->lock);
3484
3485       res = func (client, sess, user_data);
3486
3487       g_mutex_lock (&priv->lock);
3488     } else
3489       res = GST_RTSP_FILTER_REF;
3490
3491     changed = (cookie != priv->sessions_cookie);
3492
3493     switch (res) {
3494       case GST_RTSP_FILTER_REMOVE:
3495         /* stop watching the session and pretend it went away, if the list was
3496          * changed, we can't use the current list position, try to see if we
3497          * still have the session */
3498         client_unwatch_session (client, sess, changed ? NULL : walk);
3499         cookie = priv->sessions_cookie;
3500         break;
3501       case GST_RTSP_FILTER_REF:
3502         result = g_list_prepend (result, g_object_ref (sess));
3503         break;
3504       case GST_RTSP_FILTER_KEEP:
3505       default:
3506         break;
3507     }
3508     if (changed)
3509       goto restart;
3510   }
3511   g_mutex_unlock (&priv->lock);
3512
3513   if (func)
3514     g_hash_table_unref (visited);
3515
3516   return result;
3517 }