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