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