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