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