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