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