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