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