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