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