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