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