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