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