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