fa1c3a05338d8ae02db2d767e4dbaaa9760dd1e1
[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   /* check if reply is SDP */
2292   gst_rtsp_message_get_header (ctx->request, GST_RTSP_HDR_CONTENT_TYPE, &cont,
2293       0);
2294   /* could not be set but since the request returned OK, we assume it
2295    * was SDP, else check it. */
2296   if (cont) {
2297     if (!g_ascii_strcasecmp (cont, "application/sdp") == 0)
2298       goto wrong_content_type;
2299   }
2300
2301   /* get message body and parse as SDP */
2302   gst_rtsp_message_get_body (ctx->request, &data, &size);
2303   if (data == NULL || size == 0)
2304     goto no_message;
2305
2306   GST_DEBUG ("client %p: parse SDP...", client);
2307   gst_sdp_message_new (&sdp);
2308   sres = gst_sdp_message_parse_buffer (data, size, sdp);
2309   if (sres != GST_SDP_OK)
2310     goto sdp_parse_failed;
2311
2312   if (!(path = gst_rtsp_mount_points_make_path (priv->mount_points, ctx->uri)))
2313     goto no_path;
2314
2315   /* find the media object for the uri */
2316   if (!(media = find_media (client, ctx, path, NULL)))
2317     goto no_media;
2318
2319   if (!gst_rtsp_media_is_record (media))
2320     goto play_media;
2321
2322   /* Tell client subclass about the media */
2323   if (!klass->handle_sdp (client, ctx, media, sdp))
2324     goto unhandled_sdp;
2325
2326   /* we suspend after the announce */
2327   gst_rtsp_media_suspend (media);
2328   g_object_unref (media);
2329
2330   gst_rtsp_message_init_response (ctx->response, GST_RTSP_STS_OK,
2331       gst_rtsp_status_as_text (GST_RTSP_STS_OK), ctx->request);
2332
2333   send_message (client, ctx, ctx->response, FALSE);
2334
2335   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_ANNOUNCE_REQUEST],
2336       0, ctx);
2337
2338   gst_sdp_message_free (sdp);
2339   g_free (path);
2340   return TRUE;
2341
2342 no_uri:
2343   {
2344     GST_ERROR ("client %p: no uri", client);
2345     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
2346     return FALSE;
2347   }
2348 no_mount_points:
2349   {
2350     GST_ERROR ("client %p: no mount points configured", client);
2351     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
2352     return FALSE;
2353   }
2354 no_path:
2355   {
2356     GST_ERROR ("client %p: can't find path for url", client);
2357     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
2358     gst_sdp_message_free (sdp);
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     return FALSE;
2366   }
2367 no_message:
2368   {
2369     GST_ERROR ("client %p: can't find SDP message", client);
2370     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
2371     return FALSE;
2372   }
2373 sdp_parse_failed:
2374   {
2375     GST_ERROR ("client %p: failed to parse SDP message", client);
2376     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
2377     gst_sdp_message_free (sdp);
2378     return FALSE;
2379   }
2380 no_media:
2381   {
2382     GST_ERROR ("client %p: no media", client);
2383     g_free (path);
2384     /* error reply is already sent */
2385     gst_sdp_message_free (sdp);
2386     return FALSE;
2387   }
2388 play_media:
2389   {
2390     GST_ERROR ("client %p: PLAY media does not support ANNOUNCE", client);
2391     send_generic_response (client, GST_RTSP_STS_METHOD_NOT_ALLOWED, ctx);
2392     g_free (path);
2393     g_object_unref (media);
2394     gst_sdp_message_free (sdp);
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     gst_sdp_message_free (sdp);
2404     return FALSE;
2405   }
2406 }
2407
2408 static gboolean
2409 handle_record_request (GstRTSPClient * client, GstRTSPContext * ctx)
2410 {
2411   GstRTSPSession *session;
2412   GstRTSPClientClass *klass;
2413   GstRTSPSessionMedia *sessmedia;
2414   GstRTSPMedia *media;
2415   GstRTSPUrl *uri;
2416   GstRTSPState rtspstate;
2417   gchar *path;
2418   gint matched;
2419
2420   if (!(session = ctx->session))
2421     goto no_session;
2422
2423   if (!(uri = ctx->uri))
2424     goto no_uri;
2425
2426   klass = GST_RTSP_CLIENT_GET_CLASS (client);
2427   path = klass->make_path_from_uri (client, uri);
2428
2429   /* get a handle to the configuration of the media in the session */
2430   sessmedia = gst_rtsp_session_get_media (session, path, &matched);
2431   if (!sessmedia)
2432     goto not_found;
2433
2434   if (path[matched] != '\0')
2435     goto no_aggregate;
2436
2437   g_free (path);
2438
2439   ctx->sessmedia = sessmedia;
2440   ctx->media = media = gst_rtsp_session_media_get_media (sessmedia);
2441
2442   if (!gst_rtsp_media_is_record (media))
2443     goto play_media;
2444
2445   /* the session state must be playing or ready */
2446   rtspstate = gst_rtsp_session_media_get_rtsp_state (sessmedia);
2447   if (rtspstate != GST_RTSP_STATE_PLAYING && rtspstate != GST_RTSP_STATE_READY)
2448     goto invalid_state;
2449
2450   /* in play we first unsuspend, media could be suspended from SDP or PAUSED */
2451   if (!gst_rtsp_media_unsuspend (media))
2452     goto unsuspend_failed;
2453
2454   gst_rtsp_message_init_response (ctx->response, GST_RTSP_STS_OK,
2455       gst_rtsp_status_as_text (GST_RTSP_STS_OK), ctx->request);
2456
2457   send_message (client, ctx, ctx->response, FALSE);
2458
2459   /* start playing after sending the response */
2460   gst_rtsp_session_media_set_state (sessmedia, GST_STATE_PLAYING);
2461
2462   gst_rtsp_session_media_set_rtsp_state (sessmedia, GST_RTSP_STATE_PLAYING);
2463
2464   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_RECORD_REQUEST], 0,
2465       ctx);
2466
2467   return TRUE;
2468
2469   /* ERRORS */
2470 no_session:
2471   {
2472     GST_ERROR ("client %p: no session", client);
2473     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
2474     return FALSE;
2475   }
2476 no_uri:
2477   {
2478     GST_ERROR ("client %p: no uri supplied", client);
2479     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
2480     return FALSE;
2481   }
2482 not_found:
2483   {
2484     GST_ERROR ("client %p: media not found", client);
2485     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
2486     return FALSE;
2487   }
2488 no_aggregate:
2489   {
2490     GST_ERROR ("client %p: no aggregate path %s", client, path);
2491     send_generic_response (client,
2492         GST_RTSP_STS_ONLY_AGGREGATE_OPERATION_ALLOWED, ctx);
2493     g_free (path);
2494     return FALSE;
2495   }
2496 play_media:
2497   {
2498     GST_ERROR ("client %p: PLAY media does not support RECORD", client);
2499     send_generic_response (client, GST_RTSP_STS_METHOD_NOT_ALLOWED, ctx);
2500     return FALSE;
2501   }
2502 invalid_state:
2503   {
2504     GST_ERROR ("client %p: not PLAYING or READY", client);
2505     send_generic_response (client, GST_RTSP_STS_METHOD_NOT_VALID_IN_THIS_STATE,
2506         ctx);
2507     return FALSE;
2508   }
2509 unsuspend_failed:
2510   {
2511     GST_ERROR ("client %p: unsuspend failed", client);
2512     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, ctx);
2513     return FALSE;
2514   }
2515 }
2516
2517 static gboolean
2518 handle_options_request (GstRTSPClient * client, GstRTSPContext * ctx)
2519 {
2520   GstRTSPMethod options;
2521   gchar *str;
2522
2523   options = GST_RTSP_DESCRIBE |
2524       GST_RTSP_OPTIONS |
2525       GST_RTSP_PAUSE |
2526       GST_RTSP_PLAY |
2527       GST_RTSP_SETUP |
2528       GST_RTSP_GET_PARAMETER | GST_RTSP_SET_PARAMETER | GST_RTSP_TEARDOWN;
2529
2530   str = gst_rtsp_options_as_text (options);
2531
2532   gst_rtsp_message_init_response (ctx->response, GST_RTSP_STS_OK,
2533       gst_rtsp_status_as_text (GST_RTSP_STS_OK), ctx->request);
2534
2535   gst_rtsp_message_add_header (ctx->response, GST_RTSP_HDR_PUBLIC, str);
2536   g_free (str);
2537
2538   send_message (client, ctx, ctx->response, FALSE);
2539
2540   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_OPTIONS_REQUEST],
2541       0, ctx);
2542
2543   return TRUE;
2544 }
2545
2546 /* remove duplicate and trailing '/' */
2547 static void
2548 sanitize_uri (GstRTSPUrl * uri)
2549 {
2550   gint i, len;
2551   gchar *s, *d;
2552   gboolean have_slash, prev_slash;
2553
2554   s = d = uri->abspath;
2555   len = strlen (uri->abspath);
2556
2557   prev_slash = FALSE;
2558
2559   for (i = 0; i < len; i++) {
2560     have_slash = s[i] == '/';
2561     *d = s[i];
2562     if (!have_slash || !prev_slash)
2563       d++;
2564     prev_slash = have_slash;
2565   }
2566   len = d - uri->abspath;
2567   /* don't remove the first slash if that's the only thing left */
2568   if (len > 1 && *(d - 1) == '/')
2569     d--;
2570   *d = '\0';
2571 }
2572
2573 /* is called when the session is removed from its session pool. */
2574 static void
2575 client_session_removed (GstRTSPSessionPool * pool, GstRTSPSession * session,
2576     GstRTSPClient * client)
2577 {
2578   GstRTSPClientPrivate *priv = client->priv;
2579
2580   GST_INFO ("client %p: session %p removed", client, session);
2581
2582   g_mutex_lock (&priv->lock);
2583   if (priv->watch != NULL)
2584     gst_rtsp_watch_set_send_backlog (priv->watch, 0, 0);
2585   client_unwatch_session (client, session, NULL);
2586   if (priv->watch != NULL)
2587     gst_rtsp_watch_set_send_backlog (priv->watch, 0, WATCH_BACKLOG_SIZE);
2588   g_mutex_unlock (&priv->lock);
2589 }
2590
2591 /* Returns TRUE if there are no Require headers, otherwise returns FALSE
2592  * and also returns a newly-allocated string of (comma-separated) unsupported
2593  * options in the unsupported_reqs variable .
2594  *
2595  * There may be multiple Require headers, but we must send one single
2596  * Unsupported header with all the unsupported options as response. If
2597  * an incoming Require header contained a comma-separated list of options
2598  * GstRtspConnection will already have split that list up into multiple
2599  * headers.
2600  *
2601  * TODO: allow the application to decide what features are supported
2602  */
2603 static gboolean
2604 check_request_requirements (GstRTSPMessage * msg, gchar ** unsupported_reqs)
2605 {
2606   GstRTSPResult res;
2607   GPtrArray *arr = NULL;
2608   gchar *reqs = NULL;
2609   gint i;
2610
2611   i = 0;
2612   do {
2613     res = gst_rtsp_message_get_header (msg, GST_RTSP_HDR_REQUIRE, &reqs, i++);
2614
2615     if (res == GST_RTSP_ENOTIMPL)
2616       break;
2617
2618     if (arr == NULL)
2619       arr = g_ptr_array_new_with_free_func ((GDestroyNotify) g_free);
2620
2621     g_ptr_array_add (arr, g_strdup (reqs));
2622   }
2623   while (TRUE);
2624
2625   /* if we don't have any Require headers at all, all is fine */
2626   if (i == 1)
2627     return TRUE;
2628
2629   /* otherwise we've now processed at all the Require headers */
2630   g_ptr_array_add (arr, NULL);
2631
2632   /* for now we don't commit to supporting anything, so will just report
2633    * all of the required options as unsupported */
2634   *unsupported_reqs = g_strjoinv (", ", (gchar **) arr->pdata);
2635
2636   g_ptr_array_unref (arr);
2637   return FALSE;
2638 }
2639
2640 static void
2641 handle_request (GstRTSPClient * client, GstRTSPMessage * request)
2642 {
2643   GstRTSPClientPrivate *priv = client->priv;
2644   GstRTSPMethod method;
2645   const gchar *uristr;
2646   GstRTSPUrl *uri = NULL;
2647   GstRTSPVersion version;
2648   GstRTSPResult res;
2649   GstRTSPSession *session = NULL;
2650   GstRTSPContext sctx = { NULL }, *ctx;
2651   GstRTSPMessage response = { 0 };
2652   gchar *unsupported_reqs = NULL;
2653   gchar *sessid;
2654
2655   if (!(ctx = gst_rtsp_context_get_current ())) {
2656     ctx = &sctx;
2657     ctx->auth = priv->auth;
2658     gst_rtsp_context_push_current (ctx);
2659   }
2660
2661   ctx->conn = priv->connection;
2662   ctx->client = client;
2663   ctx->request = request;
2664   ctx->response = &response;
2665
2666   if (gst_debug_category_get_threshold (rtsp_client_debug) >= GST_LEVEL_LOG) {
2667     gst_rtsp_message_dump (request);
2668   }
2669
2670   gst_rtsp_message_parse_request (request, &method, &uristr, &version);
2671
2672   GST_INFO ("client %p: received a request %s %s %s", client,
2673       gst_rtsp_method_as_text (method), uristr,
2674       gst_rtsp_version_as_text (version));
2675
2676   /* we can only handle 1.0 requests */
2677   if (version != GST_RTSP_VERSION_1_0)
2678     goto not_supported;
2679
2680   ctx->method = method;
2681
2682   /* we always try to parse the url first */
2683   if (strcmp (uristr, "*") == 0) {
2684     /* special case where we have * as uri, keep uri = NULL */
2685   } else if (gst_rtsp_url_parse (uristr, &uri) != GST_RTSP_OK) {
2686     /* check if the uristr is an absolute path <=> scheme and host information
2687      * is missing */
2688     gchar *scheme;
2689
2690     scheme = g_uri_parse_scheme (uristr);
2691     if (scheme == NULL && g_str_has_prefix (uristr, "/")) {
2692       gchar *absolute_uristr = NULL;
2693
2694       GST_WARNING_OBJECT (client, "request doesn't contain absolute url");
2695       if (priv->server_ip == NULL) {
2696         GST_WARNING_OBJECT (client, "host information missing");
2697         goto bad_request;
2698       }
2699
2700       absolute_uristr =
2701           g_strdup_printf ("rtsp://%s%s", priv->server_ip, uristr);
2702
2703       GST_DEBUG_OBJECT (client, "absolute url: %s", absolute_uristr);
2704       if (gst_rtsp_url_parse (absolute_uristr, &uri) != GST_RTSP_OK) {
2705         g_free (absolute_uristr);
2706         goto bad_request;
2707       }
2708       g_free (absolute_uristr);
2709     } else {
2710       g_free (scheme);
2711       goto bad_request;
2712     }
2713   }
2714
2715   /* get the session if there is any */
2716   res = gst_rtsp_message_get_header (request, GST_RTSP_HDR_SESSION, &sessid, 0);
2717   if (res == GST_RTSP_OK) {
2718     if (priv->session_pool == NULL)
2719       goto no_pool;
2720
2721     /* we had a session in the request, find it again */
2722     if (!(session = gst_rtsp_session_pool_find (priv->session_pool, sessid)))
2723       goto session_not_found;
2724
2725     /* we add the session to the client list of watched sessions. When a session
2726      * disappears because it times out, we will be notified. If all sessions are
2727      * gone, we will close the connection */
2728     client_watch_session (client, session);
2729   }
2730
2731   /* sanitize the uri */
2732   if (uri)
2733     sanitize_uri (uri);
2734   ctx->uri = uri;
2735   ctx->session = session;
2736
2737   if (!gst_rtsp_auth_check (GST_RTSP_AUTH_CHECK_URL))
2738     goto not_authorized;
2739
2740   /* handle any 'Require' headers */
2741   if (!check_request_requirements (ctx->request, &unsupported_reqs))
2742     goto unsupported_requirement;
2743
2744   /* the backlog must be unlimited while processing requests.
2745    * the causes of this are two cases of deadlocks while streaming over TCP:
2746    *
2747    * 1. consider the scenario where the media pipeline's streaming thread
2748    * is blocking in the appsink (taking the appsink's preroll lock) because
2749    * the backlog is full. when a PAUSE request is received by the RTSP
2750    * client thread then the the state of the session media ought to change
2751    * to PAUSED. while most elements in the pipeline can change state this
2752    * can never happen for the appsink since its preroll lock is taken by
2753    * another thread.
2754    *
2755    * 2. consider the scenario where the media pipeline's streaming thread
2756    * is blocking in the appsink new_sample callback (taking the send lock
2757    * in RTSP client) because the backlog is full. when e.g. a GET request
2758    * is received by the RTSP client thread then a response ought to be sent
2759    * but this can never happen since it requires taking the send lock
2760    * already taken by another thread.
2761    *
2762    * the reason that the backlog is never emptied is that the source used
2763    * for dequeing messages from the backlog is never dispatched because it
2764    * is attached to the same mainloop as the source receving RTSP requests and
2765    * therefore run by the RTSP client thread which is alreayd blocking.
2766    *
2767    * without significant changes the easiest way to cope with this is to
2768    * not block indefinitely when the backlog is full, but rather let the
2769    * backlog grow in size. this in effect means that there can not be any
2770    * upper boundary on its size.
2771    */
2772   if (priv->watch != NULL)
2773     gst_rtsp_watch_set_send_backlog (priv->watch, 0, 0);
2774
2775   /* now see what is asked and dispatch to a dedicated handler */
2776   switch (method) {
2777     case GST_RTSP_OPTIONS:
2778       handle_options_request (client, ctx);
2779       break;
2780     case GST_RTSP_DESCRIBE:
2781       handle_describe_request (client, ctx);
2782       break;
2783     case GST_RTSP_SETUP:
2784       handle_setup_request (client, ctx);
2785       break;
2786     case GST_RTSP_PLAY:
2787       handle_play_request (client, ctx);
2788       break;
2789     case GST_RTSP_PAUSE:
2790       handle_pause_request (client, ctx);
2791       break;
2792     case GST_RTSP_TEARDOWN:
2793       handle_teardown_request (client, ctx);
2794       break;
2795     case GST_RTSP_SET_PARAMETER:
2796       handle_set_param_request (client, ctx);
2797       break;
2798     case GST_RTSP_GET_PARAMETER:
2799       handle_get_param_request (client, ctx);
2800       break;
2801     case GST_RTSP_ANNOUNCE:
2802       handle_announce_request (client, ctx);
2803       break;
2804     case GST_RTSP_RECORD:
2805       handle_record_request (client, ctx);
2806       break;
2807     case GST_RTSP_REDIRECT:
2808       if (priv->watch != NULL)
2809         gst_rtsp_watch_set_send_backlog (priv->watch, 0, WATCH_BACKLOG_SIZE);
2810       goto not_implemented;
2811     case GST_RTSP_INVALID:
2812     default:
2813       if (priv->watch != NULL)
2814         gst_rtsp_watch_set_send_backlog (priv->watch, 0, WATCH_BACKLOG_SIZE);
2815       goto bad_request;
2816   }
2817
2818   if (priv->watch != NULL)
2819     gst_rtsp_watch_set_send_backlog (priv->watch, 0, WATCH_BACKLOG_SIZE);
2820
2821 done:
2822   if (ctx == &sctx)
2823     gst_rtsp_context_pop_current (ctx);
2824   if (session)
2825     g_object_unref (session);
2826   if (uri)
2827     gst_rtsp_url_free (uri);
2828   return;
2829
2830   /* ERRORS */
2831 not_supported:
2832   {
2833     GST_ERROR ("client %p: version %d not supported", client, version);
2834     send_generic_response (client, GST_RTSP_STS_RTSP_VERSION_NOT_SUPPORTED,
2835         ctx);
2836     goto done;
2837   }
2838 bad_request:
2839   {
2840     GST_ERROR ("client %p: bad request", client);
2841     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
2842     goto done;
2843   }
2844 no_pool:
2845   {
2846     GST_ERROR ("client %p: no pool configured", client);
2847     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
2848     goto done;
2849   }
2850 session_not_found:
2851   {
2852     GST_ERROR ("client %p: session not found", client);
2853     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
2854     goto done;
2855   }
2856 not_authorized:
2857   {
2858     GST_ERROR ("client %p: not allowed", client);
2859     /* error reply is already sent */
2860     goto done;
2861   }
2862 unsupported_requirement:
2863   {
2864     GST_ERROR ("client %p: Required option is not supported (%s)", client,
2865         unsupported_reqs);
2866     send_option_not_supported_response (client, ctx, unsupported_reqs);
2867     g_free (unsupported_reqs);
2868     goto done;
2869   }
2870 not_implemented:
2871   {
2872     GST_ERROR ("client %p: method %d not implemented", client, method);
2873     send_generic_response (client, GST_RTSP_STS_NOT_IMPLEMENTED, ctx);
2874     goto done;
2875   }
2876 }
2877
2878
2879 static void
2880 handle_response (GstRTSPClient * client, GstRTSPMessage * response)
2881 {
2882   GstRTSPClientPrivate *priv = client->priv;
2883   GstRTSPResult res;
2884   GstRTSPSession *session = NULL;
2885   GstRTSPContext sctx = { NULL }, *ctx;
2886   gchar *sessid;
2887
2888   if (!(ctx = gst_rtsp_context_get_current ())) {
2889     ctx = &sctx;
2890     ctx->auth = priv->auth;
2891     gst_rtsp_context_push_current (ctx);
2892   }
2893
2894   ctx->conn = priv->connection;
2895   ctx->client = client;
2896   ctx->request = NULL;
2897   ctx->uri = NULL;
2898   ctx->method = GST_RTSP_INVALID;
2899   ctx->response = response;
2900
2901   if (gst_debug_category_get_threshold (rtsp_client_debug) >= GST_LEVEL_LOG) {
2902     gst_rtsp_message_dump (response);
2903   }
2904
2905   GST_INFO ("client %p: received a response", client);
2906
2907   /* get the session if there is any */
2908   res =
2909       gst_rtsp_message_get_header (response, GST_RTSP_HDR_SESSION, &sessid, 0);
2910   if (res == GST_RTSP_OK) {
2911     if (priv->session_pool == NULL)
2912       goto no_pool;
2913
2914     /* we had a session in the request, find it again */
2915     if (!(session = gst_rtsp_session_pool_find (priv->session_pool, sessid)))
2916       goto session_not_found;
2917
2918     /* we add the session to the client list of watched sessions. When a session
2919      * disappears because it times out, we will be notified. If all sessions are
2920      * gone, we will close the connection */
2921     client_watch_session (client, session);
2922   }
2923
2924   ctx->session = session;
2925
2926   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_HANDLE_RESPONSE],
2927       0, ctx);
2928
2929 done:
2930   if (ctx == &sctx)
2931     gst_rtsp_context_pop_current (ctx);
2932   if (session)
2933     g_object_unref (session);
2934   return;
2935
2936 no_pool:
2937   {
2938     GST_ERROR ("client %p: no pool configured", client);
2939     goto done;
2940   }
2941 session_not_found:
2942   {
2943     GST_ERROR ("client %p: session not found", client);
2944     goto done;
2945   }
2946 }
2947
2948 static void
2949 handle_data (GstRTSPClient * client, GstRTSPMessage * message)
2950 {
2951   GstRTSPClientPrivate *priv = client->priv;
2952   GstRTSPResult res;
2953   guint8 channel;
2954   guint8 *data;
2955   guint size;
2956   GstBuffer *buffer;
2957   GstRTSPStreamTransport *trans;
2958
2959   /* find the stream for this message */
2960   res = gst_rtsp_message_parse_data (message, &channel);
2961   if (res != GST_RTSP_OK)
2962     return;
2963
2964   gst_rtsp_message_get_body (message, &data, &size);
2965   if (size < 2)
2966     goto invalid_length;
2967
2968   gst_rtsp_message_steal_body (message, &data, &size);
2969
2970   /* Strip trailing \0 (which GstRTSPConnection adds) */
2971   --size;
2972
2973   buffer = gst_buffer_new_wrapped (data, size);
2974
2975   trans =
2976       g_hash_table_lookup (priv->transports, GINT_TO_POINTER ((gint) channel));
2977   if (trans) {
2978     /* dispatch to the stream based on the channel number */
2979     GST_LOG_OBJECT (client, "%u bytes of data on channel %u", size, channel);
2980     gst_rtsp_stream_transport_recv_data (trans, channel, buffer);
2981   } else {
2982     GST_DEBUG_OBJECT (client, "received %u bytes of data for "
2983         "unknown channel %u", size, channel);
2984     gst_buffer_unref (buffer);
2985   }
2986
2987   return;
2988
2989 /* ERRORS */
2990 invalid_length:
2991   {
2992     GST_DEBUG ("client %p: Short message received, ignoring", client);
2993     return;
2994   }
2995 }
2996
2997 /**
2998  * gst_rtsp_client_set_session_pool:
2999  * @client: a #GstRTSPClient
3000  * @pool: (transfer none): a #GstRTSPSessionPool
3001  *
3002  * Set @pool as the sessionpool for @client which it will use to find
3003  * or allocate sessions. the sessionpool is usually inherited from the server
3004  * that created the client but can be overridden later.
3005  */
3006 void
3007 gst_rtsp_client_set_session_pool (GstRTSPClient * client,
3008     GstRTSPSessionPool * pool)
3009 {
3010   GstRTSPSessionPool *old;
3011   GstRTSPClientPrivate *priv;
3012
3013   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
3014
3015   priv = client->priv;
3016
3017   if (pool)
3018     g_object_ref (pool);
3019
3020   g_mutex_lock (&priv->lock);
3021   old = priv->session_pool;
3022   priv->session_pool = pool;
3023
3024   if (priv->session_removed_id) {
3025     g_signal_handler_disconnect (old, priv->session_removed_id);
3026     priv->session_removed_id = 0;
3027   }
3028   g_mutex_unlock (&priv->lock);
3029
3030   /* FIXME, should remove all sessions from the old pool for this client */
3031   if (old)
3032     g_object_unref (old);
3033 }
3034
3035 /**
3036  * gst_rtsp_client_get_session_pool:
3037  * @client: a #GstRTSPClient
3038  *
3039  * Get the #GstRTSPSessionPool object that @client uses to manage its sessions.
3040  *
3041  * Returns: (transfer full): a #GstRTSPSessionPool, unref after usage.
3042  */
3043 GstRTSPSessionPool *
3044 gst_rtsp_client_get_session_pool (GstRTSPClient * client)
3045 {
3046   GstRTSPClientPrivate *priv;
3047   GstRTSPSessionPool *result;
3048
3049   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
3050
3051   priv = client->priv;
3052
3053   g_mutex_lock (&priv->lock);
3054   if ((result = priv->session_pool))
3055     g_object_ref (result);
3056   g_mutex_unlock (&priv->lock);
3057
3058   return result;
3059 }
3060
3061 /**
3062  * gst_rtsp_client_set_mount_points:
3063  * @client: a #GstRTSPClient
3064  * @mounts: (transfer none): a #GstRTSPMountPoints
3065  *
3066  * Set @mounts as the mount points for @client which it will use to map urls
3067  * to media streams. These mount points are usually inherited from the server that
3068  * created the client but can be overriden later.
3069  */
3070 void
3071 gst_rtsp_client_set_mount_points (GstRTSPClient * client,
3072     GstRTSPMountPoints * mounts)
3073 {
3074   GstRTSPClientPrivate *priv;
3075   GstRTSPMountPoints *old;
3076
3077   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
3078
3079   priv = client->priv;
3080
3081   if (mounts)
3082     g_object_ref (mounts);
3083
3084   g_mutex_lock (&priv->lock);
3085   old = priv->mount_points;
3086   priv->mount_points = mounts;
3087   g_mutex_unlock (&priv->lock);
3088
3089   if (old)
3090     g_object_unref (old);
3091 }
3092
3093 /**
3094  * gst_rtsp_client_get_mount_points:
3095  * @client: a #GstRTSPClient
3096  *
3097  * Get the #GstRTSPMountPoints object that @client uses to manage its sessions.
3098  *
3099  * Returns: (transfer full): a #GstRTSPMountPoints, unref after usage.
3100  */
3101 GstRTSPMountPoints *
3102 gst_rtsp_client_get_mount_points (GstRTSPClient * client)
3103 {
3104   GstRTSPClientPrivate *priv;
3105   GstRTSPMountPoints *result;
3106
3107   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
3108
3109   priv = client->priv;
3110
3111   g_mutex_lock (&priv->lock);
3112   if ((result = priv->mount_points))
3113     g_object_ref (result);
3114   g_mutex_unlock (&priv->lock);
3115
3116   return result;
3117 }
3118
3119 /**
3120  * gst_rtsp_client_set_auth:
3121  * @client: a #GstRTSPClient
3122  * @auth: (transfer none): a #GstRTSPAuth
3123  *
3124  * configure @auth to be used as the authentication manager of @client.
3125  */
3126 void
3127 gst_rtsp_client_set_auth (GstRTSPClient * client, GstRTSPAuth * auth)
3128 {
3129   GstRTSPClientPrivate *priv;
3130   GstRTSPAuth *old;
3131
3132   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
3133
3134   priv = client->priv;
3135
3136   if (auth)
3137     g_object_ref (auth);
3138
3139   g_mutex_lock (&priv->lock);
3140   old = priv->auth;
3141   priv->auth = auth;
3142   g_mutex_unlock (&priv->lock);
3143
3144   if (old)
3145     g_object_unref (old);
3146 }
3147
3148
3149 /**
3150  * gst_rtsp_client_get_auth:
3151  * @client: a #GstRTSPClient
3152  *
3153  * Get the #GstRTSPAuth used as the authentication manager of @client.
3154  *
3155  * Returns: (transfer full): the #GstRTSPAuth of @client. g_object_unref() after
3156  * usage.
3157  */
3158 GstRTSPAuth *
3159 gst_rtsp_client_get_auth (GstRTSPClient * client)
3160 {
3161   GstRTSPClientPrivate *priv;
3162   GstRTSPAuth *result;
3163
3164   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
3165
3166   priv = client->priv;
3167
3168   g_mutex_lock (&priv->lock);
3169   if ((result = priv->auth))
3170     g_object_ref (result);
3171   g_mutex_unlock (&priv->lock);
3172
3173   return result;
3174 }
3175
3176 /**
3177  * gst_rtsp_client_set_thread_pool:
3178  * @client: a #GstRTSPClient
3179  * @pool: (transfer none): a #GstRTSPThreadPool
3180  *
3181  * configure @pool to be used as the thread pool of @client.
3182  */
3183 void
3184 gst_rtsp_client_set_thread_pool (GstRTSPClient * client,
3185     GstRTSPThreadPool * pool)
3186 {
3187   GstRTSPClientPrivate *priv;
3188   GstRTSPThreadPool *old;
3189
3190   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
3191
3192   priv = client->priv;
3193
3194   if (pool)
3195     g_object_ref (pool);
3196
3197   g_mutex_lock (&priv->lock);
3198   old = priv->thread_pool;
3199   priv->thread_pool = pool;
3200   g_mutex_unlock (&priv->lock);
3201
3202   if (old)
3203     g_object_unref (old);
3204 }
3205
3206 /**
3207  * gst_rtsp_client_get_thread_pool:
3208  * @client: a #GstRTSPClient
3209  *
3210  * Get the #GstRTSPThreadPool used as the thread pool of @client.
3211  *
3212  * Returns: (transfer full): the #GstRTSPThreadPool of @client. g_object_unref() after
3213  * usage.
3214  */
3215 GstRTSPThreadPool *
3216 gst_rtsp_client_get_thread_pool (GstRTSPClient * client)
3217 {
3218   GstRTSPClientPrivate *priv;
3219   GstRTSPThreadPool *result;
3220
3221   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
3222
3223   priv = client->priv;
3224
3225   g_mutex_lock (&priv->lock);
3226   if ((result = priv->thread_pool))
3227     g_object_ref (result);
3228   g_mutex_unlock (&priv->lock);
3229
3230   return result;
3231 }
3232
3233 /**
3234  * gst_rtsp_client_set_connection:
3235  * @client: a #GstRTSPClient
3236  * @conn: (transfer full): a #GstRTSPConnection
3237  *
3238  * Set the #GstRTSPConnection of @client. This function takes ownership of
3239  * @conn.
3240  *
3241  * Returns: %TRUE on success.
3242  */
3243 gboolean
3244 gst_rtsp_client_set_connection (GstRTSPClient * client,
3245     GstRTSPConnection * conn)
3246 {
3247   GstRTSPClientPrivate *priv;
3248   GSocket *read_socket;
3249   GSocketAddress *address;
3250   GstRTSPUrl *url;
3251   GError *error = NULL;
3252
3253   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), FALSE);
3254   g_return_val_if_fail (conn != NULL, FALSE);
3255
3256   priv = client->priv;
3257
3258   read_socket = gst_rtsp_connection_get_read_socket (conn);
3259
3260   if (!(address = g_socket_get_local_address (read_socket, &error)))
3261     goto no_address;
3262
3263   g_free (priv->server_ip);
3264   /* keep the original ip that the client connected to */
3265   if (G_IS_INET_SOCKET_ADDRESS (address)) {
3266     GInetAddress *iaddr;
3267
3268     iaddr = g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (address));
3269
3270     /* socket might be ipv6 but adress still ipv4 */
3271     priv->is_ipv6 = g_inet_address_get_family (iaddr) == G_SOCKET_FAMILY_IPV6;
3272     priv->server_ip = g_inet_address_to_string (iaddr);
3273     g_object_unref (address);
3274   } else {
3275     priv->is_ipv6 = g_socket_get_family (read_socket) == G_SOCKET_FAMILY_IPV6;
3276     priv->server_ip = g_strdup ("unknown");
3277   }
3278
3279   GST_INFO ("client %p connected to server ip %s, ipv6 = %d", client,
3280       priv->server_ip, priv->is_ipv6);
3281
3282   url = gst_rtsp_connection_get_url (conn);
3283   GST_INFO ("added new client %p ip %s:%d", client, url->host, url->port);
3284
3285   priv->connection = conn;
3286
3287   return TRUE;
3288
3289   /* ERRORS */
3290 no_address:
3291   {
3292     GST_ERROR ("could not get local address %s", error->message);
3293     g_error_free (error);
3294     return FALSE;
3295   }
3296 }
3297
3298 /**
3299  * gst_rtsp_client_get_connection:
3300  * @client: a #GstRTSPClient
3301  *
3302  * Get the #GstRTSPConnection of @client.
3303  *
3304  * Returns: (transfer none): the #GstRTSPConnection of @client.
3305  * The connection object returned remains valid until the client is freed.
3306  */
3307 GstRTSPConnection *
3308 gst_rtsp_client_get_connection (GstRTSPClient * client)
3309 {
3310   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
3311
3312   return client->priv->connection;
3313 }
3314
3315 /**
3316  * gst_rtsp_client_set_send_func:
3317  * @client: a #GstRTSPClient
3318  * @func: (scope notified): a #GstRTSPClientSendFunc
3319  * @user_data: (closure): user data passed to @func
3320  * @notify: (allow-none): called when @user_data is no longer in use
3321  *
3322  * Set @func as the callback that will be called when a new message needs to be
3323  * sent to the client. @user_data is passed to @func and @notify is called when
3324  * @user_data is no longer in use.
3325  *
3326  * By default, the client will send the messages on the #GstRTSPConnection that
3327  * was configured with gst_rtsp_client_attach() was called.
3328  */
3329 void
3330 gst_rtsp_client_set_send_func (GstRTSPClient * client,
3331     GstRTSPClientSendFunc func, gpointer user_data, GDestroyNotify notify)
3332 {
3333   GstRTSPClientPrivate *priv;
3334   GDestroyNotify old_notify;
3335   gpointer old_data;
3336
3337   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
3338
3339   priv = client->priv;
3340
3341   g_mutex_lock (&priv->send_lock);
3342   priv->send_func = func;
3343   old_notify = priv->send_notify;
3344   old_data = priv->send_data;
3345   priv->send_notify = notify;
3346   priv->send_data = user_data;
3347   g_mutex_unlock (&priv->send_lock);
3348
3349   if (old_notify)
3350     old_notify (old_data);
3351 }
3352
3353 /**
3354  * gst_rtsp_client_handle_message:
3355  * @client: a #GstRTSPClient
3356  * @message: (transfer none): an #GstRTSPMessage
3357  *
3358  * Let the client handle @message.
3359  *
3360  * Returns: a #GstRTSPResult.
3361  */
3362 GstRTSPResult
3363 gst_rtsp_client_handle_message (GstRTSPClient * client,
3364     GstRTSPMessage * message)
3365 {
3366   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), GST_RTSP_EINVAL);
3367   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
3368
3369   switch (message->type) {
3370     case GST_RTSP_MESSAGE_REQUEST:
3371       handle_request (client, message);
3372       break;
3373     case GST_RTSP_MESSAGE_RESPONSE:
3374       handle_response (client, message);
3375       break;
3376     case GST_RTSP_MESSAGE_DATA:
3377       handle_data (client, message);
3378       break;
3379     default:
3380       break;
3381   }
3382   return GST_RTSP_OK;
3383 }
3384
3385 /**
3386  * gst_rtsp_client_send_message:
3387  * @client: a #GstRTSPClient
3388  * @session: (allow-none) (transfer none): a #GstRTSPSession to send
3389  *   the message to or %NULL
3390  * @message: (transfer none): The #GstRTSPMessage to send
3391  *
3392  * Send a message message to the remote end. @message must be a
3393  * #GST_RTSP_MESSAGE_REQUEST or a #GST_RTSP_MESSAGE_RESPONSE.
3394  */
3395 GstRTSPResult
3396 gst_rtsp_client_send_message (GstRTSPClient * client, GstRTSPSession * session,
3397     GstRTSPMessage * message)
3398 {
3399   GstRTSPContext sctx = { NULL }
3400   , *ctx;
3401   GstRTSPClientPrivate *priv;
3402
3403   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), GST_RTSP_EINVAL);
3404   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
3405   g_return_val_if_fail (message->type == GST_RTSP_MESSAGE_REQUEST ||
3406       message->type == GST_RTSP_MESSAGE_RESPONSE, GST_RTSP_EINVAL);
3407
3408   priv = client->priv;
3409
3410   if (!(ctx = gst_rtsp_context_get_current ())) {
3411     ctx = &sctx;
3412     ctx->auth = priv->auth;
3413     gst_rtsp_context_push_current (ctx);
3414   }
3415
3416   ctx->conn = priv->connection;
3417   ctx->client = client;
3418   ctx->session = session;
3419
3420   send_message (client, ctx, message, FALSE);
3421
3422   if (ctx == &sctx)
3423     gst_rtsp_context_pop_current (ctx);
3424
3425   return GST_RTSP_OK;
3426 }
3427
3428 static GstRTSPResult
3429 do_send_message (GstRTSPClient * client, GstRTSPMessage * message,
3430     gboolean close, gpointer user_data)
3431 {
3432   GstRTSPClientPrivate *priv = client->priv;
3433   GstRTSPResult ret;
3434   GTimeVal time;
3435
3436   time.tv_sec = 1;
3437   time.tv_usec = 0;
3438
3439   do {
3440     /* send the response and store the seq number so we can wait until it's
3441      * written to the client to close the connection */
3442     ret =
3443         gst_rtsp_watch_send_message (priv->watch, message,
3444         close ? &priv->close_seq : NULL);
3445     if (ret == GST_RTSP_OK)
3446       break;
3447
3448     if (ret != GST_RTSP_ENOMEM)
3449       goto error;
3450
3451     /* drop backlog */
3452     if (priv->drop_backlog)
3453       break;
3454
3455     /* queue was full, wait for more space */
3456     GST_DEBUG_OBJECT (client, "waiting for backlog");
3457     ret = gst_rtsp_watch_wait_backlog (priv->watch, &time);
3458     GST_DEBUG_OBJECT (client, "Resend due to backlog full");
3459   } while (ret != GST_RTSP_EINTR);
3460
3461   return ret;
3462
3463   /* ERRORS */
3464 error:
3465   {
3466     GST_DEBUG_OBJECT (client, "got error %d", ret);
3467     return ret;
3468   }
3469 }
3470
3471 static GstRTSPResult
3472 message_received (GstRTSPWatch * watch, GstRTSPMessage * message,
3473     gpointer user_data)
3474 {
3475   return gst_rtsp_client_handle_message (GST_RTSP_CLIENT (user_data), message);
3476 }
3477
3478 static GstRTSPResult
3479 message_sent (GstRTSPWatch * watch, guint cseq, gpointer user_data)
3480 {
3481   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3482   GstRTSPClientPrivate *priv = client->priv;
3483
3484   if (priv->close_seq && priv->close_seq == cseq) {
3485     GST_INFO ("client %p: send close message", client);
3486     priv->close_seq = 0;
3487     gst_rtsp_client_close (client);
3488   }
3489
3490   return GST_RTSP_OK;
3491 }
3492
3493 static GstRTSPResult
3494 closed (GstRTSPWatch * watch, gpointer user_data)
3495 {
3496   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3497   GstRTSPClientPrivate *priv = client->priv;
3498   const gchar *tunnelid;
3499
3500   GST_INFO ("client %p: connection closed", client);
3501
3502   if ((tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection))) {
3503     g_mutex_lock (&tunnels_lock);
3504     /* remove from tunnelids */
3505     g_hash_table_remove (tunnels, tunnelid);
3506     g_mutex_unlock (&tunnels_lock);
3507   }
3508
3509   gst_rtsp_watch_set_flushing (watch, TRUE);
3510   g_mutex_lock (&priv->watch_lock);
3511   gst_rtsp_client_set_send_func (client, NULL, NULL, NULL);
3512   g_mutex_unlock (&priv->watch_lock);
3513
3514   return GST_RTSP_OK;
3515 }
3516
3517 static GstRTSPResult
3518 error (GstRTSPWatch * watch, GstRTSPResult result, gpointer user_data)
3519 {
3520   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3521   gchar *str;
3522
3523   str = gst_rtsp_strresult (result);
3524   GST_INFO ("client %p: received an error %s", client, str);
3525   g_free (str);
3526
3527   return GST_RTSP_OK;
3528 }
3529
3530 static GstRTSPResult
3531 error_full (GstRTSPWatch * watch, GstRTSPResult result,
3532     GstRTSPMessage * message, guint id, gpointer user_data)
3533 {
3534   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3535   gchar *str;
3536
3537   str = gst_rtsp_strresult (result);
3538   GST_INFO
3539       ("client %p: error when handling message %p with id %d: %s",
3540       client, message, id, str);
3541   g_free (str);
3542
3543   return GST_RTSP_OK;
3544 }
3545
3546 static gboolean
3547 remember_tunnel (GstRTSPClient * client)
3548 {
3549   GstRTSPClientPrivate *priv = client->priv;
3550   const gchar *tunnelid;
3551
3552   /* store client in the pending tunnels */
3553   tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection);
3554   if (tunnelid == NULL)
3555     goto no_tunnelid;
3556
3557   GST_INFO ("client %p: inserting tunnel session %s", client, tunnelid);
3558
3559   /* we can't have two clients connecting with the same tunnelid */
3560   g_mutex_lock (&tunnels_lock);
3561   if (g_hash_table_lookup (tunnels, tunnelid))
3562     goto tunnel_existed;
3563
3564   g_hash_table_insert (tunnels, g_strdup (tunnelid), g_object_ref (client));
3565   g_mutex_unlock (&tunnels_lock);
3566
3567   return TRUE;
3568
3569   /* ERRORS */
3570 no_tunnelid:
3571   {
3572     GST_ERROR ("client %p: no tunnelid provided", client);
3573     return FALSE;
3574   }
3575 tunnel_existed:
3576   {
3577     g_mutex_unlock (&tunnels_lock);
3578     GST_ERROR ("client %p: tunnel session %s already existed", client,
3579         tunnelid);
3580     return FALSE;
3581   }
3582 }
3583
3584 static GstRTSPResult
3585 tunnel_lost (GstRTSPWatch * watch, gpointer user_data)
3586 {
3587   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3588   GstRTSPClientPrivate *priv = client->priv;
3589
3590   GST_WARNING ("client %p: tunnel lost (connection %p)", client,
3591       priv->connection);
3592
3593   /* ignore error, it'll only be a problem when the client does a POST again */
3594   remember_tunnel (client);
3595
3596   return GST_RTSP_OK;
3597 }
3598
3599 static gboolean
3600 handle_tunnel (GstRTSPClient * client)
3601 {
3602   GstRTSPClientPrivate *priv = client->priv;
3603   GstRTSPClient *oclient;
3604   GstRTSPClientPrivate *opriv;
3605   const gchar *tunnelid;
3606
3607   tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection);
3608   if (tunnelid == NULL)
3609     goto no_tunnelid;
3610
3611   /* check for previous tunnel */
3612   g_mutex_lock (&tunnels_lock);
3613   oclient = g_hash_table_lookup (tunnels, tunnelid);
3614
3615   if (oclient == NULL) {
3616     /* no previous tunnel, remember tunnel */
3617     g_hash_table_insert (tunnels, g_strdup (tunnelid), g_object_ref (client));
3618     g_mutex_unlock (&tunnels_lock);
3619
3620     GST_INFO ("client %p: no previous tunnel found, remembering tunnel (%p)",
3621         client, priv->connection);
3622   } else {
3623     /* merge both tunnels into the first client */
3624     /* remove the old client from the table. ref before because removing it will
3625      * remove the ref to it. */
3626     g_object_ref (oclient);
3627     g_hash_table_remove (tunnels, tunnelid);
3628     g_mutex_unlock (&tunnels_lock);
3629
3630     opriv = oclient->priv;
3631
3632     g_mutex_lock (&opriv->watch_lock);
3633     if (opriv->watch == NULL)
3634       goto tunnel_closed;
3635
3636     GST_INFO ("client %p: found previous tunnel %p (old %p, new %p)", client,
3637         oclient, opriv->connection, priv->connection);
3638
3639     gst_rtsp_connection_do_tunnel (opriv->connection, priv->connection);
3640     gst_rtsp_watch_reset (priv->watch);
3641     gst_rtsp_watch_reset (opriv->watch);
3642     g_mutex_unlock (&opriv->watch_lock);
3643     g_object_unref (oclient);
3644
3645     /* the old client owns the tunnel now, the new one will be freed */
3646     g_source_destroy ((GSource *) priv->watch);
3647     priv->watch = NULL;
3648     gst_rtsp_client_set_send_func (client, NULL, NULL, NULL);
3649   }
3650
3651   return TRUE;
3652
3653   /* ERRORS */
3654 no_tunnelid:
3655   {
3656     GST_ERROR ("client %p: no tunnelid provided", client);
3657     return FALSE;
3658   }
3659 tunnel_closed:
3660   {
3661     GST_ERROR ("client %p: tunnel session %s was closed", client, tunnelid);
3662     g_mutex_unlock (&opriv->watch_lock);
3663     g_object_unref (oclient);
3664     return FALSE;
3665   }
3666 }
3667
3668 static GstRTSPStatusCode
3669 tunnel_get (GstRTSPWatch * watch, gpointer user_data)
3670 {
3671   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3672
3673   GST_INFO ("client %p: tunnel get (connection %p)", client,
3674       client->priv->connection);
3675
3676   if (!handle_tunnel (client)) {
3677     return GST_RTSP_STS_SERVICE_UNAVAILABLE;
3678   }
3679
3680   return GST_RTSP_STS_OK;
3681 }
3682
3683 static GstRTSPResult
3684 tunnel_post (GstRTSPWatch * watch, gpointer user_data)
3685 {
3686   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3687
3688   GST_INFO ("client %p: tunnel post (connection %p)", client,
3689       client->priv->connection);
3690
3691   if (!handle_tunnel (client)) {
3692     return GST_RTSP_ERROR;
3693   }
3694
3695   return GST_RTSP_OK;
3696 }
3697
3698 static GstRTSPResult
3699 tunnel_http_response (GstRTSPWatch * watch, GstRTSPMessage * request,
3700     GstRTSPMessage * response, gpointer user_data)
3701 {
3702   GstRTSPClientClass *klass;
3703
3704   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3705   klass = GST_RTSP_CLIENT_GET_CLASS (client);
3706
3707   if (klass->tunnel_http_response) {
3708     klass->tunnel_http_response (client, request, response);
3709   }
3710
3711   return GST_RTSP_OK;
3712 }
3713
3714 static GstRTSPWatchFuncs watch_funcs = {
3715   message_received,
3716   message_sent,
3717   closed,
3718   error,
3719   tunnel_get,
3720   tunnel_post,
3721   error_full,
3722   tunnel_lost,
3723   tunnel_http_response
3724 };
3725
3726 static void
3727 client_watch_notify (GstRTSPClient * client)
3728 {
3729   GstRTSPClientPrivate *priv = client->priv;
3730
3731   GST_INFO ("client %p: watch destroyed", client);
3732   priv->watch = NULL;
3733   /* remove all sessions and so drop the extra client ref */
3734   gst_rtsp_client_session_filter (client, cleanup_session, NULL);
3735   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_CLOSED], 0, NULL);
3736   g_object_unref (client);
3737 }
3738
3739 /**
3740  * gst_rtsp_client_attach:
3741  * @client: a #GstRTSPClient
3742  * @context: (allow-none): a #GMainContext
3743  *
3744  * Attaches @client to @context. When the mainloop for @context is run, the
3745  * client will be dispatched. When @context is %NULL, the default context will be
3746  * used).
3747  *
3748  * This function should be called when the client properties and urls are fully
3749  * configured and the client is ready to start.
3750  *
3751  * Returns: the ID (greater than 0) for the source within the GMainContext.
3752  */
3753 guint
3754 gst_rtsp_client_attach (GstRTSPClient * client, GMainContext * context)
3755 {
3756   GstRTSPClientPrivate *priv;
3757   guint res;
3758
3759   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), 0);
3760   priv = client->priv;
3761   g_return_val_if_fail (priv->connection != NULL, 0);
3762   g_return_val_if_fail (priv->watch == NULL, 0);
3763
3764   /* make sure noone will free the context before the watch is destroyed */
3765   priv->watch_context = g_main_context_ref (context);
3766
3767   /* create watch for the connection and attach */
3768   priv->watch = gst_rtsp_watch_new (priv->connection, &watch_funcs,
3769       g_object_ref (client), (GDestroyNotify) client_watch_notify);
3770   gst_rtsp_client_set_send_func (client, do_send_message, priv->watch,
3771       (GDestroyNotify) gst_rtsp_watch_unref);
3772
3773   gst_rtsp_watch_set_send_backlog (priv->watch, 0, WATCH_BACKLOG_SIZE);
3774
3775   GST_INFO ("client %p: attaching to context %p", client, context);
3776   res = gst_rtsp_watch_attach (priv->watch, context);
3777
3778   return res;
3779 }
3780
3781 /**
3782  * gst_rtsp_client_session_filter:
3783  * @client: a #GstRTSPClient
3784  * @func: (scope call) (allow-none): a callback
3785  * @user_data: user data passed to @func
3786  *
3787  * Call @func for each session managed by @client. The result value of @func
3788  * determines what happens to the session. @func will be called with @client
3789  * locked so no further actions on @client can be performed from @func.
3790  *
3791  * If @func returns #GST_RTSP_FILTER_REMOVE, the session will be removed from
3792  * @client.
3793  *
3794  * If @func returns #GST_RTSP_FILTER_KEEP, the session will remain in @client.
3795  *
3796  * If @func returns #GST_RTSP_FILTER_REF, the session will remain in @client but
3797  * will also be added with an additional ref to the result #GList of this
3798  * function..
3799  *
3800  * When @func is %NULL, #GST_RTSP_FILTER_REF will be assumed for each session.
3801  *
3802  * Returns: (element-type GstRTSPSession) (transfer full): a #GList with all
3803  * sessions for which @func returned #GST_RTSP_FILTER_REF. After usage, each
3804  * element in the #GList should be unreffed before the list is freed.
3805  */
3806 GList *
3807 gst_rtsp_client_session_filter (GstRTSPClient * client,
3808     GstRTSPClientSessionFilterFunc func, gpointer user_data)
3809 {
3810   GstRTSPClientPrivate *priv;
3811   GList *result, *walk, *next;
3812   GHashTable *visited;
3813   guint cookie;
3814
3815   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
3816
3817   priv = client->priv;
3818
3819   result = NULL;
3820   if (func)
3821     visited = g_hash_table_new_full (NULL, NULL, g_object_unref, NULL);
3822
3823   g_mutex_lock (&priv->lock);
3824 restart:
3825   cookie = priv->sessions_cookie;
3826   for (walk = priv->sessions; walk; walk = next) {
3827     GstRTSPSession *sess = walk->data;
3828     GstRTSPFilterResult res;
3829     gboolean changed;
3830
3831     next = g_list_next (walk);
3832
3833     if (func) {
3834       /* only visit each session once */
3835       if (g_hash_table_contains (visited, sess))
3836         continue;
3837
3838       g_hash_table_add (visited, g_object_ref (sess));
3839       g_mutex_unlock (&priv->lock);
3840
3841       res = func (client, sess, user_data);
3842
3843       g_mutex_lock (&priv->lock);
3844     } else
3845       res = GST_RTSP_FILTER_REF;
3846
3847     changed = (cookie != priv->sessions_cookie);
3848
3849     switch (res) {
3850       case GST_RTSP_FILTER_REMOVE:
3851         /* stop watching the session and pretend it went away, if the list was
3852          * changed, we can't use the current list position, try to see if we
3853          * still have the session */
3854         client_unwatch_session (client, sess, changed ? NULL : walk);
3855         cookie = priv->sessions_cookie;
3856         break;
3857       case GST_RTSP_FILTER_REF:
3858         result = g_list_prepend (result, g_object_ref (sess));
3859         break;
3860       case GST_RTSP_FILTER_KEEP:
3861       default:
3862         break;
3863     }
3864     if (changed)
3865       goto restart;
3866   }
3867   g_mutex_unlock (&priv->lock);
3868
3869   if (func)
3870     g_hash_table_unref (visited);
3871
3872   return result;
3873 }