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