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