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