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