client: Do not read beyond end of path string
[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   if (path[matched] == '\0')
1429     goto control_not_found;
1430
1431   /* path is what matched. We can modify the parsed uri in place */
1432   path[matched] = '\0';
1433   /* control is remainder */
1434   control = &path[matched + 1];
1435
1436   /* find the stream now using the control part */
1437   stream = gst_rtsp_media_find_stream (media, control);
1438   if (stream == NULL)
1439     goto stream_not_found;
1440
1441   /* now we have a uri identifying a valid media and stream */
1442   ctx->stream = stream;
1443   ctx->media = media;
1444
1445   if (session == NULL) {
1446     /* create a session if this fails we probably reached our session limit or
1447      * something. */
1448     if (!(session = gst_rtsp_session_pool_create (priv->session_pool)))
1449       goto service_unavailable;
1450
1451     /* make sure this client is closed when the session is closed */
1452     client_watch_session (client, session);
1453
1454     /* signal new session */
1455     g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_NEW_SESSION], 0,
1456         session);
1457
1458     ctx->session = session;
1459   }
1460
1461   if (sessmedia == NULL) {
1462     /* manage the media in our session now, if not done already  */
1463     sessmedia = gst_rtsp_session_manage_media (session, path, media);
1464     /* if we stil have no media, error */
1465     if (sessmedia == NULL)
1466       goto sessmedia_unavailable;
1467   } else {
1468     g_object_unref (media);
1469   }
1470
1471   ctx->sessmedia = sessmedia;
1472
1473   /* set blocksize on this stream */
1474   if (!handle_blocksize (media, stream, ctx->request))
1475     goto invalid_blocksize;
1476
1477   gst_rtsp_transport_new (&ct);
1478
1479   /* our supported transports */
1480   supported = gst_rtsp_stream_get_protocols (stream);
1481
1482   /* parse and find a usable supported transport */
1483   if (!parse_transport (transport, supported, ct))
1484     goto unsupported_transports;
1485
1486   /* update the client transport */
1487   klass = GST_RTSP_CLIENT_GET_CLASS (client);
1488   if (!klass->configure_client_transport (client, ctx, ct))
1489     goto unsupported_client_transport;
1490
1491   /* set in the session media transport */
1492   trans = gst_rtsp_session_media_set_transport (sessmedia, stream, ct);
1493
1494   /* configure keepalive for this transport */
1495   gst_rtsp_stream_transport_set_keepalive (trans,
1496       (GstRTSPKeepAliveFunc) do_keepalive, session, NULL);
1497
1498   /* create and serialize the server transport */
1499   st = make_server_transport (client, ctx, ct);
1500   trans_str = gst_rtsp_transport_as_text (st);
1501   gst_rtsp_transport_free (st);
1502
1503   /* construct the response now */
1504   code = GST_RTSP_STS_OK;
1505   gst_rtsp_message_init_response (ctx->response, code,
1506       gst_rtsp_status_as_text (code), ctx->request);
1507
1508   gst_rtsp_message_add_header (ctx->response, GST_RTSP_HDR_TRANSPORT,
1509       trans_str);
1510   g_free (trans_str);
1511
1512   send_message (client, session, ctx->response, FALSE);
1513
1514   /* update the state */
1515   rtspstate = gst_rtsp_session_media_get_rtsp_state (sessmedia);
1516   switch (rtspstate) {
1517     case GST_RTSP_STATE_PLAYING:
1518     case GST_RTSP_STATE_RECORDING:
1519     case GST_RTSP_STATE_READY:
1520       /* no state change */
1521       break;
1522     default:
1523       gst_rtsp_session_media_set_rtsp_state (sessmedia, GST_RTSP_STATE_READY);
1524       break;
1525   }
1526   g_object_unref (session);
1527
1528   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_SETUP_REQUEST], 0, ctx);
1529
1530   return TRUE;
1531
1532   /* ERRORS */
1533 no_uri:
1534   {
1535     GST_ERROR ("client %p: no uri", client);
1536     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
1537     return FALSE;
1538   }
1539 no_transport:
1540   {
1541     GST_ERROR ("client %p: no transport", client);
1542     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, ctx);
1543     return FALSE;
1544   }
1545 no_pool:
1546   {
1547     GST_ERROR ("client %p: no session pool configured", client);
1548     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
1549     return FALSE;
1550   }
1551 media_not_found:
1552   {
1553     GST_ERROR ("client %p: media '%s' not found", client, path);
1554     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
1555     return FALSE;
1556   }
1557 control_not_found:
1558   {
1559     GST_ERROR ("client %p: no control in path '%s'", client, path);
1560     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
1561     g_object_unref (media);
1562     return FALSE;
1563   }
1564 stream_not_found:
1565   {
1566     GST_ERROR ("client %p: stream '%s' not found", client, control);
1567     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
1568     g_object_unref (media);
1569     return FALSE;
1570   }
1571 service_unavailable:
1572   {
1573     GST_ERROR ("client %p: can't create session", client);
1574     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, ctx);
1575     g_object_unref (media);
1576     return FALSE;
1577   }
1578 sessmedia_unavailable:
1579   {
1580     GST_ERROR ("client %p: can't create session media", client);
1581     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, ctx);
1582     g_object_unref (media);
1583     g_object_unref (session);
1584     return FALSE;
1585   }
1586 invalid_blocksize:
1587   {
1588     GST_ERROR ("client %p: invalid blocksize", client);
1589     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
1590     g_object_unref (session);
1591     return FALSE;
1592   }
1593 unsupported_transports:
1594   {
1595     GST_ERROR ("client %p: unsupported transports", client);
1596     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, ctx);
1597     gst_rtsp_transport_free (ct);
1598     g_object_unref (session);
1599     return FALSE;
1600   }
1601 unsupported_client_transport:
1602   {
1603     GST_ERROR ("client %p: unsupported client transport", client);
1604     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, ctx);
1605     gst_rtsp_transport_free (ct);
1606     g_object_unref (session);
1607     return FALSE;
1608   }
1609 }
1610
1611 static GstSDPMessage *
1612 create_sdp (GstRTSPClient * client, GstRTSPMedia * media)
1613 {
1614   GstRTSPClientPrivate *priv = client->priv;
1615   GstSDPMessage *sdp;
1616   GstSDPInfo info;
1617   const gchar *proto;
1618
1619   gst_sdp_message_new (&sdp);
1620
1621   /* some standard things first */
1622   gst_sdp_message_set_version (sdp, "0");
1623
1624   if (priv->is_ipv6)
1625     proto = "IP6";
1626   else
1627     proto = "IP4";
1628
1629   gst_sdp_message_set_origin (sdp, "-", "1188340656180883", "1", "IN", proto,
1630       priv->server_ip);
1631
1632   gst_sdp_message_set_session_name (sdp, "Session streamed with GStreamer");
1633   gst_sdp_message_set_information (sdp, "rtsp-server");
1634   gst_sdp_message_add_time (sdp, "0", "0", NULL);
1635   gst_sdp_message_add_attribute (sdp, "tool", "GStreamer");
1636   gst_sdp_message_add_attribute (sdp, "type", "broadcast");
1637   gst_sdp_message_add_attribute (sdp, "control", "*");
1638
1639   info.is_ipv6 = priv->is_ipv6;
1640   info.server_ip = priv->server_ip;
1641
1642   /* create an SDP for the media object */
1643   if (!gst_rtsp_sdp_from_media (sdp, &info, media))
1644     goto no_sdp;
1645
1646   return sdp;
1647
1648   /* ERRORS */
1649 no_sdp:
1650   {
1651     GST_ERROR ("client %p: could not create SDP", client);
1652     gst_sdp_message_free (sdp);
1653     return NULL;
1654   }
1655 }
1656
1657 /* for the describe we must generate an SDP */
1658 static gboolean
1659 handle_describe_request (GstRTSPClient * client, GstRTSPContext * ctx)
1660 {
1661   GstRTSPClientPrivate *priv = client->priv;
1662   GstRTSPResult res;
1663   GstSDPMessage *sdp;
1664   guint i;
1665   gchar *path, *str;
1666   GstRTSPMedia *media;
1667   GstRTSPClientClass *klass;
1668
1669   klass = GST_RTSP_CLIENT_GET_CLASS (client);
1670
1671   if (!ctx->uri)
1672     goto no_uri;
1673
1674   /* check what kind of format is accepted, we don't really do anything with it
1675    * and always return SDP for now. */
1676   for (i = 0; i++;) {
1677     gchar *accept;
1678
1679     res =
1680         gst_rtsp_message_get_header (ctx->request, GST_RTSP_HDR_ACCEPT,
1681         &accept, i);
1682     if (res == GST_RTSP_ENOTIMPL)
1683       break;
1684
1685     if (g_ascii_strcasecmp (accept, "application/sdp") == 0)
1686       break;
1687   }
1688
1689   if (!priv->mount_points)
1690     goto no_mount_points;
1691
1692   if (!(path = gst_rtsp_mount_points_make_path (priv->mount_points, ctx->uri)))
1693     goto no_path;
1694
1695   /* find the media object for the uri */
1696   if (!(media = find_media (client, ctx, path, NULL)))
1697     goto no_media;
1698
1699   /* create an SDP for the media object on this client */
1700   if (!(sdp = klass->create_sdp (client, media)))
1701     goto no_sdp;
1702
1703   g_object_unref (media);
1704
1705   gst_rtsp_message_init_response (ctx->response, GST_RTSP_STS_OK,
1706       gst_rtsp_status_as_text (GST_RTSP_STS_OK), ctx->request);
1707
1708   gst_rtsp_message_add_header (ctx->response, GST_RTSP_HDR_CONTENT_TYPE,
1709       "application/sdp");
1710
1711   /* content base for some clients that might screw up creating the setup uri */
1712   str = make_base_url (client, ctx->uri, path);
1713   g_free (path);
1714
1715   GST_INFO ("adding content-base: %s", str);
1716   gst_rtsp_message_take_header (ctx->response, GST_RTSP_HDR_CONTENT_BASE, str);
1717
1718   /* add SDP to the response body */
1719   str = gst_sdp_message_as_text (sdp);
1720   gst_rtsp_message_take_body (ctx->response, (guint8 *) str, strlen (str));
1721   gst_sdp_message_free (sdp);
1722
1723   send_message (client, ctx->session, ctx->response, FALSE);
1724
1725   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_DESCRIBE_REQUEST],
1726       0, ctx);
1727
1728   return TRUE;
1729
1730   /* ERRORS */
1731 no_uri:
1732   {
1733     GST_ERROR ("client %p: no uri", client);
1734     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
1735     return FALSE;
1736   }
1737 no_mount_points:
1738   {
1739     GST_ERROR ("client %p: no mount points configured", client);
1740     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
1741     return FALSE;
1742   }
1743 no_path:
1744   {
1745     GST_ERROR ("client %p: can't find path for url", client);
1746     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
1747     return FALSE;
1748   }
1749 no_media:
1750   {
1751     GST_ERROR ("client %p: no media", client);
1752     g_free (path);
1753     /* error reply is already sent */
1754     return FALSE;
1755   }
1756 no_sdp:
1757   {
1758     GST_ERROR ("client %p: can't create SDP", client);
1759     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, ctx);
1760     g_free (path);
1761     g_object_unref (media);
1762     return FALSE;
1763   }
1764 }
1765
1766 static gboolean
1767 handle_options_request (GstRTSPClient * client, GstRTSPContext * ctx)
1768 {
1769   GstRTSPMethod options;
1770   gchar *str;
1771
1772   options = GST_RTSP_DESCRIBE |
1773       GST_RTSP_OPTIONS |
1774       GST_RTSP_PAUSE |
1775       GST_RTSP_PLAY |
1776       GST_RTSP_SETUP |
1777       GST_RTSP_GET_PARAMETER | GST_RTSP_SET_PARAMETER | GST_RTSP_TEARDOWN;
1778
1779   str = gst_rtsp_options_as_text (options);
1780
1781   gst_rtsp_message_init_response (ctx->response, GST_RTSP_STS_OK,
1782       gst_rtsp_status_as_text (GST_RTSP_STS_OK), ctx->request);
1783
1784   gst_rtsp_message_add_header (ctx->response, GST_RTSP_HDR_PUBLIC, str);
1785   g_free (str);
1786
1787   send_message (client, ctx->session, ctx->response, FALSE);
1788
1789   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_OPTIONS_REQUEST],
1790       0, ctx);
1791
1792   return TRUE;
1793 }
1794
1795 /* remove duplicate and trailing '/' */
1796 static void
1797 sanitize_uri (GstRTSPUrl * uri)
1798 {
1799   gint i, len;
1800   gchar *s, *d;
1801   gboolean have_slash, prev_slash;
1802
1803   s = d = uri->abspath;
1804   len = strlen (uri->abspath);
1805
1806   prev_slash = FALSE;
1807
1808   for (i = 0; i < len; i++) {
1809     have_slash = s[i] == '/';
1810     *d = s[i];
1811     if (!have_slash || !prev_slash)
1812       d++;
1813     prev_slash = have_slash;
1814   }
1815   len = d - uri->abspath;
1816   /* don't remove the first slash if that's the only thing left */
1817   if (len > 1 && *(d - 1) == '/')
1818     d--;
1819   *d = '\0';
1820 }
1821
1822 static void
1823 client_session_finalized (GstRTSPClient * client, GstRTSPSession * session)
1824 {
1825   GstRTSPClientPrivate *priv = client->priv;
1826
1827   GST_INFO ("client %p: session %p finished", client, session);
1828
1829   /* unlink all media managed in this session */
1830   client_unlink_session (client, session);
1831
1832   /* remove the session */
1833   if (!(priv->sessions = g_list_remove (priv->sessions, session))) {
1834     GST_INFO ("client %p: all sessions finalized, close the connection",
1835         client);
1836     close_connection (client);
1837   }
1838 }
1839
1840 static void
1841 handle_request (GstRTSPClient * client, GstRTSPMessage * request)
1842 {
1843   GstRTSPClientPrivate *priv = client->priv;
1844   GstRTSPMethod method;
1845   const gchar *uristr;
1846   GstRTSPUrl *uri = NULL;
1847   GstRTSPVersion version;
1848   GstRTSPResult res;
1849   GstRTSPSession *session = NULL;
1850   GstRTSPContext sctx = { NULL }, *ctx;
1851   GstRTSPMessage response = { 0 };
1852   gchar *sessid;
1853
1854   if (!(ctx = gst_rtsp_context_get_current ())) {
1855     ctx = &sctx;
1856     ctx->auth = priv->auth;
1857     gst_rtsp_context_push_current (ctx);
1858   }
1859
1860   ctx->conn = priv->connection;
1861   ctx->client = client;
1862   ctx->request = request;
1863   ctx->response = &response;
1864
1865   if (gst_debug_category_get_threshold (rtsp_client_debug) >= GST_LEVEL_LOG) {
1866     gst_rtsp_message_dump (request);
1867   }
1868
1869   GST_INFO ("client %p: received a request", client);
1870
1871   gst_rtsp_message_parse_request (request, &method, &uristr, &version);
1872
1873   /* we can only handle 1.0 requests */
1874   if (version != GST_RTSP_VERSION_1_0)
1875     goto not_supported;
1876
1877   ctx->method = method;
1878
1879   /* we always try to parse the url first */
1880   if (strcmp (uristr, "*") == 0) {
1881     /* special case where we have * as uri, keep uri = NULL */
1882   } else if (gst_rtsp_url_parse (uristr, &uri) != GST_RTSP_OK)
1883     goto bad_request;
1884
1885   /* get the session if there is any */
1886   res = gst_rtsp_message_get_header (request, GST_RTSP_HDR_SESSION, &sessid, 0);
1887   if (res == GST_RTSP_OK) {
1888     if (priv->session_pool == NULL)
1889       goto no_pool;
1890
1891     /* we had a session in the request, find it again */
1892     if (!(session = gst_rtsp_session_pool_find (priv->session_pool, sessid)))
1893       goto session_not_found;
1894
1895     /* we add the session to the client list of watched sessions. When a session
1896      * disappears because it times out, we will be notified. If all sessions are
1897      * gone, we will close the connection */
1898     client_watch_session (client, session);
1899   }
1900
1901   /* sanitize the uri */
1902   if (uri)
1903     sanitize_uri (uri);
1904   ctx->uri = uri;
1905   ctx->session = session;
1906
1907   if (!gst_rtsp_auth_check (GST_RTSP_AUTH_CHECK_URL))
1908     goto not_authorized;
1909
1910   /* now see what is asked and dispatch to a dedicated handler */
1911   switch (method) {
1912     case GST_RTSP_OPTIONS:
1913       handle_options_request (client, ctx);
1914       break;
1915     case GST_RTSP_DESCRIBE:
1916       handle_describe_request (client, ctx);
1917       break;
1918     case GST_RTSP_SETUP:
1919       handle_setup_request (client, ctx);
1920       break;
1921     case GST_RTSP_PLAY:
1922       handle_play_request (client, ctx);
1923       break;
1924     case GST_RTSP_PAUSE:
1925       handle_pause_request (client, ctx);
1926       break;
1927     case GST_RTSP_TEARDOWN:
1928       handle_teardown_request (client, ctx);
1929       break;
1930     case GST_RTSP_SET_PARAMETER:
1931       handle_set_param_request (client, ctx);
1932       break;
1933     case GST_RTSP_GET_PARAMETER:
1934       handle_get_param_request (client, ctx);
1935       break;
1936     case GST_RTSP_ANNOUNCE:
1937     case GST_RTSP_RECORD:
1938     case GST_RTSP_REDIRECT:
1939       goto not_implemented;
1940     case GST_RTSP_INVALID:
1941     default:
1942       goto bad_request;
1943   }
1944
1945 done:
1946   if (ctx == &sctx)
1947     gst_rtsp_context_pop_current (ctx);
1948   if (session)
1949     g_object_unref (session);
1950   if (uri)
1951     gst_rtsp_url_free (uri);
1952   return;
1953
1954   /* ERRORS */
1955 not_supported:
1956   {
1957     GST_ERROR ("client %p: version %d not supported", client, version);
1958     send_generic_response (client, GST_RTSP_STS_RTSP_VERSION_NOT_SUPPORTED,
1959         ctx);
1960     goto done;
1961   }
1962 bad_request:
1963   {
1964     GST_ERROR ("client %p: bad request", client);
1965     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
1966     goto done;
1967   }
1968 no_pool:
1969   {
1970     GST_ERROR ("client %p: no pool configured", client);
1971     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
1972     goto done;
1973   }
1974 session_not_found:
1975   {
1976     GST_ERROR ("client %p: session not found", client);
1977     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
1978     goto done;
1979   }
1980 not_authorized:
1981   {
1982     GST_ERROR ("client %p: not allowed", client);
1983     goto done;
1984   }
1985 not_implemented:
1986   {
1987     GST_ERROR ("client %p: method %d not implemented", client, method);
1988     send_generic_response (client, GST_RTSP_STS_NOT_IMPLEMENTED, ctx);
1989     goto done;
1990   }
1991 }
1992
1993
1994 static void
1995 handle_response (GstRTSPClient * client, GstRTSPMessage * response)
1996 {
1997   GstRTSPClientPrivate *priv = client->priv;
1998   GstRTSPResult res;
1999   GstRTSPSession *session = NULL;
2000   GstRTSPContext sctx = { NULL }, *ctx;
2001   gchar *sessid;
2002
2003   if (!(ctx = gst_rtsp_context_get_current ())) {
2004     ctx = &sctx;
2005     ctx->auth = priv->auth;
2006     gst_rtsp_context_push_current (ctx);
2007   }
2008
2009   ctx->conn = priv->connection;
2010   ctx->client = client;
2011   ctx->request = NULL;
2012   ctx->uri = NULL;
2013   ctx->method = GST_RTSP_INVALID;
2014   ctx->response = response;
2015
2016   if (gst_debug_category_get_threshold (rtsp_client_debug) >= GST_LEVEL_LOG) {
2017     gst_rtsp_message_dump (response);
2018   }
2019
2020   GST_INFO ("client %p: received a response", client);
2021
2022   /* get the session if there is any */
2023   res =
2024       gst_rtsp_message_get_header (response, GST_RTSP_HDR_SESSION, &sessid, 0);
2025   if (res == GST_RTSP_OK) {
2026     if (priv->session_pool == NULL)
2027       goto no_pool;
2028
2029     /* we had a session in the request, find it again */
2030     if (!(session = gst_rtsp_session_pool_find (priv->session_pool, sessid)))
2031       goto session_not_found;
2032
2033     /* we add the session to the client list of watched sessions. When a session
2034      * disappears because it times out, we will be notified. If all sessions are
2035      * gone, we will close the connection */
2036     client_watch_session (client, session);
2037   }
2038
2039   ctx->session = session;
2040
2041   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_HANDLE_RESPONSE],
2042       0, ctx);
2043
2044 done:
2045   if (ctx == &sctx)
2046     gst_rtsp_context_pop_current (ctx);
2047   if (session)
2048     g_object_unref (session);
2049   return;
2050
2051 no_pool:
2052   {
2053     GST_ERROR ("client %p: no pool configured", client);
2054     goto done;
2055   }
2056 session_not_found:
2057   {
2058     GST_ERROR ("client %p: session not found", client);
2059     goto done;
2060   }
2061 }
2062
2063 static void
2064 handle_data (GstRTSPClient * client, GstRTSPMessage * message)
2065 {
2066   GstRTSPClientPrivate *priv = client->priv;
2067   GstRTSPResult res;
2068   guint8 channel;
2069   GList *walk;
2070   guint8 *data;
2071   guint size;
2072   GstBuffer *buffer;
2073   gboolean handled;
2074
2075   /* find the stream for this message */
2076   res = gst_rtsp_message_parse_data (message, &channel);
2077   if (res != GST_RTSP_OK)
2078     return;
2079
2080   gst_rtsp_message_steal_body (message, &data, &size);
2081
2082   buffer = gst_buffer_new_wrapped (data, size);
2083
2084   handled = FALSE;
2085   for (walk = priv->transports; walk; walk = g_list_next (walk)) {
2086     GstRTSPStreamTransport *trans;
2087     GstRTSPStream *stream;
2088     const GstRTSPTransport *tr;
2089
2090     trans = walk->data;
2091
2092     tr = gst_rtsp_stream_transport_get_transport (trans);
2093     stream = gst_rtsp_stream_transport_get_stream (trans);
2094
2095     /* check for TCP transport */
2096     if (tr->lower_transport == GST_RTSP_LOWER_TRANS_TCP) {
2097       /* dispatch to the stream based on the channel number */
2098       if (tr->interleaved.min == channel) {
2099         gst_rtsp_stream_recv_rtp (stream, buffer);
2100         handled = TRUE;
2101         break;
2102       } else if (tr->interleaved.max == channel) {
2103         gst_rtsp_stream_recv_rtcp (stream, buffer);
2104         handled = TRUE;
2105         break;
2106       }
2107     }
2108   }
2109   if (!handled)
2110     gst_buffer_unref (buffer);
2111 }
2112
2113 /**
2114  * gst_rtsp_client_set_session_pool:
2115  * @client: a #GstRTSPClient
2116  * @pool: a #GstRTSPSessionPool
2117  *
2118  * Set @pool as the sessionpool for @client which it will use to find
2119  * or allocate sessions. the sessionpool is usually inherited from the server
2120  * that created the client but can be overridden later.
2121  */
2122 void
2123 gst_rtsp_client_set_session_pool (GstRTSPClient * client,
2124     GstRTSPSessionPool * pool)
2125 {
2126   GstRTSPSessionPool *old;
2127   GstRTSPClientPrivate *priv;
2128
2129   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2130
2131   priv = client->priv;
2132
2133   if (pool)
2134     g_object_ref (pool);
2135
2136   g_mutex_lock (&priv->lock);
2137   old = priv->session_pool;
2138   priv->session_pool = pool;
2139   g_mutex_unlock (&priv->lock);
2140
2141   if (old)
2142     g_object_unref (old);
2143 }
2144
2145 /**
2146  * gst_rtsp_client_get_session_pool:
2147  * @client: a #GstRTSPClient
2148  *
2149  * Get the #GstRTSPSessionPool object that @client uses to manage its sessions.
2150  *
2151  * Returns: (transfer full): a #GstRTSPSessionPool, unref after usage.
2152  */
2153 GstRTSPSessionPool *
2154 gst_rtsp_client_get_session_pool (GstRTSPClient * client)
2155 {
2156   GstRTSPClientPrivate *priv;
2157   GstRTSPSessionPool *result;
2158
2159   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2160
2161   priv = client->priv;
2162
2163   g_mutex_lock (&priv->lock);
2164   if ((result = priv->session_pool))
2165     g_object_ref (result);
2166   g_mutex_unlock (&priv->lock);
2167
2168   return result;
2169 }
2170
2171 /**
2172  * gst_rtsp_client_set_mount_points:
2173  * @client: a #GstRTSPClient
2174  * @mounts: a #GstRTSPMountPoints
2175  *
2176  * Set @mounts as the mount points for @client which it will use to map urls
2177  * to media streams. These mount points are usually inherited from the server that
2178  * created the client but can be overriden later.
2179  */
2180 void
2181 gst_rtsp_client_set_mount_points (GstRTSPClient * client,
2182     GstRTSPMountPoints * mounts)
2183 {
2184   GstRTSPClientPrivate *priv;
2185   GstRTSPMountPoints *old;
2186
2187   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2188
2189   priv = client->priv;
2190
2191   if (mounts)
2192     g_object_ref (mounts);
2193
2194   g_mutex_lock (&priv->lock);
2195   old = priv->mount_points;
2196   priv->mount_points = mounts;
2197   g_mutex_unlock (&priv->lock);
2198
2199   if (old)
2200     g_object_unref (old);
2201 }
2202
2203 /**
2204  * gst_rtsp_client_get_mount_points:
2205  * @client: a #GstRTSPClient
2206  *
2207  * Get the #GstRTSPMountPoints object that @client uses to manage its sessions.
2208  *
2209  * Returns: (transfer full): a #GstRTSPMountPoints, unref after usage.
2210  */
2211 GstRTSPMountPoints *
2212 gst_rtsp_client_get_mount_points (GstRTSPClient * client)
2213 {
2214   GstRTSPClientPrivate *priv;
2215   GstRTSPMountPoints *result;
2216
2217   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2218
2219   priv = client->priv;
2220
2221   g_mutex_lock (&priv->lock);
2222   if ((result = priv->mount_points))
2223     g_object_ref (result);
2224   g_mutex_unlock (&priv->lock);
2225
2226   return result;
2227 }
2228
2229 /**
2230  * gst_rtsp_client_set_auth:
2231  * @client: a #GstRTSPClient
2232  * @auth: a #GstRTSPAuth
2233  *
2234  * configure @auth to be used as the authentication manager of @client.
2235  */
2236 void
2237 gst_rtsp_client_set_auth (GstRTSPClient * client, GstRTSPAuth * auth)
2238 {
2239   GstRTSPClientPrivate *priv;
2240   GstRTSPAuth *old;
2241
2242   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2243
2244   priv = client->priv;
2245
2246   if (auth)
2247     g_object_ref (auth);
2248
2249   g_mutex_lock (&priv->lock);
2250   old = priv->auth;
2251   priv->auth = auth;
2252   g_mutex_unlock (&priv->lock);
2253
2254   if (old)
2255     g_object_unref (old);
2256 }
2257
2258
2259 /**
2260  * gst_rtsp_client_get_auth:
2261  * @client: a #GstRTSPClient
2262  *
2263  * Get the #GstRTSPAuth used as the authentication manager of @client.
2264  *
2265  * Returns: (transfer full): the #GstRTSPAuth of @client. g_object_unref() after
2266  * usage.
2267  */
2268 GstRTSPAuth *
2269 gst_rtsp_client_get_auth (GstRTSPClient * client)
2270 {
2271   GstRTSPClientPrivate *priv;
2272   GstRTSPAuth *result;
2273
2274   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2275
2276   priv = client->priv;
2277
2278   g_mutex_lock (&priv->lock);
2279   if ((result = priv->auth))
2280     g_object_ref (result);
2281   g_mutex_unlock (&priv->lock);
2282
2283   return result;
2284 }
2285
2286 /**
2287  * gst_rtsp_client_set_thread_pool:
2288  * @client: a #GstRTSPClient
2289  * @pool: a #GstRTSPThreadPool
2290  *
2291  * configure @pool to be used as the thread pool of @client.
2292  */
2293 void
2294 gst_rtsp_client_set_thread_pool (GstRTSPClient * client,
2295     GstRTSPThreadPool * pool)
2296 {
2297   GstRTSPClientPrivate *priv;
2298   GstRTSPThreadPool *old;
2299
2300   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2301
2302   priv = client->priv;
2303
2304   if (pool)
2305     g_object_ref (pool);
2306
2307   g_mutex_lock (&priv->lock);
2308   old = priv->thread_pool;
2309   priv->thread_pool = pool;
2310   g_mutex_unlock (&priv->lock);
2311
2312   if (old)
2313     g_object_unref (old);
2314 }
2315
2316 /**
2317  * gst_rtsp_client_get_thread_pool:
2318  * @client: a #GstRTSPClient
2319  *
2320  * Get the #GstRTSPThreadPool used as the thread pool of @client.
2321  *
2322  * Returns: (transfer full): the #GstRTSPThreadPool of @client. g_object_unref() after
2323  * usage.
2324  */
2325 GstRTSPThreadPool *
2326 gst_rtsp_client_get_thread_pool (GstRTSPClient * client)
2327 {
2328   GstRTSPClientPrivate *priv;
2329   GstRTSPThreadPool *result;
2330
2331   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2332
2333   priv = client->priv;
2334
2335   g_mutex_lock (&priv->lock);
2336   if ((result = priv->thread_pool))
2337     g_object_ref (result);
2338   g_mutex_unlock (&priv->lock);
2339
2340   return result;
2341 }
2342
2343 /**
2344  * gst_rtsp_client_set_connection:
2345  * @client: a #GstRTSPClient
2346  * @conn: (transfer full): a #GstRTSPConnection
2347  *
2348  * Set the #GstRTSPConnection of @client. This function takes ownership of
2349  * @conn.
2350  *
2351  * Returns: %TRUE on success.
2352  */
2353 gboolean
2354 gst_rtsp_client_set_connection (GstRTSPClient * client,
2355     GstRTSPConnection * conn)
2356 {
2357   GstRTSPClientPrivate *priv;
2358   GSocket *read_socket;
2359   GSocketAddress *address;
2360   GstRTSPUrl *url;
2361   GError *error = NULL;
2362
2363   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), FALSE);
2364   g_return_val_if_fail (conn != NULL, FALSE);
2365
2366   priv = client->priv;
2367
2368   read_socket = gst_rtsp_connection_get_read_socket (conn);
2369
2370   if (!(address = g_socket_get_local_address (read_socket, &error)))
2371     goto no_address;
2372
2373   g_free (priv->server_ip);
2374   /* keep the original ip that the client connected to */
2375   if (G_IS_INET_SOCKET_ADDRESS (address)) {
2376     GInetAddress *iaddr;
2377
2378     iaddr = g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (address));
2379
2380     /* socket might be ipv6 but adress still ipv4 */
2381     priv->is_ipv6 = g_inet_address_get_family (iaddr) == G_SOCKET_FAMILY_IPV6;
2382     priv->server_ip = g_inet_address_to_string (iaddr);
2383     g_object_unref (address);
2384   } else {
2385     priv->is_ipv6 = g_socket_get_family (read_socket) == G_SOCKET_FAMILY_IPV6;
2386     priv->server_ip = g_strdup ("unknown");
2387   }
2388
2389   GST_INFO ("client %p connected to server ip %s, ipv6 = %d", client,
2390       priv->server_ip, priv->is_ipv6);
2391
2392   url = gst_rtsp_connection_get_url (conn);
2393   GST_INFO ("added new client %p ip %s:%d", client, url->host, url->port);
2394
2395   priv->connection = conn;
2396
2397   return TRUE;
2398
2399   /* ERRORS */
2400 no_address:
2401   {
2402     GST_ERROR ("could not get local address %s", error->message);
2403     g_error_free (error);
2404     return FALSE;
2405   }
2406 }
2407
2408 /**
2409  * gst_rtsp_client_get_connection:
2410  * @client: a #GstRTSPClient
2411  *
2412  * Get the #GstRTSPConnection of @client.
2413  *
2414  * Returns: (transfer none): the #GstRTSPConnection of @client.
2415  * The connection object returned remains valid until the client is freed.
2416  */
2417 GstRTSPConnection *
2418 gst_rtsp_client_get_connection (GstRTSPClient * client)
2419 {
2420   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2421
2422   return client->priv->connection;
2423 }
2424
2425 /**
2426  * gst_rtsp_client_set_send_func:
2427  * @client: a #GstRTSPClient
2428  * @func: a #GstRTSPClientSendFunc
2429  * @user_data: user data passed to @func
2430  * @notify: called when @user_data is no longer in use
2431  *
2432  * Set @func as the callback that will be called when a new message needs to be
2433  * sent to the client. @user_data is passed to @func and @notify is called when
2434  * @user_data is no longer in use.
2435  *
2436  * By default, the client will send the messages on the #GstRTSPConnection that
2437  * was configured with gst_rtsp_client_attach() was called.
2438  */
2439 void
2440 gst_rtsp_client_set_send_func (GstRTSPClient * client,
2441     GstRTSPClientSendFunc func, gpointer user_data, GDestroyNotify notify)
2442 {
2443   GstRTSPClientPrivate *priv;
2444   GDestroyNotify old_notify;
2445   gpointer old_data;
2446
2447   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2448
2449   priv = client->priv;
2450
2451   g_mutex_lock (&priv->send_lock);
2452   priv->send_func = func;
2453   old_notify = priv->send_notify;
2454   old_data = priv->send_data;
2455   priv->send_notify = notify;
2456   priv->send_data = user_data;
2457   g_mutex_unlock (&priv->send_lock);
2458
2459   if (old_notify)
2460     old_notify (old_data);
2461 }
2462
2463 /**
2464  * gst_rtsp_client_handle_message:
2465  * @client: a #GstRTSPClient
2466  * @message: an #GstRTSPMessage
2467  *
2468  * Let the client handle @message.
2469  *
2470  * Returns: a #GstRTSPResult.
2471  */
2472 GstRTSPResult
2473 gst_rtsp_client_handle_message (GstRTSPClient * client,
2474     GstRTSPMessage * message)
2475 {
2476   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), GST_RTSP_EINVAL);
2477   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2478
2479   switch (message->type) {
2480     case GST_RTSP_MESSAGE_REQUEST:
2481       handle_request (client, message);
2482       break;
2483     case GST_RTSP_MESSAGE_RESPONSE:
2484       handle_response (client, message);
2485       break;
2486     case GST_RTSP_MESSAGE_DATA:
2487       handle_data (client, message);
2488       break;
2489     default:
2490       break;
2491   }
2492   return GST_RTSP_OK;
2493 }
2494
2495 /**
2496  * gst_rtsp_client_send_message:
2497  * @client: a #GstRTSPClient
2498  * @session: a #GstRTSPSession to send the message to or %NULL
2499  * @message: The #GstRTSPMessage to send
2500  *
2501  * Send a message message to the remote end. @message must be a
2502  * #GST_RTSP_MESSAGE_REQUEST or a #GST_RTSP_MESSAGE_RESPONSE.
2503  */
2504 GstRTSPResult
2505 gst_rtsp_client_send_message (GstRTSPClient * client, GstRTSPSession * session,
2506     GstRTSPMessage * message)
2507 {
2508   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), GST_RTSP_EINVAL);
2509   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2510   g_return_val_if_fail (message->type == GST_RTSP_MESSAGE_REQUEST ||
2511       message->type == GST_RTSP_MESSAGE_RESPONSE, GST_RTSP_EINVAL);
2512
2513   send_message (client, session, message, FALSE);
2514
2515   return GST_RTSP_OK;
2516 }
2517
2518 static GstRTSPResult
2519 do_send_message (GstRTSPClient * client, GstRTSPMessage * message,
2520     gboolean close, gpointer user_data)
2521 {
2522   GstRTSPClientPrivate *priv = client->priv;
2523
2524   /* send the response and store the seq number so we can wait until it's
2525    * written to the client to close the connection */
2526   return gst_rtsp_watch_send_message (priv->watch, message, close ?
2527       &priv->close_seq : NULL);
2528 }
2529
2530 static GstRTSPResult
2531 message_received (GstRTSPWatch * watch, GstRTSPMessage * message,
2532     gpointer user_data)
2533 {
2534   return gst_rtsp_client_handle_message (GST_RTSP_CLIENT (user_data), message);
2535 }
2536
2537 static GstRTSPResult
2538 message_sent (GstRTSPWatch * watch, guint cseq, gpointer user_data)
2539 {
2540   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2541   GstRTSPClientPrivate *priv = client->priv;
2542
2543   if (priv->close_seq && priv->close_seq == cseq) {
2544     priv->close_seq = 0;
2545     close_connection (client);
2546   }
2547
2548   return GST_RTSP_OK;
2549 }
2550
2551 static GstRTSPResult
2552 closed (GstRTSPWatch * watch, gpointer user_data)
2553 {
2554   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2555   GstRTSPClientPrivate *priv = client->priv;
2556   const gchar *tunnelid;
2557
2558   GST_INFO ("client %p: connection closed", client);
2559
2560   if ((tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection))) {
2561     g_mutex_lock (&tunnels_lock);
2562     /* remove from tunnelids */
2563     g_hash_table_remove (tunnels, tunnelid);
2564     g_mutex_unlock (&tunnels_lock);
2565   }
2566
2567   gst_rtsp_client_set_send_func (client, NULL, NULL, NULL);
2568
2569   return GST_RTSP_OK;
2570 }
2571
2572 static GstRTSPResult
2573 error (GstRTSPWatch * watch, GstRTSPResult result, gpointer user_data)
2574 {
2575   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2576   gchar *str;
2577
2578   str = gst_rtsp_strresult (result);
2579   GST_INFO ("client %p: received an error %s", client, str);
2580   g_free (str);
2581
2582   return GST_RTSP_OK;
2583 }
2584
2585 static GstRTSPResult
2586 error_full (GstRTSPWatch * watch, GstRTSPResult result,
2587     GstRTSPMessage * message, guint id, gpointer user_data)
2588 {
2589   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2590   gchar *str;
2591
2592   str = gst_rtsp_strresult (result);
2593   GST_INFO
2594       ("client %p: error when handling message %p with id %d: %s",
2595       client, message, id, str);
2596   g_free (str);
2597
2598   return GST_RTSP_OK;
2599 }
2600
2601 static gboolean
2602 remember_tunnel (GstRTSPClient * client)
2603 {
2604   GstRTSPClientPrivate *priv = client->priv;
2605   const gchar *tunnelid;
2606
2607   /* store client in the pending tunnels */
2608   tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection);
2609   if (tunnelid == NULL)
2610     goto no_tunnelid;
2611
2612   GST_INFO ("client %p: inserting tunnel session %s", client, tunnelid);
2613
2614   /* we can't have two clients connecting with the same tunnelid */
2615   g_mutex_lock (&tunnels_lock);
2616   if (g_hash_table_lookup (tunnels, tunnelid))
2617     goto tunnel_existed;
2618
2619   g_hash_table_insert (tunnels, g_strdup (tunnelid), g_object_ref (client));
2620   g_mutex_unlock (&tunnels_lock);
2621
2622   return TRUE;
2623
2624   /* ERRORS */
2625 no_tunnelid:
2626   {
2627     GST_ERROR ("client %p: no tunnelid provided", client);
2628     return FALSE;
2629   }
2630 tunnel_existed:
2631   {
2632     g_mutex_unlock (&tunnels_lock);
2633     GST_ERROR ("client %p: tunnel session %s already existed", client,
2634         tunnelid);
2635     return FALSE;
2636   }
2637 }
2638
2639 static GstRTSPStatusCode
2640 tunnel_start (GstRTSPWatch * watch, gpointer user_data)
2641 {
2642   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2643   GstRTSPClientPrivate *priv = client->priv;
2644
2645   GST_INFO ("client %p: tunnel start (connection %p)", client,
2646       priv->connection);
2647
2648   if (!remember_tunnel (client))
2649     goto tunnel_error;
2650
2651   return GST_RTSP_STS_OK;
2652
2653   /* ERRORS */
2654 tunnel_error:
2655   {
2656     GST_ERROR ("client %p: error starting tunnel", client);
2657     return GST_RTSP_STS_SERVICE_UNAVAILABLE;
2658   }
2659 }
2660
2661 static GstRTSPResult
2662 tunnel_lost (GstRTSPWatch * watch, gpointer user_data)
2663 {
2664   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2665   GstRTSPClientPrivate *priv = client->priv;
2666
2667   GST_WARNING ("client %p: tunnel lost (connection %p)", client,
2668       priv->connection);
2669
2670   /* ignore error, it'll only be a problem when the client does a POST again */
2671   remember_tunnel (client);
2672
2673   return GST_RTSP_OK;
2674 }
2675
2676 static GstRTSPResult
2677 tunnel_complete (GstRTSPWatch * watch, gpointer user_data)
2678 {
2679   const gchar *tunnelid;
2680   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2681   GstRTSPClientPrivate *priv = client->priv;
2682   GstRTSPClient *oclient;
2683   GstRTSPClientPrivate *opriv;
2684
2685   GST_INFO ("client %p: tunnel complete", client);
2686
2687   /* find previous tunnel */
2688   tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection);
2689   if (tunnelid == NULL)
2690     goto no_tunnelid;
2691
2692   g_mutex_lock (&tunnels_lock);
2693   if (!(oclient = g_hash_table_lookup (tunnels, tunnelid)))
2694     goto no_tunnel;
2695
2696   /* remove the old client from the table. ref before because removing it will
2697    * remove the ref to it. */
2698   g_object_ref (oclient);
2699   g_hash_table_remove (tunnels, tunnelid);
2700
2701   opriv = oclient->priv;
2702
2703   if (opriv->watch == NULL)
2704     goto tunnel_closed;
2705   g_mutex_unlock (&tunnels_lock);
2706
2707   GST_INFO ("client %p: found tunnel %p (old %p, new %p)", client, oclient,
2708       opriv->connection, priv->connection);
2709
2710   /* merge the tunnels into the first client */
2711   gst_rtsp_connection_do_tunnel (opriv->connection, priv->connection);
2712   gst_rtsp_watch_reset (opriv->watch);
2713   g_object_unref (oclient);
2714
2715   return GST_RTSP_OK;
2716
2717   /* ERRORS */
2718 no_tunnelid:
2719   {
2720     GST_ERROR ("client %p: no tunnelid provided", client);
2721     return GST_RTSP_ERROR;
2722   }
2723 no_tunnel:
2724   {
2725     g_mutex_unlock (&tunnels_lock);
2726     GST_ERROR ("client %p: tunnel session %s not found", client, tunnelid);
2727     return GST_RTSP_ERROR;
2728   }
2729 tunnel_closed:
2730   {
2731     g_mutex_unlock (&tunnels_lock);
2732     GST_ERROR ("client %p: tunnel session %s was closed", client, tunnelid);
2733     g_object_unref (oclient);
2734     return GST_RTSP_ERROR;
2735   }
2736 }
2737
2738 static GstRTSPWatchFuncs watch_funcs = {
2739   message_received,
2740   message_sent,
2741   closed,
2742   error,
2743   tunnel_start,
2744   tunnel_complete,
2745   error_full,
2746   tunnel_lost
2747 };
2748
2749 static void
2750 client_watch_notify (GstRTSPClient * client)
2751 {
2752   GstRTSPClientPrivate *priv = client->priv;
2753
2754   GST_INFO ("client %p: watch destroyed", client);
2755   priv->watch = NULL;
2756   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_CLOSED], 0, NULL);
2757   g_object_unref (client);
2758 }
2759
2760 /**
2761  * gst_rtsp_client_attach:
2762  * @client: a #GstRTSPClient
2763  * @context: (allow-none): a #GMainContext
2764  *
2765  * Attaches @client to @context. When the mainloop for @context is run, the
2766  * client will be dispatched. When @context is NULL, the default context will be
2767  * used).
2768  *
2769  * This function should be called when the client properties and urls are fully
2770  * configured and the client is ready to start.
2771  *
2772  * Returns: the ID (greater than 0) for the source within the GMainContext.
2773  */
2774 guint
2775 gst_rtsp_client_attach (GstRTSPClient * client, GMainContext * context)
2776 {
2777   GstRTSPClientPrivate *priv;
2778   guint res;
2779
2780   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), 0);
2781   priv = client->priv;
2782   g_return_val_if_fail (priv->connection != NULL, 0);
2783   g_return_val_if_fail (priv->watch == NULL, 0);
2784
2785   /* create watch for the connection and attach */
2786   priv->watch = gst_rtsp_watch_new (priv->connection, &watch_funcs,
2787       g_object_ref (client), (GDestroyNotify) client_watch_notify);
2788   gst_rtsp_client_set_send_func (client, do_send_message, priv->watch,
2789       (GDestroyNotify) gst_rtsp_watch_unref);
2790
2791   /* FIXME make this configurable. We don't want to do this yet because it will
2792    * be superceeded by a cache object later */
2793   gst_rtsp_watch_set_send_backlog (priv->watch, 0, 100);
2794
2795   GST_INFO ("attaching to context %p", context);
2796   res = gst_rtsp_watch_attach (priv->watch, context);
2797
2798   return res;
2799 }
2800
2801 /**
2802  * gst_rtsp_client_session_filter:
2803  * @client: a #GstRTSPClient
2804  * @func: (scope call): a callback
2805  * @user_data: user data passed to @func
2806  *
2807  * Call @func for each session managed by @client. The result value of @func
2808  * determines what happens to the session. @func will be called with @client
2809  * locked so no further actions on @client can be performed from @func.
2810  *
2811  * If @func returns #GST_RTSP_FILTER_REMOVE, the session will be removed from
2812  * @client.
2813  *
2814  * If @func returns #GST_RTSP_FILTER_KEEP, the session will remain in @client.
2815  *
2816  * If @func returns #GST_RTSP_FILTER_REF, the session will remain in @client but
2817  * will also be added with an additional ref to the result #GList of this
2818  * function..
2819  *
2820  * Returns: (element-type GstRTSPSession) (transfer full): a #GList with all
2821  * sessions for which @func returned #GST_RTSP_FILTER_REF. After usage, each
2822  * element in the #GList should be unreffed before the list is freed.
2823  */
2824 GList *
2825 gst_rtsp_client_session_filter (GstRTSPClient * client,
2826     GstRTSPClientSessionFilterFunc func, gpointer user_data)
2827 {
2828   GstRTSPClientPrivate *priv;
2829   GList *result, *walk, *next;
2830
2831   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2832   g_return_val_if_fail (func != NULL, NULL);
2833
2834   priv = client->priv;
2835
2836   result = NULL;
2837
2838   g_mutex_lock (&priv->lock);
2839   for (walk = priv->sessions; walk; walk = next) {
2840     GstRTSPSession *sess = walk->data;
2841
2842     next = g_list_next (walk);
2843
2844     switch (func (client, sess, user_data)) {
2845       case GST_RTSP_FILTER_REMOVE:
2846         /* stop watching the session and pretent it went away */
2847         client_cleanup_session (client, sess);
2848         break;
2849       case GST_RTSP_FILTER_REF:
2850         result = g_list_prepend (result, g_object_ref (sess));
2851         break;
2852       case GST_RTSP_FILTER_KEEP:
2853       default:
2854         break;
2855     }
2856   }
2857   g_mutex_unlock (&priv->lock);
2858
2859   return result;
2860 }