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