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