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