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