rtsp-client: Allow backlog to grow while expiring session
[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   GstRTSPClientPrivate *priv = client->priv;
965   GstRTSPSession *session;
966   GstRTSPClientClass *klass;
967   GstRTSPSessionMedia *sessmedia;
968   GstRTSPStatusCode code;
969   GstRTSPState rtspstate;
970   gchar *path;
971   gint matched;
972
973   if (!(session = ctx->session))
974     goto no_session;
975
976   if (!ctx->uri)
977     goto no_uri;
978
979   klass = GST_RTSP_CLIENT_GET_CLASS (client);
980   path = klass->make_path_from_uri (client, ctx->uri);
981
982   /* get a handle to the configuration of the media in the session */
983   sessmedia = gst_rtsp_session_get_media (session, path, &matched);
984   if (!sessmedia)
985     goto not_found;
986
987   if (path[matched] != '\0')
988     goto no_aggregate;
989
990   g_free (path);
991
992   ctx->sessmedia = sessmedia;
993
994   rtspstate = gst_rtsp_session_media_get_rtsp_state (sessmedia);
995   /* the session state must be playing or recording */
996   if (rtspstate != GST_RTSP_STATE_PLAYING &&
997       rtspstate != GST_RTSP_STATE_RECORDING)
998     goto invalid_state;
999
1000   /* No limit on watch queue because else we might be blocking in the appsink
1001    * render method and the PAUSE below will hang */
1002   if (priv->watch != NULL)
1003     gst_rtsp_watch_set_send_backlog (priv->watch, 0, 0);
1004
1005   /* then pause sending */
1006   gst_rtsp_session_media_set_state (sessmedia, GST_STATE_PAUSED);
1007
1008   /* construct the response now */
1009   code = GST_RTSP_STS_OK;
1010   gst_rtsp_message_init_response (ctx->response, code,
1011       gst_rtsp_status_as_text (code), ctx->request);
1012
1013   send_message (client, ctx, ctx->response, FALSE);
1014
1015   if (priv->watch != NULL)
1016     gst_rtsp_watch_set_send_backlog (priv->watch, 0, WATCH_BACKLOG_SIZE);
1017
1018   /* the state is now READY */
1019   gst_rtsp_session_media_set_rtsp_state (sessmedia, GST_RTSP_STATE_READY);
1020
1021   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_PAUSE_REQUEST], 0, ctx);
1022
1023   return TRUE;
1024
1025   /* ERRORS */
1026 no_session:
1027   {
1028     GST_ERROR ("client %p: no seesion", client);
1029     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
1030     return FALSE;
1031   }
1032 no_uri:
1033   {
1034     GST_ERROR ("client %p: no uri supplied", client);
1035     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
1036     return FALSE;
1037   }
1038 not_found:
1039   {
1040     GST_ERROR ("client %p: no media for uri", client);
1041     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
1042     g_free (path);
1043     return FALSE;
1044   }
1045 no_aggregate:
1046   {
1047     GST_ERROR ("client %p: no aggregate path %s", client, path);
1048     send_generic_response (client,
1049         GST_RTSP_STS_ONLY_AGGREGATE_OPERATION_ALLOWED, ctx);
1050     g_free (path);
1051     return FALSE;
1052   }
1053 invalid_state:
1054   {
1055     GST_ERROR ("client %p: not PLAYING or RECORDING", client);
1056     send_generic_response (client, GST_RTSP_STS_METHOD_NOT_VALID_IN_THIS_STATE,
1057         ctx);
1058     return FALSE;
1059   }
1060 }
1061
1062 /* convert @url and @path to a URL used as a content base for the factory
1063  * located at @path */
1064 static gchar *
1065 make_base_url (GstRTSPClient * client, GstRTSPUrl * url, const gchar * path)
1066 {
1067   GstRTSPUrl tmp;
1068   gchar *result;
1069   const gchar *trail;
1070
1071   /* check for trailing '/' and append one */
1072   trail = (path[strlen (path) - 1] != '/' ? "/" : "");
1073
1074   tmp = *url;
1075   tmp.user = NULL;
1076   tmp.passwd = NULL;
1077   tmp.abspath = g_strdup_printf ("%s%s", path, trail);
1078   tmp.query = NULL;
1079   result = gst_rtsp_url_get_request_uri (&tmp);
1080   g_free (tmp.abspath);
1081
1082   return result;
1083 }
1084
1085 static gboolean
1086 handle_play_request (GstRTSPClient * client, GstRTSPContext * ctx)
1087 {
1088   GstRTSPSession *session;
1089   GstRTSPClientClass *klass;
1090   GstRTSPSessionMedia *sessmedia;
1091   GstRTSPMedia *media;
1092   GstRTSPStatusCode code;
1093   GstRTSPUrl *uri;
1094   gchar *str;
1095   GstRTSPTimeRange *range;
1096   GstRTSPResult res;
1097   GstRTSPState rtspstate;
1098   GstRTSPRangeUnit unit = GST_RTSP_RANGE_NPT;
1099   gchar *path, *rtpinfo;
1100   gint matched;
1101
1102   if (!(session = ctx->session))
1103     goto no_session;
1104
1105   if (!(uri = ctx->uri))
1106     goto no_uri;
1107
1108   klass = GST_RTSP_CLIENT_GET_CLASS (client);
1109   path = klass->make_path_from_uri (client, uri);
1110
1111   /* get a handle to the configuration of the media in the session */
1112   sessmedia = gst_rtsp_session_get_media (session, path, &matched);
1113   if (!sessmedia)
1114     goto not_found;
1115
1116   if (path[matched] != '\0')
1117     goto no_aggregate;
1118
1119   g_free (path);
1120
1121   ctx->sessmedia = sessmedia;
1122   ctx->media = media = gst_rtsp_session_media_get_media (sessmedia);
1123
1124   /* the session state must be playing or ready */
1125   rtspstate = gst_rtsp_session_media_get_rtsp_state (sessmedia);
1126   if (rtspstate != GST_RTSP_STATE_PLAYING && rtspstate != GST_RTSP_STATE_READY)
1127     goto invalid_state;
1128
1129   /* in play we first unsuspend, media could be suspended from SDP or PAUSED */
1130   if (!gst_rtsp_media_unsuspend (media))
1131     goto unsuspend_failed;
1132
1133   /* parse the range header if we have one */
1134   res = gst_rtsp_message_get_header (ctx->request, GST_RTSP_HDR_RANGE, &str, 0);
1135   if (res == GST_RTSP_OK) {
1136     if (gst_rtsp_range_parse (str, &range) == GST_RTSP_OK) {
1137       /* we have a range, seek to the position */
1138       unit = range->unit;
1139       gst_rtsp_media_seek (media, range);
1140       gst_rtsp_range_free (range);
1141     }
1142   }
1143
1144   /* grab RTPInfo from the media now */
1145   rtpinfo = gst_rtsp_session_media_get_rtpinfo (sessmedia);
1146
1147   /* construct the response now */
1148   code = GST_RTSP_STS_OK;
1149   gst_rtsp_message_init_response (ctx->response, code,
1150       gst_rtsp_status_as_text (code), ctx->request);
1151
1152   /* add the RTP-Info header */
1153   if (rtpinfo)
1154     gst_rtsp_message_take_header (ctx->response, GST_RTSP_HDR_RTP_INFO,
1155         rtpinfo);
1156
1157   /* add the range */
1158   str = gst_rtsp_media_get_range_string (media, TRUE, unit);
1159   if (str)
1160     gst_rtsp_message_take_header (ctx->response, GST_RTSP_HDR_RANGE, str);
1161
1162   send_message (client, ctx, ctx->response, FALSE);
1163
1164   /* start playing after sending the response */
1165   gst_rtsp_session_media_set_state (sessmedia, GST_STATE_PLAYING);
1166
1167   gst_rtsp_session_media_set_rtsp_state (sessmedia, GST_RTSP_STATE_PLAYING);
1168
1169   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_PLAY_REQUEST], 0, ctx);
1170
1171   return TRUE;
1172
1173   /* ERRORS */
1174 no_session:
1175   {
1176     GST_ERROR ("client %p: no session", client);
1177     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
1178     return FALSE;
1179   }
1180 no_uri:
1181   {
1182     GST_ERROR ("client %p: no uri supplied", client);
1183     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
1184     return FALSE;
1185   }
1186 not_found:
1187   {
1188     GST_ERROR ("client %p: media not found", client);
1189     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
1190     return FALSE;
1191   }
1192 no_aggregate:
1193   {
1194     GST_ERROR ("client %p: no aggregate path %s", client, path);
1195     send_generic_response (client,
1196         GST_RTSP_STS_ONLY_AGGREGATE_OPERATION_ALLOWED, ctx);
1197     g_free (path);
1198     return FALSE;
1199   }
1200 invalid_state:
1201   {
1202     GST_ERROR ("client %p: not PLAYING or READY", client);
1203     send_generic_response (client, GST_RTSP_STS_METHOD_NOT_VALID_IN_THIS_STATE,
1204         ctx);
1205     return FALSE;
1206   }
1207 unsuspend_failed:
1208   {
1209     GST_ERROR ("client %p: unsuspend failed", client);
1210     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, ctx);
1211     return FALSE;
1212   }
1213 }
1214
1215 static void
1216 do_keepalive (GstRTSPSession * session)
1217 {
1218   GST_INFO ("keep session %p alive", session);
1219   gst_rtsp_session_touch (session);
1220 }
1221
1222 /* parse @transport and return a valid transport in @tr. only transports
1223  * supported by @stream are returned. Returns FALSE if no valid transport
1224  * was found. */
1225 static gboolean
1226 parse_transport (const char *transport, GstRTSPStream * stream,
1227     GstRTSPTransport * tr)
1228 {
1229   gint i;
1230   gboolean res;
1231   gchar **transports;
1232
1233   res = FALSE;
1234   gst_rtsp_transport_init (tr);
1235
1236   GST_DEBUG ("parsing transports %s", transport);
1237
1238   transports = g_strsplit (transport, ",", 0);
1239
1240   /* loop through the transports, try to parse */
1241   for (i = 0; transports[i]; i++) {
1242     res = gst_rtsp_transport_parse (transports[i], tr);
1243     if (res != GST_RTSP_OK) {
1244       /* no valid transport, search some more */
1245       GST_WARNING ("could not parse transport %s", transports[i]);
1246       goto next;
1247     }
1248
1249     /* we have a transport, see if it's supported */
1250     if (!gst_rtsp_stream_is_transport_supported (stream, tr)) {
1251       GST_WARNING ("unsupported transport %s", transports[i]);
1252       goto next;
1253     }
1254
1255     /* we have a valid transport */
1256     GST_INFO ("found valid transport %s", transports[i]);
1257     res = TRUE;
1258     break;
1259
1260   next:
1261     gst_rtsp_transport_init (tr);
1262   }
1263   g_strfreev (transports);
1264
1265   return res;
1266 }
1267
1268 static gboolean
1269 default_configure_client_media (GstRTSPClient * client, GstRTSPMedia * media,
1270     GstRTSPStream * stream, GstRTSPContext * ctx)
1271 {
1272   GstRTSPMessage *request = ctx->request;
1273   gchar *blocksize_str;
1274
1275   if (gst_rtsp_message_get_header (request, GST_RTSP_HDR_BLOCKSIZE,
1276           &blocksize_str, 0) == GST_RTSP_OK) {
1277     guint64 blocksize;
1278     gchar *end;
1279
1280     blocksize = g_ascii_strtoull (blocksize_str, &end, 10);
1281     if (end == blocksize_str)
1282       goto parse_failed;
1283
1284     /* we don't want to change the mtu when this media
1285      * can be shared because it impacts other clients */
1286     if (gst_rtsp_media_is_shared (media))
1287       goto done;
1288
1289     if (blocksize > G_MAXUINT)
1290       blocksize = G_MAXUINT;
1291
1292     gst_rtsp_stream_set_mtu (stream, blocksize);
1293   }
1294 done:
1295   return TRUE;
1296
1297   /* ERRORS */
1298 parse_failed:
1299   {
1300     GST_ERROR_OBJECT (client, "failed to parse blocksize");
1301     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
1302     return FALSE;
1303   }
1304 }
1305
1306 static gboolean
1307 default_configure_client_transport (GstRTSPClient * client,
1308     GstRTSPContext * ctx, GstRTSPTransport * ct)
1309 {
1310   GstRTSPClientPrivate *priv = client->priv;
1311
1312   /* we have a valid transport now, set the destination of the client. */
1313   if (ct->lower_transport == GST_RTSP_LOWER_TRANS_UDP_MCAST) {
1314     gboolean use_client_settings;
1315
1316     use_client_settings =
1317         gst_rtsp_auth_check (GST_RTSP_AUTH_CHECK_TRANSPORT_CLIENT_SETTINGS);
1318
1319     if (ct->destination && use_client_settings) {
1320       GstRTSPAddress *addr;
1321
1322       addr = gst_rtsp_stream_reserve_address (ctx->stream, ct->destination,
1323           ct->port.min, ct->port.max - ct->port.min + 1, ct->ttl);
1324
1325       if (addr == NULL)
1326         goto no_address;
1327
1328       gst_rtsp_address_free (addr);
1329     } else {
1330       GstRTSPAddress *addr;
1331       GSocketFamily family;
1332
1333       family = priv->is_ipv6 ? G_SOCKET_FAMILY_IPV6 : G_SOCKET_FAMILY_IPV4;
1334
1335       addr = gst_rtsp_stream_get_multicast_address (ctx->stream, family);
1336       if (addr == NULL)
1337         goto no_address;
1338
1339       g_free (ct->destination);
1340       ct->destination = g_strdup (addr->address);
1341       ct->port.min = addr->port;
1342       ct->port.max = addr->port + addr->n_ports - 1;
1343       ct->ttl = addr->ttl;
1344
1345       gst_rtsp_address_free (addr);
1346     }
1347   } else {
1348     GstRTSPUrl *url;
1349
1350     url = gst_rtsp_connection_get_url (priv->connection);
1351     g_free (ct->destination);
1352     ct->destination = g_strdup (url->host);
1353
1354     if (ct->lower_transport & GST_RTSP_LOWER_TRANS_TCP) {
1355       GSocket *sock;
1356       GSocketAddress *addr;
1357
1358       sock = gst_rtsp_connection_get_read_socket (priv->connection);
1359       if ((addr = g_socket_get_remote_address (sock, NULL))) {
1360         /* our read port is the sender port of client */
1361         ct->client_port.min =
1362             g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (addr));
1363         g_object_unref (addr);
1364       }
1365       if ((addr = g_socket_get_local_address (sock, NULL))) {
1366         ct->server_port.max =
1367             g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (addr));
1368         g_object_unref (addr);
1369       }
1370       sock = gst_rtsp_connection_get_write_socket (priv->connection);
1371       if ((addr = g_socket_get_remote_address (sock, NULL))) {
1372         /* our write port is the receiver port of client */
1373         ct->client_port.max =
1374             g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (addr));
1375         g_object_unref (addr);
1376       }
1377       if ((addr = g_socket_get_local_address (sock, NULL))) {
1378         ct->server_port.min =
1379             g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (addr));
1380         g_object_unref (addr);
1381       }
1382       /* check if the client selected channels for TCP */
1383       if (ct->interleaved.min == -1 || ct->interleaved.max == -1) {
1384         gst_rtsp_session_media_alloc_channels (ctx->sessmedia,
1385             &ct->interleaved);
1386       }
1387     }
1388   }
1389   return TRUE;
1390
1391   /* ERRORS */
1392 no_address:
1393   {
1394     GST_ERROR_OBJECT (client, "failed to acquire address for stream");
1395     return FALSE;
1396   }
1397 }
1398
1399 static GstRTSPTransport *
1400 make_server_transport (GstRTSPClient * client, GstRTSPContext * ctx,
1401     GstRTSPTransport * ct)
1402 {
1403   GstRTSPTransport *st;
1404   GInetAddress *addr;
1405   GSocketFamily family;
1406
1407   /* prepare the server transport */
1408   gst_rtsp_transport_new (&st);
1409
1410   st->trans = ct->trans;
1411   st->profile = ct->profile;
1412   st->lower_transport = ct->lower_transport;
1413
1414   addr = g_inet_address_new_from_string (ct->destination);
1415
1416   if (!addr) {
1417     GST_ERROR ("failed to get inet addr from client destination");
1418     family = G_SOCKET_FAMILY_IPV4;
1419   } else {
1420     family = g_inet_address_get_family (addr);
1421     g_object_unref (addr);
1422     addr = NULL;
1423   }
1424
1425   switch (st->lower_transport) {
1426     case GST_RTSP_LOWER_TRANS_UDP:
1427       st->client_port = ct->client_port;
1428       gst_rtsp_stream_get_server_port (ctx->stream, &st->server_port, family);
1429       break;
1430     case GST_RTSP_LOWER_TRANS_UDP_MCAST:
1431       st->port = ct->port;
1432       st->destination = g_strdup (ct->destination);
1433       st->ttl = ct->ttl;
1434       break;
1435     case GST_RTSP_LOWER_TRANS_TCP:
1436       st->interleaved = ct->interleaved;
1437       st->client_port = ct->client_port;
1438       st->server_port = ct->server_port;
1439     default:
1440       break;
1441   }
1442
1443   gst_rtsp_stream_get_ssrc (ctx->stream, &st->ssrc);
1444
1445   return st;
1446 }
1447
1448 #define AES_128_KEY_LEN 16
1449 #define AES_256_KEY_LEN 32
1450
1451 #define HMAC_32_KEY_LEN 4
1452 #define HMAC_80_KEY_LEN 10
1453
1454 static gboolean
1455 mikey_apply_policy (GstCaps * caps, GstMIKEYMessage * msg, guint8 policy)
1456 {
1457   const gchar *srtp_cipher;
1458   const gchar *srtp_auth;
1459   const GstMIKEYPayload *sp;
1460   guint i;
1461
1462   /* loop over Security policy until we find one containing policy */
1463   for (i = 0;; i++) {
1464     if ((sp = gst_mikey_message_find_payload (msg, GST_MIKEY_PT_SP, i)) == NULL)
1465       break;
1466
1467     if (((GstMIKEYPayloadSP *) sp)->policy == policy)
1468       break;
1469   }
1470
1471   /* the default ciphers */
1472   srtp_cipher = "aes-128-icm";
1473   srtp_auth = "hmac-sha1-80";
1474
1475   /* now override the defaults with what is in the Security Policy */
1476   if (sp != NULL) {
1477     guint len;
1478
1479     /* collect all the params and go over them */
1480     len = gst_mikey_payload_sp_get_n_params (sp);
1481     for (i = 0; i < len; i++) {
1482       const GstMIKEYPayloadSPParam *param =
1483           gst_mikey_payload_sp_get_param (sp, i);
1484
1485       switch (param->type) {
1486         case GST_MIKEY_SP_SRTP_ENC_ALG:
1487           switch (param->val[0]) {
1488             case 0:
1489               srtp_cipher = "null";
1490               break;
1491             case 2:
1492             case 1:
1493               srtp_cipher = "aes-128-icm";
1494               break;
1495             default:
1496               break;
1497           }
1498           break;
1499         case GST_MIKEY_SP_SRTP_ENC_KEY_LEN:
1500           switch (param->val[0]) {
1501             case AES_128_KEY_LEN:
1502               srtp_cipher = "aes-128-icm";
1503               break;
1504             case AES_256_KEY_LEN:
1505               srtp_cipher = "aes-256-icm";
1506               break;
1507             default:
1508               break;
1509           }
1510           break;
1511         case GST_MIKEY_SP_SRTP_AUTH_ALG:
1512           switch (param->val[0]) {
1513             case 0:
1514               srtp_auth = "null";
1515               break;
1516             case 2:
1517             case 1:
1518               srtp_auth = "hmac-sha1-80";
1519               break;
1520             default:
1521               break;
1522           }
1523           break;
1524         case GST_MIKEY_SP_SRTP_AUTH_KEY_LEN:
1525           switch (param->val[0]) {
1526             case HMAC_32_KEY_LEN:
1527               srtp_auth = "hmac-sha1-32";
1528               break;
1529             case HMAC_80_KEY_LEN:
1530               srtp_auth = "hmac-sha1-80";
1531               break;
1532             default:
1533               break;
1534           }
1535           break;
1536         case GST_MIKEY_SP_SRTP_SRTP_ENC:
1537           break;
1538         case GST_MIKEY_SP_SRTP_SRTCP_ENC:
1539           break;
1540         default:
1541           break;
1542       }
1543     }
1544   }
1545   /* now configure the SRTP parameters */
1546   gst_caps_set_simple (caps,
1547       "srtp-cipher", G_TYPE_STRING, srtp_cipher,
1548       "srtp-auth", G_TYPE_STRING, srtp_auth,
1549       "srtcp-cipher", G_TYPE_STRING, srtp_cipher,
1550       "srtcp-auth", G_TYPE_STRING, srtp_auth, NULL);
1551
1552   return TRUE;
1553 }
1554
1555 static gboolean
1556 handle_mikey_data (GstRTSPClient * client, GstRTSPContext * ctx,
1557     guint8 * data, gsize size)
1558 {
1559   GstMIKEYMessage *msg;
1560   guint i, n_cs;
1561   GstCaps *caps = NULL;
1562   GstMIKEYPayloadKEMAC *kemac;
1563   const GstMIKEYPayloadKeyData *pkd;
1564   GstBuffer *key;
1565
1566   /* the MIKEY message contains a CSB or crypto session bundle. It is a
1567    * set of Crypto Sessions protected with the same master key.
1568    * In the context of SRTP, an RTP and its RTCP stream is part of a
1569    * crypto session */
1570   if ((msg = gst_mikey_message_new_from_data (data, size, NULL, NULL)) == NULL)
1571     goto parse_failed;
1572
1573   /* we can only handle SRTP crypto sessions for now */
1574   if (msg->map_type != GST_MIKEY_MAP_TYPE_SRTP)
1575     goto invalid_map_type;
1576
1577   /* get the number of crypto sessions. This maps SSRC to its
1578    * security parameters */
1579   n_cs = gst_mikey_message_get_n_cs (msg);
1580   if (n_cs == 0)
1581     goto no_crypto_sessions;
1582
1583   /* we also need keys */
1584   if (!(kemac = (GstMIKEYPayloadKEMAC *) gst_mikey_message_find_payload
1585           (msg, GST_MIKEY_PT_KEMAC, 0)))
1586     goto no_keys;
1587
1588   /* we don't support encrypted keys */
1589   if (kemac->enc_alg != GST_MIKEY_ENC_NULL
1590       || kemac->mac_alg != GST_MIKEY_MAC_NULL)
1591     goto unsupported_encryption;
1592
1593   /* get Key data sub-payload */
1594   pkd = (const GstMIKEYPayloadKeyData *)
1595       gst_mikey_payload_kemac_get_sub (&kemac->pt, 0);
1596
1597   key =
1598       gst_buffer_new_wrapped (g_memdup (pkd->key_data, pkd->key_len),
1599       pkd->key_len);
1600
1601   /* go over all crypto sessions and create the security policy for each
1602    * SSRC */
1603   for (i = 0; i < n_cs; i++) {
1604     const GstMIKEYMapSRTP *map = gst_mikey_message_get_cs_srtp (msg, i);
1605
1606     caps = gst_caps_new_simple ("application/x-srtp",
1607         "ssrc", G_TYPE_UINT, map->ssrc,
1608         "roc", G_TYPE_UINT, map->roc, "srtp-key", GST_TYPE_BUFFER, key, NULL);
1609     mikey_apply_policy (caps, msg, map->policy);
1610
1611     gst_rtsp_stream_update_crypto (ctx->stream, map->ssrc, caps);
1612     gst_caps_unref (caps);
1613   }
1614   gst_mikey_message_unref (msg);
1615
1616   return TRUE;
1617
1618   /* ERRORS */
1619 parse_failed:
1620   {
1621     GST_DEBUG_OBJECT (client, "failed to parse MIKEY message");
1622     return FALSE;
1623   }
1624 invalid_map_type:
1625   {
1626     GST_DEBUG_OBJECT (client, "invalid map type %d", msg->map_type);
1627     goto cleanup_message;
1628   }
1629 no_crypto_sessions:
1630   {
1631     GST_DEBUG_OBJECT (client, "no crypto sessions");
1632     goto cleanup_message;
1633   }
1634 no_keys:
1635   {
1636     GST_DEBUG_OBJECT (client, "no keys found");
1637     goto cleanup_message;
1638   }
1639 unsupported_encryption:
1640   {
1641     GST_DEBUG_OBJECT (client, "unsupported key encryption");
1642     goto cleanup_message;
1643   }
1644 cleanup_message:
1645   {
1646     gst_mikey_message_unref (msg);
1647     return FALSE;
1648   }
1649 }
1650
1651 #define IS_STRIP_CHAR(c) (g_ascii_isspace ((guchar)(c)) || ((c) == '\"'))
1652
1653 static void
1654 strip_chars (gchar * str)
1655 {
1656   gchar *s;
1657   gsize len;
1658
1659   len = strlen (str);
1660   while (len--) {
1661     if (!IS_STRIP_CHAR (str[len]))
1662       break;
1663     str[len] = '\0';
1664   }
1665   for (s = str; *s && IS_STRIP_CHAR (*s); s++);
1666   memmove (str, s, len + 1);
1667 }
1668
1669 /* KeyMgmt = "KeyMgmt" ":" key-mgmt-spec 0*("," key-mgmt-spec)
1670  * key-mgmt-spec = "prot" "=" KMPID ";" ["uri" "=" %x22 URI %x22 ";"]
1671  */
1672 static gboolean
1673 handle_keymgmt (GstRTSPClient * client, GstRTSPContext * ctx, gchar * keymgmt)
1674 {
1675   gchar **specs;
1676   gint i, j;
1677
1678   specs = g_strsplit (keymgmt, ",", 0);
1679   for (i = 0; specs[i]; i++) {
1680     gchar **split;
1681
1682     split = g_strsplit (specs[i], ";", 0);
1683     for (j = 0; split[j]; j++) {
1684       g_strstrip (split[j]);
1685       if (g_str_has_prefix (split[j], "prot=")) {
1686         g_strstrip (split[j] + 5);
1687         if (!g_str_equal (split[j] + 5, "mikey"))
1688           break;
1689         GST_DEBUG ("found mikey");
1690       } else if (g_str_has_prefix (split[j], "uri=")) {
1691         strip_chars (split[j] + 4);
1692         GST_DEBUG ("found uri '%s'", split[j] + 4);
1693       } else if (g_str_has_prefix (split[j], "data=")) {
1694         guchar *data;
1695         gsize size;
1696         strip_chars (split[j] + 5);
1697         GST_DEBUG ("found data '%s'", split[j] + 5);
1698         data = g_base64_decode_inplace (split[j] + 5, &size);
1699         handle_mikey_data (client, ctx, data, size);
1700       }
1701     }
1702   }
1703   return TRUE;
1704 }
1705
1706 static gboolean
1707 handle_setup_request (GstRTSPClient * client, GstRTSPContext * ctx)
1708 {
1709   GstRTSPClientPrivate *priv = client->priv;
1710   GstRTSPResult res;
1711   GstRTSPUrl *uri;
1712   gchar *transport, *keymgmt;
1713   GstRTSPTransport *ct, *st;
1714   GstRTSPStatusCode code;
1715   GstRTSPSession *session;
1716   GstRTSPStreamTransport *trans;
1717   gchar *trans_str;
1718   GstRTSPSessionMedia *sessmedia;
1719   GstRTSPMedia *media;
1720   GstRTSPStream *stream;
1721   GstRTSPState rtspstate;
1722   GstRTSPClientClass *klass;
1723   gchar *path, *control;
1724   gint matched;
1725   gboolean new_session = FALSE;
1726
1727   if (!ctx->uri)
1728     goto no_uri;
1729
1730   uri = ctx->uri;
1731   klass = GST_RTSP_CLIENT_GET_CLASS (client);
1732   path = klass->make_path_from_uri (client, uri);
1733
1734   /* parse the transport */
1735   res =
1736       gst_rtsp_message_get_header (ctx->request, GST_RTSP_HDR_TRANSPORT,
1737       &transport, 0);
1738   if (res != GST_RTSP_OK)
1739     goto no_transport;
1740
1741   /* we create the session after parsing stuff so that we don't make
1742    * a session for malformed requests */
1743   if (priv->session_pool == NULL)
1744     goto no_pool;
1745
1746   session = ctx->session;
1747
1748   if (session) {
1749     g_object_ref (session);
1750     /* get a handle to the configuration of the media in the session, this can
1751      * return NULL if this is a new url to manage in this session. */
1752     sessmedia = gst_rtsp_session_get_media (session, path, &matched);
1753   } else {
1754     /* we need a new media configuration in this session */
1755     sessmedia = NULL;
1756   }
1757
1758   /* we have no session media, find one and manage it */
1759   if (sessmedia == NULL) {
1760     /* get a handle to the configuration of the media in the session */
1761     media = find_media (client, ctx, path, &matched);
1762   } else {
1763     if ((media = gst_rtsp_session_media_get_media (sessmedia)))
1764       g_object_ref (media);
1765     else
1766       goto media_not_found;
1767   }
1768   /* no media, not found then */
1769   if (media == NULL)
1770     goto media_not_found_no_reply;
1771
1772   if (path[matched] == '\0')
1773     goto control_not_found;
1774
1775   /* path is what matched. */
1776   path[matched] = '\0';
1777   /* control is remainder */
1778   control = &path[matched + 1];
1779
1780   /* find the stream now using the control part */
1781   stream = gst_rtsp_media_find_stream (media, control);
1782   if (stream == NULL)
1783     goto stream_not_found;
1784
1785   /* now we have a uri identifying a valid media and stream */
1786   ctx->stream = stream;
1787   ctx->media = media;
1788
1789   if (session == NULL) {
1790     /* create a session if this fails we probably reached our session limit or
1791      * something. */
1792     if (!(session = gst_rtsp_session_pool_create (priv->session_pool)))
1793       goto service_unavailable;
1794
1795     /* make sure this client is closed when the session is closed */
1796     client_watch_session (client, session);
1797
1798     new_session = TRUE;
1799     /* signal new session */
1800     g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_NEW_SESSION], 0,
1801         session);
1802
1803     ctx->session = session;
1804   }
1805
1806   if (!klass->configure_client_media (client, media, stream, ctx))
1807     goto configure_media_failed_no_reply;
1808
1809   gst_rtsp_transport_new (&ct);
1810
1811   /* parse and find a usable supported transport */
1812   if (!parse_transport (transport, stream, ct))
1813     goto unsupported_transports;
1814
1815   /* update the client transport */
1816   if (!klass->configure_client_transport (client, ctx, ct))
1817     goto unsupported_client_transport;
1818
1819   /* parse the keymgmt */
1820   if (gst_rtsp_message_get_header (ctx->request, GST_RTSP_HDR_KEYMGMT,
1821           &keymgmt, 0) == GST_RTSP_OK) {
1822     if (!handle_keymgmt (client, ctx, keymgmt))
1823       goto keymgmt_error;
1824   }
1825
1826   if (sessmedia == NULL) {
1827     /* manage the media in our session now, if not done already  */
1828     sessmedia = gst_rtsp_session_manage_media (session, path, media);
1829     /* if we stil have no media, error */
1830     if (sessmedia == NULL)
1831       goto sessmedia_unavailable;
1832   } else {
1833     g_object_unref (media);
1834   }
1835
1836   ctx->sessmedia = sessmedia;
1837
1838   /* set in the session media transport */
1839   trans = gst_rtsp_session_media_set_transport (sessmedia, stream, ct);
1840
1841   /* configure the url used to set this transport, this we will use when
1842    * generating the response for the PLAY request */
1843   gst_rtsp_stream_transport_set_url (trans, uri);
1844   /* configure keepalive for this transport */
1845   gst_rtsp_stream_transport_set_keepalive (trans,
1846       (GstRTSPKeepAliveFunc) do_keepalive, session, NULL);
1847
1848   if (ct->lower_transport == GST_RTSP_LOWER_TRANS_TCP) {
1849     /* our callbacks to send data on this TCP connection */
1850     gst_rtsp_stream_transport_set_callbacks (trans,
1851         (GstRTSPSendFunc) do_send_data,
1852         (GstRTSPSendFunc) do_send_data, client, NULL);
1853
1854     g_hash_table_insert (priv->transports,
1855         GINT_TO_POINTER (ct->interleaved.min), trans);
1856     g_hash_table_insert (priv->transports,
1857         GINT_TO_POINTER (ct->interleaved.max), trans);
1858   }
1859
1860   /* create and serialize the server transport */
1861   st = make_server_transport (client, ctx, ct);
1862   trans_str = gst_rtsp_transport_as_text (st);
1863   gst_rtsp_transport_free (st);
1864
1865   /* construct the response now */
1866   code = GST_RTSP_STS_OK;
1867   gst_rtsp_message_init_response (ctx->response, code,
1868       gst_rtsp_status_as_text (code), ctx->request);
1869
1870   gst_rtsp_message_add_header (ctx->response, GST_RTSP_HDR_TRANSPORT,
1871       trans_str);
1872   g_free (trans_str);
1873
1874   send_message (client, ctx, ctx->response, FALSE);
1875
1876   /* update the state */
1877   rtspstate = gst_rtsp_session_media_get_rtsp_state (sessmedia);
1878   switch (rtspstate) {
1879     case GST_RTSP_STATE_PLAYING:
1880     case GST_RTSP_STATE_RECORDING:
1881     case GST_RTSP_STATE_READY:
1882       /* no state change */
1883       break;
1884     default:
1885       gst_rtsp_session_media_set_rtsp_state (sessmedia, GST_RTSP_STATE_READY);
1886       break;
1887   }
1888   g_object_unref (session);
1889   g_free (path);
1890
1891   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_SETUP_REQUEST], 0, ctx);
1892
1893   return TRUE;
1894
1895   /* ERRORS */
1896 no_uri:
1897   {
1898     GST_ERROR ("client %p: no uri", client);
1899     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
1900     return FALSE;
1901   }
1902 no_transport:
1903   {
1904     GST_ERROR ("client %p: no transport", client);
1905     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, ctx);
1906     goto cleanup_path;
1907   }
1908 no_pool:
1909   {
1910     GST_ERROR ("client %p: no session pool configured", client);
1911     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
1912     goto cleanup_path;
1913   }
1914 media_not_found_no_reply:
1915   {
1916     GST_ERROR ("client %p: media '%s' not found", client, path);
1917     /* error reply is already sent */
1918     goto cleanup_path;
1919   }
1920 media_not_found:
1921   {
1922     GST_ERROR ("client %p: media '%s' not found", client, path);
1923     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
1924     goto cleanup_path;
1925   }
1926 control_not_found:
1927   {
1928     GST_ERROR ("client %p: no control in path '%s'", client, path);
1929     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
1930     g_object_unref (media);
1931     goto cleanup_path;
1932   }
1933 stream_not_found:
1934   {
1935     GST_ERROR ("client %p: stream '%s' not found", client, control);
1936     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
1937     g_object_unref (media);
1938     goto cleanup_path;
1939   }
1940 service_unavailable:
1941   {
1942     GST_ERROR ("client %p: can't create session", client);
1943     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, ctx);
1944     g_object_unref (media);
1945     goto cleanup_path;
1946   }
1947 sessmedia_unavailable:
1948   {
1949     GST_ERROR ("client %p: can't create session media", client);
1950     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, ctx);
1951     g_object_unref (media);
1952     goto cleanup_session;
1953   }
1954 configure_media_failed_no_reply:
1955   {
1956     GST_ERROR ("client %p: configure_media failed", client);
1957     /* error reply is already sent */
1958     goto cleanup_session;
1959   }
1960 unsupported_transports:
1961   {
1962     GST_ERROR ("client %p: unsupported transports", client);
1963     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, ctx);
1964     goto cleanup_transport;
1965   }
1966 unsupported_client_transport:
1967   {
1968     GST_ERROR ("client %p: unsupported client transport", client);
1969     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, ctx);
1970     goto cleanup_transport;
1971   }
1972 keymgmt_error:
1973   {
1974     GST_ERROR ("client %p: keymgmt error", client);
1975     send_generic_response (client, GST_RTSP_STS_KEY_MANAGEMENT_FAILURE, ctx);
1976     goto cleanup_transport;
1977   }
1978   {
1979   cleanup_transport:
1980     gst_rtsp_transport_free (ct);
1981   cleanup_session:
1982     if (new_session)
1983       gst_rtsp_session_pool_remove (priv->session_pool, session);
1984     g_object_unref (session);
1985   cleanup_path:
1986     g_free (path);
1987     return FALSE;
1988   }
1989 }
1990
1991 static GstSDPMessage *
1992 create_sdp (GstRTSPClient * client, GstRTSPMedia * media)
1993 {
1994   GstRTSPClientPrivate *priv = client->priv;
1995   GstSDPMessage *sdp;
1996   GstSDPInfo info;
1997   const gchar *proto;
1998
1999   gst_sdp_message_new (&sdp);
2000
2001   /* some standard things first */
2002   gst_sdp_message_set_version (sdp, "0");
2003
2004   if (priv->is_ipv6)
2005     proto = "IP6";
2006   else
2007     proto = "IP4";
2008
2009   gst_sdp_message_set_origin (sdp, "-", "1188340656180883", "1", "IN", proto,
2010       priv->server_ip);
2011
2012   gst_sdp_message_set_session_name (sdp, "Session streamed with GStreamer");
2013   gst_sdp_message_set_information (sdp, "rtsp-server");
2014   gst_sdp_message_add_time (sdp, "0", "0", NULL);
2015   gst_sdp_message_add_attribute (sdp, "tool", "GStreamer");
2016   gst_sdp_message_add_attribute (sdp, "type", "broadcast");
2017   gst_sdp_message_add_attribute (sdp, "control", "*");
2018
2019   info.is_ipv6 = priv->is_ipv6;
2020   info.server_ip = priv->server_ip;
2021
2022   /* create an SDP for the media object */
2023   if (!gst_rtsp_media_setup_sdp (media, sdp, &info))
2024     goto no_sdp;
2025
2026   return sdp;
2027
2028   /* ERRORS */
2029 no_sdp:
2030   {
2031     GST_ERROR ("client %p: could not create SDP", client);
2032     gst_sdp_message_free (sdp);
2033     return NULL;
2034   }
2035 }
2036
2037 /* for the describe we must generate an SDP */
2038 static gboolean
2039 handle_describe_request (GstRTSPClient * client, GstRTSPContext * ctx)
2040 {
2041   GstRTSPClientPrivate *priv = client->priv;
2042   GstRTSPResult res;
2043   GstSDPMessage *sdp;
2044   guint i;
2045   gchar *path, *str;
2046   GstRTSPMedia *media;
2047   GstRTSPClientClass *klass;
2048
2049   klass = GST_RTSP_CLIENT_GET_CLASS (client);
2050
2051   if (!ctx->uri)
2052     goto no_uri;
2053
2054   /* check what kind of format is accepted, we don't really do anything with it
2055    * and always return SDP for now. */
2056   for (i = 0;; i++) {
2057     gchar *accept;
2058
2059     res =
2060         gst_rtsp_message_get_header (ctx->request, GST_RTSP_HDR_ACCEPT,
2061         &accept, i);
2062     if (res == GST_RTSP_ENOTIMPL)
2063       break;
2064
2065     if (g_ascii_strcasecmp (accept, "application/sdp") == 0)
2066       break;
2067   }
2068
2069   if (!priv->mount_points)
2070     goto no_mount_points;
2071
2072   if (!(path = gst_rtsp_mount_points_make_path (priv->mount_points, ctx->uri)))
2073     goto no_path;
2074
2075   /* find the media object for the uri */
2076   if (!(media = find_media (client, ctx, path, NULL)))
2077     goto no_media;
2078
2079   /* create an SDP for the media object on this client */
2080   if (!(sdp = klass->create_sdp (client, media)))
2081     goto no_sdp;
2082
2083   /* we suspend after the describe */
2084   gst_rtsp_media_suspend (media);
2085   g_object_unref (media);
2086
2087   gst_rtsp_message_init_response (ctx->response, GST_RTSP_STS_OK,
2088       gst_rtsp_status_as_text (GST_RTSP_STS_OK), ctx->request);
2089
2090   gst_rtsp_message_add_header (ctx->response, GST_RTSP_HDR_CONTENT_TYPE,
2091       "application/sdp");
2092
2093   /* content base for some clients that might screw up creating the setup uri */
2094   str = make_base_url (client, ctx->uri, path);
2095   g_free (path);
2096
2097   GST_INFO ("adding content-base: %s", str);
2098   gst_rtsp_message_take_header (ctx->response, GST_RTSP_HDR_CONTENT_BASE, str);
2099
2100   /* add SDP to the response body */
2101   str = gst_sdp_message_as_text (sdp);
2102   gst_rtsp_message_take_body (ctx->response, (guint8 *) str, strlen (str));
2103   gst_sdp_message_free (sdp);
2104
2105   send_message (client, ctx, ctx->response, FALSE);
2106
2107   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_DESCRIBE_REQUEST],
2108       0, ctx);
2109
2110   return TRUE;
2111
2112   /* ERRORS */
2113 no_uri:
2114   {
2115     GST_ERROR ("client %p: no uri", client);
2116     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
2117     return FALSE;
2118   }
2119 no_mount_points:
2120   {
2121     GST_ERROR ("client %p: no mount points configured", client);
2122     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
2123     return FALSE;
2124   }
2125 no_path:
2126   {
2127     GST_ERROR ("client %p: can't find path for url", client);
2128     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
2129     return FALSE;
2130   }
2131 no_media:
2132   {
2133     GST_ERROR ("client %p: no media", client);
2134     g_free (path);
2135     /* error reply is already sent */
2136     return FALSE;
2137   }
2138 no_sdp:
2139   {
2140     GST_ERROR ("client %p: can't create SDP", client);
2141     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, ctx);
2142     g_free (path);
2143     g_object_unref (media);
2144     return FALSE;
2145   }
2146 }
2147
2148 static gboolean
2149 handle_options_request (GstRTSPClient * client, GstRTSPContext * ctx)
2150 {
2151   GstRTSPMethod options;
2152   gchar *str;
2153
2154   options = GST_RTSP_DESCRIBE |
2155       GST_RTSP_OPTIONS |
2156       GST_RTSP_PAUSE |
2157       GST_RTSP_PLAY |
2158       GST_RTSP_SETUP |
2159       GST_RTSP_GET_PARAMETER | GST_RTSP_SET_PARAMETER | GST_RTSP_TEARDOWN;
2160
2161   str = gst_rtsp_options_as_text (options);
2162
2163   gst_rtsp_message_init_response (ctx->response, GST_RTSP_STS_OK,
2164       gst_rtsp_status_as_text (GST_RTSP_STS_OK), ctx->request);
2165
2166   gst_rtsp_message_add_header (ctx->response, GST_RTSP_HDR_PUBLIC, str);
2167   g_free (str);
2168
2169   send_message (client, ctx, ctx->response, FALSE);
2170
2171   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_OPTIONS_REQUEST],
2172       0, ctx);
2173
2174   return TRUE;
2175 }
2176
2177 /* remove duplicate and trailing '/' */
2178 static void
2179 sanitize_uri (GstRTSPUrl * uri)
2180 {
2181   gint i, len;
2182   gchar *s, *d;
2183   gboolean have_slash, prev_slash;
2184
2185   s = d = uri->abspath;
2186   len = strlen (uri->abspath);
2187
2188   prev_slash = FALSE;
2189
2190   for (i = 0; i < len; i++) {
2191     have_slash = s[i] == '/';
2192     *d = s[i];
2193     if (!have_slash || !prev_slash)
2194       d++;
2195     prev_slash = have_slash;
2196   }
2197   len = d - uri->abspath;
2198   /* don't remove the first slash if that's the only thing left */
2199   if (len > 1 && *(d - 1) == '/')
2200     d--;
2201   *d = '\0';
2202 }
2203
2204 /* is called when the session is removed from its session pool. */
2205 static void
2206 client_session_removed (GstRTSPSessionPool * pool, GstRTSPSession * session,
2207     GstRTSPClient * client)
2208 {
2209   GstRTSPClientPrivate *priv = client->priv;
2210
2211   GST_INFO ("client %p: session %p removed", client, session);
2212
2213   g_mutex_lock (&priv->lock);
2214   if (priv->watch != NULL)
2215     gst_rtsp_watch_set_send_backlog (priv->watch, 0, 0);
2216   client_unwatch_session (client, session, NULL);
2217   if (priv->watch != NULL)
2218     gst_rtsp_watch_set_send_backlog (priv->watch, 0, WATCH_BACKLOG_SIZE);
2219   g_mutex_unlock (&priv->lock);
2220 }
2221
2222 /* Returns TRUE if there are no Require headers, otherwise returns FALSE
2223  * and also returns a newly-allocated string of (comma-separated) unsupported
2224  * options in the unsupported_reqs variable .
2225  *
2226  * There may be multiple Require headers, but we must send one single
2227  * Unsupported header with all the unsupported options as response. If
2228  * an incoming Require header contained a comma-separated list of options
2229  * GstRtspConnection will already have split that list up into multiple
2230  * headers.
2231  *
2232  * TODO: allow the application to decide what features are supported
2233  */
2234 static gboolean
2235 check_request_requirements (GstRTSPMessage * msg, gchar ** unsupported_reqs)
2236 {
2237   GstRTSPResult res;
2238   GPtrArray *arr = NULL;
2239   gchar *reqs = NULL;
2240   gint i;
2241
2242   i = 0;
2243   do {
2244     res = gst_rtsp_message_get_header (msg, GST_RTSP_HDR_REQUIRE, &reqs, i++);
2245
2246     if (res == GST_RTSP_ENOTIMPL)
2247       break;
2248
2249     if (arr == NULL)
2250       arr = g_ptr_array_new_with_free_func ((GDestroyNotify) g_free);
2251
2252     g_ptr_array_add (arr, g_strdup (reqs));
2253   }
2254   while (TRUE);
2255
2256   /* if we don't have any Require headers at all, all is fine */
2257   if (i == 1)
2258     return TRUE;
2259
2260   /* otherwise we've now processed at all the Require headers */
2261   g_ptr_array_add (arr, NULL);
2262
2263   /* for now we don't commit to supporting anything, so will just report
2264    * all of the required options as unsupported */
2265   *unsupported_reqs = g_strjoinv (", ", (gchar **) arr->pdata);
2266
2267   g_ptr_array_unref (arr);
2268   return FALSE;
2269 }
2270
2271 static void
2272 handle_request (GstRTSPClient * client, GstRTSPMessage * request)
2273 {
2274   GstRTSPClientPrivate *priv = client->priv;
2275   GstRTSPMethod method;
2276   const gchar *uristr;
2277   GstRTSPUrl *uri = NULL;
2278   GstRTSPVersion version;
2279   GstRTSPResult res;
2280   GstRTSPSession *session = NULL;
2281   GstRTSPContext sctx = { NULL }, *ctx;
2282   GstRTSPMessage response = { 0 };
2283   gchar *unsupported_reqs = NULL;
2284   gchar *sessid;
2285
2286   if (!(ctx = gst_rtsp_context_get_current ())) {
2287     ctx = &sctx;
2288     ctx->auth = priv->auth;
2289     gst_rtsp_context_push_current (ctx);
2290   }
2291
2292   ctx->conn = priv->connection;
2293   ctx->client = client;
2294   ctx->request = request;
2295   ctx->response = &response;
2296
2297   if (gst_debug_category_get_threshold (rtsp_client_debug) >= GST_LEVEL_LOG) {
2298     gst_rtsp_message_dump (request);
2299   }
2300
2301   gst_rtsp_message_parse_request (request, &method, &uristr, &version);
2302
2303   GST_INFO ("client %p: received a request %s %s %s", client,
2304       gst_rtsp_method_as_text (method), uristr,
2305       gst_rtsp_version_as_text (version));
2306
2307   /* we can only handle 1.0 requests */
2308   if (version != GST_RTSP_VERSION_1_0)
2309     goto not_supported;
2310
2311   ctx->method = method;
2312
2313   /* we always try to parse the url first */
2314   if (strcmp (uristr, "*") == 0) {
2315     /* special case where we have * as uri, keep uri = NULL */
2316   } else if (gst_rtsp_url_parse (uristr, &uri) != GST_RTSP_OK) {
2317     /* check if the uristr is an absolute path <=> scheme and host information
2318      * is missing */
2319     gchar *scheme;
2320
2321     scheme = g_uri_parse_scheme (uristr);
2322     if (scheme == NULL && g_str_has_prefix (uristr, "/")) {
2323       gchar *absolute_uristr = NULL;
2324
2325       GST_WARNING_OBJECT (client, "request doesn't contain absolute url");
2326       if (priv->server_ip == NULL) {
2327         GST_WARNING_OBJECT (client, "host information missing");
2328         goto bad_request;
2329       }
2330
2331       absolute_uristr =
2332           g_strdup_printf ("rtsp://%s%s", priv->server_ip, uristr);
2333
2334       GST_DEBUG_OBJECT (client, "absolute url: %s", absolute_uristr);
2335       if (gst_rtsp_url_parse (absolute_uristr, &uri) != GST_RTSP_OK) {
2336         g_free (absolute_uristr);
2337         goto bad_request;
2338       }
2339       g_free (absolute_uristr);
2340     } else {
2341       g_free (scheme);
2342       goto bad_request;
2343     }
2344   }
2345
2346   /* get the session if there is any */
2347   res = gst_rtsp_message_get_header (request, GST_RTSP_HDR_SESSION, &sessid, 0);
2348   if (res == GST_RTSP_OK) {
2349     if (priv->session_pool == NULL)
2350       goto no_pool;
2351
2352     /* we had a session in the request, find it again */
2353     if (!(session = gst_rtsp_session_pool_find (priv->session_pool, sessid)))
2354       goto session_not_found;
2355
2356     /* we add the session to the client list of watched sessions. When a session
2357      * disappears because it times out, we will be notified. If all sessions are
2358      * gone, we will close the connection */
2359     client_watch_session (client, session);
2360   }
2361
2362   /* sanitize the uri */
2363   if (uri)
2364     sanitize_uri (uri);
2365   ctx->uri = uri;
2366   ctx->session = session;
2367
2368   if (!gst_rtsp_auth_check (GST_RTSP_AUTH_CHECK_URL))
2369     goto not_authorized;
2370
2371   /* handle any 'Require' headers */
2372   if (!check_request_requirements (ctx->request, &unsupported_reqs))
2373     goto unsupported_requirement;
2374
2375   /* now see what is asked and dispatch to a dedicated handler */
2376   switch (method) {
2377     case GST_RTSP_OPTIONS:
2378       handle_options_request (client, ctx);
2379       break;
2380     case GST_RTSP_DESCRIBE:
2381       handle_describe_request (client, ctx);
2382       break;
2383     case GST_RTSP_SETUP:
2384       handle_setup_request (client, ctx);
2385       break;
2386     case GST_RTSP_PLAY:
2387       handle_play_request (client, ctx);
2388       break;
2389     case GST_RTSP_PAUSE:
2390       handle_pause_request (client, ctx);
2391       break;
2392     case GST_RTSP_TEARDOWN:
2393       handle_teardown_request (client, ctx);
2394       break;
2395     case GST_RTSP_SET_PARAMETER:
2396       handle_set_param_request (client, ctx);
2397       break;
2398     case GST_RTSP_GET_PARAMETER:
2399       handle_get_param_request (client, ctx);
2400       break;
2401     case GST_RTSP_ANNOUNCE:
2402     case GST_RTSP_RECORD:
2403     case GST_RTSP_REDIRECT:
2404       goto not_implemented;
2405     case GST_RTSP_INVALID:
2406     default:
2407       goto bad_request;
2408   }
2409
2410 done:
2411   if (ctx == &sctx)
2412     gst_rtsp_context_pop_current (ctx);
2413   if (session)
2414     g_object_unref (session);
2415   if (uri)
2416     gst_rtsp_url_free (uri);
2417   return;
2418
2419   /* ERRORS */
2420 not_supported:
2421   {
2422     GST_ERROR ("client %p: version %d not supported", client, version);
2423     send_generic_response (client, GST_RTSP_STS_RTSP_VERSION_NOT_SUPPORTED,
2424         ctx);
2425     goto done;
2426   }
2427 bad_request:
2428   {
2429     GST_ERROR ("client %p: bad request", client);
2430     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
2431     goto done;
2432   }
2433 no_pool:
2434   {
2435     GST_ERROR ("client %p: no pool configured", client);
2436     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
2437     goto done;
2438   }
2439 session_not_found:
2440   {
2441     GST_ERROR ("client %p: session not found", client);
2442     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
2443     goto done;
2444   }
2445 not_authorized:
2446   {
2447     GST_ERROR ("client %p: not allowed", client);
2448     /* error reply is already sent */
2449     goto done;
2450   }
2451 unsupported_requirement:
2452   {
2453     GST_ERROR ("client %p: Required option is not supported (%s)", client,
2454         unsupported_reqs);
2455     send_option_not_supported_response (client, ctx, unsupported_reqs);
2456     g_free (unsupported_reqs);
2457     goto done;
2458   }
2459 not_implemented:
2460   {
2461     GST_ERROR ("client %p: method %d not implemented", client, method);
2462     send_generic_response (client, GST_RTSP_STS_NOT_IMPLEMENTED, ctx);
2463     goto done;
2464   }
2465 }
2466
2467
2468 static void
2469 handle_response (GstRTSPClient * client, GstRTSPMessage * response)
2470 {
2471   GstRTSPClientPrivate *priv = client->priv;
2472   GstRTSPResult res;
2473   GstRTSPSession *session = NULL;
2474   GstRTSPContext sctx = { NULL }, *ctx;
2475   gchar *sessid;
2476
2477   if (!(ctx = gst_rtsp_context_get_current ())) {
2478     ctx = &sctx;
2479     ctx->auth = priv->auth;
2480     gst_rtsp_context_push_current (ctx);
2481   }
2482
2483   ctx->conn = priv->connection;
2484   ctx->client = client;
2485   ctx->request = NULL;
2486   ctx->uri = NULL;
2487   ctx->method = GST_RTSP_INVALID;
2488   ctx->response = response;
2489
2490   if (gst_debug_category_get_threshold (rtsp_client_debug) >= GST_LEVEL_LOG) {
2491     gst_rtsp_message_dump (response);
2492   }
2493
2494   GST_INFO ("client %p: received a response", client);
2495
2496   /* get the session if there is any */
2497   res =
2498       gst_rtsp_message_get_header (response, GST_RTSP_HDR_SESSION, &sessid, 0);
2499   if (res == GST_RTSP_OK) {
2500     if (priv->session_pool == NULL)
2501       goto no_pool;
2502
2503     /* we had a session in the request, find it again */
2504     if (!(session = gst_rtsp_session_pool_find (priv->session_pool, sessid)))
2505       goto session_not_found;
2506
2507     /* we add the session to the client list of watched sessions. When a session
2508      * disappears because it times out, we will be notified. If all sessions are
2509      * gone, we will close the connection */
2510     client_watch_session (client, session);
2511   }
2512
2513   ctx->session = session;
2514
2515   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_HANDLE_RESPONSE],
2516       0, ctx);
2517
2518 done:
2519   if (ctx == &sctx)
2520     gst_rtsp_context_pop_current (ctx);
2521   if (session)
2522     g_object_unref (session);
2523   return;
2524
2525 no_pool:
2526   {
2527     GST_ERROR ("client %p: no pool configured", client);
2528     goto done;
2529   }
2530 session_not_found:
2531   {
2532     GST_ERROR ("client %p: session not found", client);
2533     goto done;
2534   }
2535 }
2536
2537 static void
2538 handle_data (GstRTSPClient * client, GstRTSPMessage * message)
2539 {
2540   GstRTSPClientPrivate *priv = client->priv;
2541   GstRTSPResult res;
2542   guint8 channel;
2543   guint8 *data;
2544   guint size;
2545   GstBuffer *buffer;
2546   GstRTSPStreamTransport *trans;
2547
2548   /* find the stream for this message */
2549   res = gst_rtsp_message_parse_data (message, &channel);
2550   if (res != GST_RTSP_OK)
2551     return;
2552
2553   gst_rtsp_message_steal_body (message, &data, &size);
2554
2555   buffer = gst_buffer_new_wrapped (data, size);
2556
2557   trans =
2558       g_hash_table_lookup (priv->transports, GINT_TO_POINTER ((gint) channel));
2559   if (trans) {
2560     /* dispatch to the stream based on the channel number */
2561     gst_rtsp_stream_transport_recv_data (trans, channel, buffer);
2562   } else {
2563     gst_buffer_unref (buffer);
2564   }
2565 }
2566
2567 /**
2568  * gst_rtsp_client_set_session_pool:
2569  * @client: a #GstRTSPClient
2570  * @pool: (transfer none): a #GstRTSPSessionPool
2571  *
2572  * Set @pool as the sessionpool for @client which it will use to find
2573  * or allocate sessions. the sessionpool is usually inherited from the server
2574  * that created the client but can be overridden later.
2575  */
2576 void
2577 gst_rtsp_client_set_session_pool (GstRTSPClient * client,
2578     GstRTSPSessionPool * pool)
2579 {
2580   GstRTSPSessionPool *old;
2581   GstRTSPClientPrivate *priv;
2582
2583   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2584
2585   priv = client->priv;
2586
2587   if (pool)
2588     g_object_ref (pool);
2589
2590   g_mutex_lock (&priv->lock);
2591   old = priv->session_pool;
2592   priv->session_pool = pool;
2593
2594   if (priv->session_removed_id) {
2595     g_signal_handler_disconnect (old, priv->session_removed_id);
2596     priv->session_removed_id = 0;
2597   }
2598   g_mutex_unlock (&priv->lock);
2599
2600   /* FIXME, should remove all sessions from the old pool for this client */
2601   if (old)
2602     g_object_unref (old);
2603 }
2604
2605 /**
2606  * gst_rtsp_client_get_session_pool:
2607  * @client: a #GstRTSPClient
2608  *
2609  * Get the #GstRTSPSessionPool object that @client uses to manage its sessions.
2610  *
2611  * Returns: (transfer full): a #GstRTSPSessionPool, unref after usage.
2612  */
2613 GstRTSPSessionPool *
2614 gst_rtsp_client_get_session_pool (GstRTSPClient * client)
2615 {
2616   GstRTSPClientPrivate *priv;
2617   GstRTSPSessionPool *result;
2618
2619   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2620
2621   priv = client->priv;
2622
2623   g_mutex_lock (&priv->lock);
2624   if ((result = priv->session_pool))
2625     g_object_ref (result);
2626   g_mutex_unlock (&priv->lock);
2627
2628   return result;
2629 }
2630
2631 /**
2632  * gst_rtsp_client_set_mount_points:
2633  * @client: a #GstRTSPClient
2634  * @mounts: (transfer none): a #GstRTSPMountPoints
2635  *
2636  * Set @mounts as the mount points for @client which it will use to map urls
2637  * to media streams. These mount points are usually inherited from the server that
2638  * created the client but can be overriden later.
2639  */
2640 void
2641 gst_rtsp_client_set_mount_points (GstRTSPClient * client,
2642     GstRTSPMountPoints * mounts)
2643 {
2644   GstRTSPClientPrivate *priv;
2645   GstRTSPMountPoints *old;
2646
2647   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2648
2649   priv = client->priv;
2650
2651   if (mounts)
2652     g_object_ref (mounts);
2653
2654   g_mutex_lock (&priv->lock);
2655   old = priv->mount_points;
2656   priv->mount_points = mounts;
2657   g_mutex_unlock (&priv->lock);
2658
2659   if (old)
2660     g_object_unref (old);
2661 }
2662
2663 /**
2664  * gst_rtsp_client_get_mount_points:
2665  * @client: a #GstRTSPClient
2666  *
2667  * Get the #GstRTSPMountPoints object that @client uses to manage its sessions.
2668  *
2669  * Returns: (transfer full): a #GstRTSPMountPoints, unref after usage.
2670  */
2671 GstRTSPMountPoints *
2672 gst_rtsp_client_get_mount_points (GstRTSPClient * client)
2673 {
2674   GstRTSPClientPrivate *priv;
2675   GstRTSPMountPoints *result;
2676
2677   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2678
2679   priv = client->priv;
2680
2681   g_mutex_lock (&priv->lock);
2682   if ((result = priv->mount_points))
2683     g_object_ref (result);
2684   g_mutex_unlock (&priv->lock);
2685
2686   return result;
2687 }
2688
2689 /**
2690  * gst_rtsp_client_set_auth:
2691  * @client: a #GstRTSPClient
2692  * @auth: (transfer none): a #GstRTSPAuth
2693  *
2694  * configure @auth to be used as the authentication manager of @client.
2695  */
2696 void
2697 gst_rtsp_client_set_auth (GstRTSPClient * client, GstRTSPAuth * auth)
2698 {
2699   GstRTSPClientPrivate *priv;
2700   GstRTSPAuth *old;
2701
2702   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2703
2704   priv = client->priv;
2705
2706   if (auth)
2707     g_object_ref (auth);
2708
2709   g_mutex_lock (&priv->lock);
2710   old = priv->auth;
2711   priv->auth = auth;
2712   g_mutex_unlock (&priv->lock);
2713
2714   if (old)
2715     g_object_unref (old);
2716 }
2717
2718
2719 /**
2720  * gst_rtsp_client_get_auth:
2721  * @client: a #GstRTSPClient
2722  *
2723  * Get the #GstRTSPAuth used as the authentication manager of @client.
2724  *
2725  * Returns: (transfer full): the #GstRTSPAuth of @client. g_object_unref() after
2726  * usage.
2727  */
2728 GstRTSPAuth *
2729 gst_rtsp_client_get_auth (GstRTSPClient * client)
2730 {
2731   GstRTSPClientPrivate *priv;
2732   GstRTSPAuth *result;
2733
2734   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2735
2736   priv = client->priv;
2737
2738   g_mutex_lock (&priv->lock);
2739   if ((result = priv->auth))
2740     g_object_ref (result);
2741   g_mutex_unlock (&priv->lock);
2742
2743   return result;
2744 }
2745
2746 /**
2747  * gst_rtsp_client_set_thread_pool:
2748  * @client: a #GstRTSPClient
2749  * @pool: (transfer none): a #GstRTSPThreadPool
2750  *
2751  * configure @pool to be used as the thread pool of @client.
2752  */
2753 void
2754 gst_rtsp_client_set_thread_pool (GstRTSPClient * client,
2755     GstRTSPThreadPool * pool)
2756 {
2757   GstRTSPClientPrivate *priv;
2758   GstRTSPThreadPool *old;
2759
2760   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2761
2762   priv = client->priv;
2763
2764   if (pool)
2765     g_object_ref (pool);
2766
2767   g_mutex_lock (&priv->lock);
2768   old = priv->thread_pool;
2769   priv->thread_pool = pool;
2770   g_mutex_unlock (&priv->lock);
2771
2772   if (old)
2773     g_object_unref (old);
2774 }
2775
2776 /**
2777  * gst_rtsp_client_get_thread_pool:
2778  * @client: a #GstRTSPClient
2779  *
2780  * Get the #GstRTSPThreadPool used as the thread pool of @client.
2781  *
2782  * Returns: (transfer full): the #GstRTSPThreadPool of @client. g_object_unref() after
2783  * usage.
2784  */
2785 GstRTSPThreadPool *
2786 gst_rtsp_client_get_thread_pool (GstRTSPClient * client)
2787 {
2788   GstRTSPClientPrivate *priv;
2789   GstRTSPThreadPool *result;
2790
2791   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2792
2793   priv = client->priv;
2794
2795   g_mutex_lock (&priv->lock);
2796   if ((result = priv->thread_pool))
2797     g_object_ref (result);
2798   g_mutex_unlock (&priv->lock);
2799
2800   return result;
2801 }
2802
2803 /**
2804  * gst_rtsp_client_set_connection:
2805  * @client: a #GstRTSPClient
2806  * @conn: (transfer full): a #GstRTSPConnection
2807  *
2808  * Set the #GstRTSPConnection of @client. This function takes ownership of
2809  * @conn.
2810  *
2811  * Returns: %TRUE on success.
2812  */
2813 gboolean
2814 gst_rtsp_client_set_connection (GstRTSPClient * client,
2815     GstRTSPConnection * conn)
2816 {
2817   GstRTSPClientPrivate *priv;
2818   GSocket *read_socket;
2819   GSocketAddress *address;
2820   GstRTSPUrl *url;
2821   GError *error = NULL;
2822
2823   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), FALSE);
2824   g_return_val_if_fail (conn != NULL, FALSE);
2825
2826   priv = client->priv;
2827
2828   read_socket = gst_rtsp_connection_get_read_socket (conn);
2829
2830   if (!(address = g_socket_get_local_address (read_socket, &error)))
2831     goto no_address;
2832
2833   g_free (priv->server_ip);
2834   /* keep the original ip that the client connected to */
2835   if (G_IS_INET_SOCKET_ADDRESS (address)) {
2836     GInetAddress *iaddr;
2837
2838     iaddr = g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (address));
2839
2840     /* socket might be ipv6 but adress still ipv4 */
2841     priv->is_ipv6 = g_inet_address_get_family (iaddr) == G_SOCKET_FAMILY_IPV6;
2842     priv->server_ip = g_inet_address_to_string (iaddr);
2843     g_object_unref (address);
2844   } else {
2845     priv->is_ipv6 = g_socket_get_family (read_socket) == G_SOCKET_FAMILY_IPV6;
2846     priv->server_ip = g_strdup ("unknown");
2847   }
2848
2849   GST_INFO ("client %p connected to server ip %s, ipv6 = %d", client,
2850       priv->server_ip, priv->is_ipv6);
2851
2852   url = gst_rtsp_connection_get_url (conn);
2853   GST_INFO ("added new client %p ip %s:%d", client, url->host, url->port);
2854
2855   priv->connection = conn;
2856
2857   return TRUE;
2858
2859   /* ERRORS */
2860 no_address:
2861   {
2862     GST_ERROR ("could not get local address %s", error->message);
2863     g_error_free (error);
2864     return FALSE;
2865   }
2866 }
2867
2868 /**
2869  * gst_rtsp_client_get_connection:
2870  * @client: a #GstRTSPClient
2871  *
2872  * Get the #GstRTSPConnection of @client.
2873  *
2874  * Returns: (transfer none): the #GstRTSPConnection of @client.
2875  * The connection object returned remains valid until the client is freed.
2876  */
2877 GstRTSPConnection *
2878 gst_rtsp_client_get_connection (GstRTSPClient * client)
2879 {
2880   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2881
2882   return client->priv->connection;
2883 }
2884
2885 /**
2886  * gst_rtsp_client_set_send_func:
2887  * @client: a #GstRTSPClient
2888  * @func: (scope notified): a #GstRTSPClientSendFunc
2889  * @user_data: (closure): user data passed to @func
2890  * @notify: (allow-none): called when @user_data is no longer in use
2891  *
2892  * Set @func as the callback that will be called when a new message needs to be
2893  * sent to the client. @user_data is passed to @func and @notify is called when
2894  * @user_data is no longer in use.
2895  *
2896  * By default, the client will send the messages on the #GstRTSPConnection that
2897  * was configured with gst_rtsp_client_attach() was called.
2898  */
2899 void
2900 gst_rtsp_client_set_send_func (GstRTSPClient * client,
2901     GstRTSPClientSendFunc func, gpointer user_data, GDestroyNotify notify)
2902 {
2903   GstRTSPClientPrivate *priv;
2904   GDestroyNotify old_notify;
2905   gpointer old_data;
2906
2907   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2908
2909   priv = client->priv;
2910
2911   g_mutex_lock (&priv->send_lock);
2912   priv->send_func = func;
2913   old_notify = priv->send_notify;
2914   old_data = priv->send_data;
2915   priv->send_notify = notify;
2916   priv->send_data = user_data;
2917   g_mutex_unlock (&priv->send_lock);
2918
2919   if (old_notify)
2920     old_notify (old_data);
2921 }
2922
2923 /**
2924  * gst_rtsp_client_handle_message:
2925  * @client: a #GstRTSPClient
2926  * @message: (transfer none): an #GstRTSPMessage
2927  *
2928  * Let the client handle @message.
2929  *
2930  * Returns: a #GstRTSPResult.
2931  */
2932 GstRTSPResult
2933 gst_rtsp_client_handle_message (GstRTSPClient * client,
2934     GstRTSPMessage * message)
2935 {
2936   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), GST_RTSP_EINVAL);
2937   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2938
2939   switch (message->type) {
2940     case GST_RTSP_MESSAGE_REQUEST:
2941       handle_request (client, message);
2942       break;
2943     case GST_RTSP_MESSAGE_RESPONSE:
2944       handle_response (client, message);
2945       break;
2946     case GST_RTSP_MESSAGE_DATA:
2947       handle_data (client, message);
2948       break;
2949     default:
2950       break;
2951   }
2952   return GST_RTSP_OK;
2953 }
2954
2955 /**
2956  * gst_rtsp_client_send_message:
2957  * @client: a #GstRTSPClient
2958  * @session: (allow-none) (transfer none): a #GstRTSPSession to send
2959  *   the message to or %NULL
2960  * @message: (transfer none): The #GstRTSPMessage to send
2961  *
2962  * Send a message message to the remote end. @message must be a
2963  * #GST_RTSP_MESSAGE_REQUEST or a #GST_RTSP_MESSAGE_RESPONSE.
2964  */
2965 GstRTSPResult
2966 gst_rtsp_client_send_message (GstRTSPClient * client, GstRTSPSession * session,
2967     GstRTSPMessage * message)
2968 {
2969   GstRTSPContext sctx = { NULL }
2970   , *ctx;
2971   GstRTSPClientPrivate *priv;
2972
2973   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), GST_RTSP_EINVAL);
2974   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2975   g_return_val_if_fail (message->type == GST_RTSP_MESSAGE_REQUEST ||
2976       message->type == GST_RTSP_MESSAGE_RESPONSE, GST_RTSP_EINVAL);
2977
2978   priv = client->priv;
2979
2980   if (!(ctx = gst_rtsp_context_get_current ())) {
2981     ctx = &sctx;
2982     ctx->auth = priv->auth;
2983     gst_rtsp_context_push_current (ctx);
2984   }
2985
2986   ctx->conn = priv->connection;
2987   ctx->client = client;
2988   ctx->session = session;
2989
2990   send_message (client, ctx, message, FALSE);
2991
2992   if (ctx == &sctx)
2993     gst_rtsp_context_pop_current (ctx);
2994
2995   return GST_RTSP_OK;
2996 }
2997
2998 static GstRTSPResult
2999 do_send_message (GstRTSPClient * client, GstRTSPMessage * message,
3000     gboolean close, gpointer user_data)
3001 {
3002   GstRTSPClientPrivate *priv = client->priv;
3003   GstRTSPResult ret;
3004   GTimeVal time;
3005
3006   time.tv_sec = 1;
3007   time.tv_usec = 0;
3008
3009   do {
3010     /* send the response and store the seq number so we can wait until it's
3011      * written to the client to close the connection */
3012     ret =
3013         gst_rtsp_watch_send_message (priv->watch, message,
3014         close ? &priv->close_seq : NULL);
3015     if (ret == GST_RTSP_OK)
3016       break;
3017
3018     if (ret != GST_RTSP_ENOMEM)
3019       goto error;
3020
3021     /* drop backlog */
3022     if (priv->drop_backlog)
3023       break;
3024
3025     /* queue was full, wait for more space */
3026     GST_DEBUG_OBJECT (client, "waiting for backlog");
3027     ret = gst_rtsp_watch_wait_backlog (priv->watch, &time);
3028     GST_DEBUG_OBJECT (client, "Resend due to backlog full");
3029   } while (ret != GST_RTSP_EINTR);
3030
3031   return ret;
3032
3033   /* ERRORS */
3034 error:
3035   {
3036     GST_DEBUG_OBJECT (client, "got error %d", ret);
3037     return ret;
3038   }
3039 }
3040
3041 static GstRTSPResult
3042 message_received (GstRTSPWatch * watch, GstRTSPMessage * message,
3043     gpointer user_data)
3044 {
3045   return gst_rtsp_client_handle_message (GST_RTSP_CLIENT (user_data), message);
3046 }
3047
3048 static GstRTSPResult
3049 message_sent (GstRTSPWatch * watch, guint cseq, gpointer user_data)
3050 {
3051   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3052   GstRTSPClientPrivate *priv = client->priv;
3053
3054   if (priv->close_seq && priv->close_seq == cseq) {
3055     GST_INFO ("client %p: send close message", client);
3056     priv->close_seq = 0;
3057     gst_rtsp_client_close (client);
3058   }
3059
3060   return GST_RTSP_OK;
3061 }
3062
3063 static GstRTSPResult
3064 closed (GstRTSPWatch * watch, gpointer user_data)
3065 {
3066   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3067   GstRTSPClientPrivate *priv = client->priv;
3068   const gchar *tunnelid;
3069
3070   GST_INFO ("client %p: connection closed", client);
3071
3072   if ((tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection))) {
3073     g_mutex_lock (&tunnels_lock);
3074     /* remove from tunnelids */
3075     g_hash_table_remove (tunnels, tunnelid);
3076     g_mutex_unlock (&tunnels_lock);
3077   }
3078
3079   gst_rtsp_watch_set_flushing (watch, TRUE);
3080   g_mutex_lock (&priv->watch_lock);
3081   gst_rtsp_client_set_send_func (client, NULL, NULL, NULL);
3082   g_mutex_unlock (&priv->watch_lock);
3083
3084   return GST_RTSP_OK;
3085 }
3086
3087 static GstRTSPResult
3088 error (GstRTSPWatch * watch, GstRTSPResult result, 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 ("client %p: received an error %s", client, str);
3095   g_free (str);
3096
3097   return GST_RTSP_OK;
3098 }
3099
3100 static GstRTSPResult
3101 error_full (GstRTSPWatch * watch, GstRTSPResult result,
3102     GstRTSPMessage * message, guint id, gpointer user_data)
3103 {
3104   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3105   gchar *str;
3106
3107   str = gst_rtsp_strresult (result);
3108   GST_INFO
3109       ("client %p: error when handling message %p with id %d: %s",
3110       client, message, id, str);
3111   g_free (str);
3112
3113   return GST_RTSP_OK;
3114 }
3115
3116 static gboolean
3117 remember_tunnel (GstRTSPClient * client)
3118 {
3119   GstRTSPClientPrivate *priv = client->priv;
3120   const gchar *tunnelid;
3121
3122   /* store client in the pending tunnels */
3123   tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection);
3124   if (tunnelid == NULL)
3125     goto no_tunnelid;
3126
3127   GST_INFO ("client %p: inserting tunnel session %s", client, tunnelid);
3128
3129   /* we can't have two clients connecting with the same tunnelid */
3130   g_mutex_lock (&tunnels_lock);
3131   if (g_hash_table_lookup (tunnels, tunnelid))
3132     goto tunnel_existed;
3133
3134   g_hash_table_insert (tunnels, g_strdup (tunnelid), g_object_ref (client));
3135   g_mutex_unlock (&tunnels_lock);
3136
3137   return TRUE;
3138
3139   /* ERRORS */
3140 no_tunnelid:
3141   {
3142     GST_ERROR ("client %p: no tunnelid provided", client);
3143     return FALSE;
3144   }
3145 tunnel_existed:
3146   {
3147     g_mutex_unlock (&tunnels_lock);
3148     GST_ERROR ("client %p: tunnel session %s already existed", client,
3149         tunnelid);
3150     return FALSE;
3151   }
3152 }
3153
3154 static GstRTSPResult
3155 tunnel_lost (GstRTSPWatch * watch, gpointer user_data)
3156 {
3157   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3158   GstRTSPClientPrivate *priv = client->priv;
3159
3160   GST_WARNING ("client %p: tunnel lost (connection %p)", client,
3161       priv->connection);
3162
3163   /* ignore error, it'll only be a problem when the client does a POST again */
3164   remember_tunnel (client);
3165
3166   return GST_RTSP_OK;
3167 }
3168
3169 static gboolean
3170 handle_tunnel (GstRTSPClient * client)
3171 {
3172   GstRTSPClientPrivate *priv = client->priv;
3173   GstRTSPClient *oclient;
3174   GstRTSPClientPrivate *opriv;
3175   const gchar *tunnelid;
3176
3177   tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection);
3178   if (tunnelid == NULL)
3179     goto no_tunnelid;
3180
3181   /* check for previous tunnel */
3182   g_mutex_lock (&tunnels_lock);
3183   oclient = g_hash_table_lookup (tunnels, tunnelid);
3184
3185   if (oclient == NULL) {
3186     /* no previous tunnel, remember tunnel */
3187     g_hash_table_insert (tunnels, g_strdup (tunnelid), g_object_ref (client));
3188     g_mutex_unlock (&tunnels_lock);
3189
3190     GST_INFO ("client %p: no previous tunnel found, remembering tunnel (%p)",
3191         client, priv->connection);
3192   } else {
3193     /* merge both tunnels into the first client */
3194     /* remove the old client from the table. ref before because removing it will
3195      * remove the ref to it. */
3196     g_object_ref (oclient);
3197     g_hash_table_remove (tunnels, tunnelid);
3198     g_mutex_unlock (&tunnels_lock);
3199
3200     opriv = oclient->priv;
3201
3202     g_mutex_lock (&opriv->watch_lock);
3203     if (opriv->watch == NULL)
3204       goto tunnel_closed;
3205
3206     GST_INFO ("client %p: found previous tunnel %p (old %p, new %p)", client,
3207         oclient, opriv->connection, priv->connection);
3208
3209     gst_rtsp_connection_do_tunnel (opriv->connection, priv->connection);
3210     gst_rtsp_watch_reset (priv->watch);
3211     gst_rtsp_watch_reset (opriv->watch);
3212     g_mutex_unlock (&opriv->watch_lock);
3213     g_object_unref (oclient);
3214
3215     /* the old client owns the tunnel now, the new one will be freed */
3216     g_source_destroy ((GSource *) priv->watch);
3217     priv->watch = NULL;
3218     gst_rtsp_client_set_send_func (client, NULL, NULL, NULL);
3219   }
3220
3221   return TRUE;
3222
3223   /* ERRORS */
3224 no_tunnelid:
3225   {
3226     GST_ERROR ("client %p: no tunnelid provided", client);
3227     return FALSE;
3228   }
3229 tunnel_closed:
3230   {
3231     GST_ERROR ("client %p: tunnel session %s was closed", client, tunnelid);
3232     g_mutex_unlock (&opriv->watch_lock);
3233     g_object_unref (oclient);
3234     return FALSE;
3235   }
3236 }
3237
3238 static GstRTSPStatusCode
3239 tunnel_get (GstRTSPWatch * watch, gpointer user_data)
3240 {
3241   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3242
3243   GST_INFO ("client %p: tunnel get (connection %p)", client,
3244       client->priv->connection);
3245
3246   if (!handle_tunnel (client)) {
3247     return GST_RTSP_STS_SERVICE_UNAVAILABLE;
3248   }
3249
3250   return GST_RTSP_STS_OK;
3251 }
3252
3253 static GstRTSPResult
3254 tunnel_post (GstRTSPWatch * watch, gpointer user_data)
3255 {
3256   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3257
3258   GST_INFO ("client %p: tunnel post (connection %p)", client,
3259       client->priv->connection);
3260
3261   if (!handle_tunnel (client)) {
3262     return GST_RTSP_ERROR;
3263   }
3264
3265   return GST_RTSP_OK;
3266 }
3267
3268 static GstRTSPResult
3269 tunnel_http_response (GstRTSPWatch * watch, GstRTSPMessage * request,
3270     GstRTSPMessage * response, gpointer user_data)
3271 {
3272   GstRTSPClientClass *klass;
3273
3274   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3275   klass = GST_RTSP_CLIENT_GET_CLASS (client);
3276
3277   if (klass->tunnel_http_response) {
3278     klass->tunnel_http_response (client, request, response);
3279   }
3280
3281   return GST_RTSP_OK;
3282 }
3283
3284 static GstRTSPWatchFuncs watch_funcs = {
3285   message_received,
3286   message_sent,
3287   closed,
3288   error,
3289   tunnel_get,
3290   tunnel_post,
3291   error_full,
3292   tunnel_lost,
3293   tunnel_http_response
3294 };
3295
3296 static void
3297 client_watch_notify (GstRTSPClient * client)
3298 {
3299   GstRTSPClientPrivate *priv = client->priv;
3300
3301   GST_INFO ("client %p: watch destroyed", client);
3302   priv->watch = NULL;
3303   g_main_context_unref (priv->watch_context);
3304   priv->watch_context = NULL;
3305   /* remove all sessions and so drop the extra client ref */
3306   gst_rtsp_client_session_filter (client, cleanup_session, NULL);
3307   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_CLOSED], 0, NULL);
3308   g_object_unref (client);
3309 }
3310
3311 /**
3312  * gst_rtsp_client_attach:
3313  * @client: a #GstRTSPClient
3314  * @context: (allow-none): a #GMainContext
3315  *
3316  * Attaches @client to @context. When the mainloop for @context is run, the
3317  * client will be dispatched. When @context is %NULL, the default context will be
3318  * used).
3319  *
3320  * This function should be called when the client properties and urls are fully
3321  * configured and the client is ready to start.
3322  *
3323  * Returns: the ID (greater than 0) for the source within the GMainContext.
3324  */
3325 guint
3326 gst_rtsp_client_attach (GstRTSPClient * client, GMainContext * context)
3327 {
3328   GstRTSPClientPrivate *priv;
3329   guint res;
3330
3331   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), 0);
3332   priv = client->priv;
3333   g_return_val_if_fail (priv->connection != NULL, 0);
3334   g_return_val_if_fail (priv->watch == NULL, 0);
3335
3336   /* make sure noone will free the context before the watch is destroyed */
3337   priv->watch_context = g_main_context_ref (context);
3338
3339   /* create watch for the connection and attach */
3340   priv->watch = gst_rtsp_watch_new (priv->connection, &watch_funcs,
3341       g_object_ref (client), (GDestroyNotify) client_watch_notify);
3342   gst_rtsp_client_set_send_func (client, do_send_message, priv->watch,
3343       (GDestroyNotify) gst_rtsp_watch_unref);
3344
3345   gst_rtsp_watch_set_send_backlog (priv->watch, 0, WATCH_BACKLOG_SIZE);
3346
3347   GST_INFO ("client %p: attaching to context %p", client, context);
3348   res = gst_rtsp_watch_attach (priv->watch, context);
3349
3350   return res;
3351 }
3352
3353 /**
3354  * gst_rtsp_client_session_filter:
3355  * @client: a #GstRTSPClient
3356  * @func: (scope call) (allow-none): a callback
3357  * @user_data: user data passed to @func
3358  *
3359  * Call @func for each session managed by @client. The result value of @func
3360  * determines what happens to the session. @func will be called with @client
3361  * locked so no further actions on @client can be performed from @func.
3362  *
3363  * If @func returns #GST_RTSP_FILTER_REMOVE, the session will be removed from
3364  * @client.
3365  *
3366  * If @func returns #GST_RTSP_FILTER_KEEP, the session will remain in @client.
3367  *
3368  * If @func returns #GST_RTSP_FILTER_REF, the session will remain in @client but
3369  * will also be added with an additional ref to the result #GList of this
3370  * function..
3371  *
3372  * When @func is %NULL, #GST_RTSP_FILTER_REF will be assumed for each session.
3373  *
3374  * Returns: (element-type GstRTSPSession) (transfer full): a #GList with all
3375  * sessions for which @func returned #GST_RTSP_FILTER_REF. After usage, each
3376  * element in the #GList should be unreffed before the list is freed.
3377  */
3378 GList *
3379 gst_rtsp_client_session_filter (GstRTSPClient * client,
3380     GstRTSPClientSessionFilterFunc func, gpointer user_data)
3381 {
3382   GstRTSPClientPrivate *priv;
3383   GList *result, *walk, *next;
3384   GHashTable *visited;
3385   guint cookie;
3386
3387   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
3388
3389   priv = client->priv;
3390
3391   result = NULL;
3392   if (func)
3393     visited = g_hash_table_new_full (NULL, NULL, g_object_unref, NULL);
3394
3395   g_mutex_lock (&priv->lock);
3396 restart:
3397   cookie = priv->sessions_cookie;
3398   for (walk = priv->sessions; walk; walk = next) {
3399     GstRTSPSession *sess = walk->data;
3400     GstRTSPFilterResult res;
3401     gboolean changed;
3402
3403     next = g_list_next (walk);
3404
3405     if (func) {
3406       /* only visit each session once */
3407       if (g_hash_table_contains (visited, sess))
3408         continue;
3409
3410       g_hash_table_add (visited, g_object_ref (sess));
3411       g_mutex_unlock (&priv->lock);
3412
3413       res = func (client, sess, user_data);
3414
3415       g_mutex_lock (&priv->lock);
3416     } else
3417       res = GST_RTSP_FILTER_REF;
3418
3419     changed = (cookie != priv->sessions_cookie);
3420
3421     switch (res) {
3422       case GST_RTSP_FILTER_REMOVE:
3423         /* stop watching the session and pretend it went away, if the list was
3424          * changed, we can't use the current list position, try to see if we
3425          * still have the session */
3426         client_unwatch_session (client, sess, changed ? NULL : walk);
3427         cookie = priv->sessions_cookie;
3428         break;
3429       case GST_RTSP_FILTER_REF:
3430         result = g_list_prepend (result, g_object_ref (sess));
3431         break;
3432       case GST_RTSP_FILTER_KEEP:
3433       default:
3434         break;
3435     }
3436     if (changed)
3437       goto restart;
3438   }
3439   g_mutex_unlock (&priv->lock);
3440
3441   if (func)
3442     g_hash_table_unref (visited);
3443
3444   return result;
3445 }