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