client: set session media to NULL without the lock
[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
1611   return TRUE;
1612
1613   /* ERRORS */
1614 parse_failed:
1615   {
1616     GST_DEBUG_OBJECT (client, "failed to parse MIKEY message");
1617     return FALSE;
1618   }
1619 invalid_map_type:
1620   {
1621     GST_DEBUG_OBJECT (client, "invalid map type %d", msg->map_type);
1622     goto cleanup_message;
1623   }
1624 no_crypto_sessions:
1625   {
1626     GST_DEBUG_OBJECT (client, "no crypto sessions");
1627     goto cleanup_message;
1628   }
1629 no_keys:
1630   {
1631     GST_DEBUG_OBJECT (client, "no keys found");
1632     goto cleanup_message;
1633   }
1634 unsupported_encryption:
1635   {
1636     GST_DEBUG_OBJECT (client, "unsupported key encryption");
1637     goto cleanup_message;
1638   }
1639 cleanup_message:
1640   {
1641     gst_mikey_message_unref (msg);
1642     return FALSE;
1643   }
1644 }
1645
1646 #define IS_STRIP_CHAR(c) (g_ascii_isspace ((guchar)(c)) || ((c) == '\"'))
1647
1648 static void
1649 strip_chars (gchar * str)
1650 {
1651   gchar *s;
1652   gsize len;
1653
1654   len = strlen (str);
1655   while (len--) {
1656     if (!IS_STRIP_CHAR (str[len]))
1657       break;
1658     str[len] = '\0';
1659   }
1660   for (s = str; *s && IS_STRIP_CHAR (*s); s++);
1661   memmove (str, s, len + 1);
1662 }
1663
1664 /* KeyMgmt = "KeyMgmt" ":" key-mgmt-spec 0*("," key-mgmt-spec)
1665  * key-mgmt-spec = "prot" "=" KMPID ";" ["uri" "=" %x22 URI %x22 ";"]
1666  */
1667 static gboolean
1668 handle_keymgmt (GstRTSPClient * client, GstRTSPContext * ctx, gchar * keymgmt)
1669 {
1670   gchar **specs;
1671   gint i, j;
1672
1673   specs = g_strsplit (keymgmt, ",", 0);
1674   for (i = 0; specs[i]; i++) {
1675     gchar **split;
1676
1677     split = g_strsplit (specs[i], ";", 0);
1678     for (j = 0; split[j]; j++) {
1679       g_strstrip (split[j]);
1680       if (g_str_has_prefix (split[j], "prot=")) {
1681         g_strstrip (split[j] + 5);
1682         if (!g_str_equal (split[j] + 5, "mikey"))
1683           break;
1684         GST_DEBUG ("found mikey");
1685       } else if (g_str_has_prefix (split[j], "uri=")) {
1686         strip_chars (split[j] + 4);
1687         GST_DEBUG ("found uri '%s'", split[j] + 4);
1688       } else if (g_str_has_prefix (split[j], "data=")) {
1689         guchar *data;
1690         gsize size;
1691         strip_chars (split[j] + 5);
1692         GST_DEBUG ("found data '%s'", split[j] + 5);
1693         data = g_base64_decode_inplace (split[j] + 5, &size);
1694         handle_mikey_data (client, ctx, data, size);
1695       }
1696     }
1697   }
1698   return TRUE;
1699 }
1700
1701 static gboolean
1702 handle_setup_request (GstRTSPClient * client, GstRTSPContext * ctx)
1703 {
1704   GstRTSPClientPrivate *priv = client->priv;
1705   GstRTSPResult res;
1706   GstRTSPUrl *uri;
1707   gchar *transport, *keymgmt;
1708   GstRTSPTransport *ct, *st;
1709   GstRTSPStatusCode code;
1710   GstRTSPSession *session;
1711   GstRTSPStreamTransport *trans;
1712   gchar *trans_str;
1713   GstRTSPSessionMedia *sessmedia;
1714   GstRTSPMedia *media;
1715   GstRTSPStream *stream;
1716   GstRTSPState rtspstate;
1717   GstRTSPClientClass *klass;
1718   gchar *path, *control;
1719   gint matched;
1720   gboolean new_session = FALSE;
1721
1722   if (!ctx->uri)
1723     goto no_uri;
1724
1725   uri = ctx->uri;
1726   klass = GST_RTSP_CLIENT_GET_CLASS (client);
1727   path = klass->make_path_from_uri (client, uri);
1728
1729   /* parse the transport */
1730   res =
1731       gst_rtsp_message_get_header (ctx->request, GST_RTSP_HDR_TRANSPORT,
1732       &transport, 0);
1733   if (res != GST_RTSP_OK)
1734     goto no_transport;
1735
1736   /* we create the session after parsing stuff so that we don't make
1737    * a session for malformed requests */
1738   if (priv->session_pool == NULL)
1739     goto no_pool;
1740
1741   session = ctx->session;
1742
1743   if (session) {
1744     g_object_ref (session);
1745     /* get a handle to the configuration of the media in the session, this can
1746      * return NULL if this is a new url to manage in this session. */
1747     sessmedia = gst_rtsp_session_get_media (session, path, &matched);
1748   } else {
1749     /* we need a new media configuration in this session */
1750     sessmedia = NULL;
1751   }
1752
1753   /* we have no session media, find one and manage it */
1754   if (sessmedia == NULL) {
1755     /* get a handle to the configuration of the media in the session */
1756     media = find_media (client, ctx, path, &matched);
1757   } else {
1758     if ((media = gst_rtsp_session_media_get_media (sessmedia)))
1759       g_object_ref (media);
1760     else
1761       goto media_not_found;
1762   }
1763   /* no media, not found then */
1764   if (media == NULL)
1765     goto media_not_found_no_reply;
1766
1767   if (path[matched] == '\0')
1768     goto control_not_found;
1769
1770   /* path is what matched. */
1771   path[matched] = '\0';
1772   /* control is remainder */
1773   control = &path[matched + 1];
1774
1775   /* find the stream now using the control part */
1776   stream = gst_rtsp_media_find_stream (media, control);
1777   if (stream == NULL)
1778     goto stream_not_found;
1779
1780   /* now we have a uri identifying a valid media and stream */
1781   ctx->stream = stream;
1782   ctx->media = media;
1783
1784   if (session == NULL) {
1785     /* create a session if this fails we probably reached our session limit or
1786      * something. */
1787     if (!(session = gst_rtsp_session_pool_create (priv->session_pool)))
1788       goto service_unavailable;
1789
1790     /* make sure this client is closed when the session is closed */
1791     client_watch_session (client, session);
1792
1793     new_session = TRUE;
1794     /* signal new session */
1795     g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_NEW_SESSION], 0,
1796         session);
1797
1798     ctx->session = session;
1799   }
1800
1801   if (!klass->configure_client_media (client, media, stream, ctx))
1802     goto configure_media_failed_no_reply;
1803
1804   gst_rtsp_transport_new (&ct);
1805
1806   /* parse and find a usable supported transport */
1807   if (!parse_transport (transport, stream, ct))
1808     goto unsupported_transports;
1809
1810   /* update the client transport */
1811   if (!klass->configure_client_transport (client, ctx, ct))
1812     goto unsupported_client_transport;
1813
1814   /* parse the keymgmt */
1815   if (gst_rtsp_message_get_header (ctx->request, GST_RTSP_HDR_KEYMGMT,
1816           &keymgmt, 0) == GST_RTSP_OK) {
1817     if (!handle_keymgmt (client, ctx, keymgmt))
1818       goto keymgmt_error;
1819   }
1820
1821   if (sessmedia == NULL) {
1822     /* manage the media in our session now, if not done already  */
1823     sessmedia = gst_rtsp_session_manage_media (session, path, media);
1824     /* if we stil have no media, error */
1825     if (sessmedia == NULL)
1826       goto sessmedia_unavailable;
1827   } else {
1828     g_object_unref (media);
1829   }
1830
1831   ctx->sessmedia = sessmedia;
1832
1833   /* set in the session media transport */
1834   trans = gst_rtsp_session_media_set_transport (sessmedia, stream, ct);
1835
1836   /* configure the url used to set this transport, this we will use when
1837    * generating the response for the PLAY request */
1838   gst_rtsp_stream_transport_set_url (trans, uri);
1839   /* configure keepalive for this transport */
1840   gst_rtsp_stream_transport_set_keepalive (trans,
1841       (GstRTSPKeepAliveFunc) do_keepalive, session, NULL);
1842
1843   if (ct->lower_transport == GST_RTSP_LOWER_TRANS_TCP) {
1844     /* our callbacks to send data on this TCP connection */
1845     gst_rtsp_stream_transport_set_callbacks (trans,
1846         (GstRTSPSendFunc) do_send_data,
1847         (GstRTSPSendFunc) do_send_data, client, NULL);
1848
1849     g_hash_table_insert (priv->transports,
1850         GINT_TO_POINTER (ct->interleaved.min), trans);
1851     g_hash_table_insert (priv->transports,
1852         GINT_TO_POINTER (ct->interleaved.max), trans);
1853   }
1854
1855   /* create and serialize the server transport */
1856   st = make_server_transport (client, ctx, ct);
1857   trans_str = gst_rtsp_transport_as_text (st);
1858   gst_rtsp_transport_free (st);
1859
1860   /* construct the response now */
1861   code = GST_RTSP_STS_OK;
1862   gst_rtsp_message_init_response (ctx->response, code,
1863       gst_rtsp_status_as_text (code), ctx->request);
1864
1865   gst_rtsp_message_add_header (ctx->response, GST_RTSP_HDR_TRANSPORT,
1866       trans_str);
1867   g_free (trans_str);
1868
1869   send_message (client, ctx, ctx->response, FALSE);
1870
1871   /* update the state */
1872   rtspstate = gst_rtsp_session_media_get_rtsp_state (sessmedia);
1873   switch (rtspstate) {
1874     case GST_RTSP_STATE_PLAYING:
1875     case GST_RTSP_STATE_RECORDING:
1876     case GST_RTSP_STATE_READY:
1877       /* no state change */
1878       break;
1879     default:
1880       gst_rtsp_session_media_set_rtsp_state (sessmedia, GST_RTSP_STATE_READY);
1881       break;
1882   }
1883   g_object_unref (session);
1884   g_free (path);
1885
1886   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_SETUP_REQUEST], 0, ctx);
1887
1888   return TRUE;
1889
1890   /* ERRORS */
1891 no_uri:
1892   {
1893     GST_ERROR ("client %p: no uri", client);
1894     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
1895     return FALSE;
1896   }
1897 no_transport:
1898   {
1899     GST_ERROR ("client %p: no transport", client);
1900     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, ctx);
1901     goto cleanup_path;
1902   }
1903 no_pool:
1904   {
1905     GST_ERROR ("client %p: no session pool configured", client);
1906     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
1907     goto cleanup_path;
1908   }
1909 media_not_found_no_reply:
1910   {
1911     GST_ERROR ("client %p: media '%s' not found", client, path);
1912     /* error reply is already sent */
1913     goto cleanup_path;
1914   }
1915 media_not_found:
1916   {
1917     GST_ERROR ("client %p: media '%s' not found", client, path);
1918     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
1919     goto cleanup_path;
1920   }
1921 control_not_found:
1922   {
1923     GST_ERROR ("client %p: no control in path '%s'", client, path);
1924     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
1925     g_object_unref (media);
1926     goto cleanup_path;
1927   }
1928 stream_not_found:
1929   {
1930     GST_ERROR ("client %p: stream '%s' not found", client, control);
1931     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
1932     g_object_unref (media);
1933     goto cleanup_path;
1934   }
1935 service_unavailable:
1936   {
1937     GST_ERROR ("client %p: can't create session", client);
1938     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, ctx);
1939     g_object_unref (media);
1940     goto cleanup_path;
1941   }
1942 sessmedia_unavailable:
1943   {
1944     GST_ERROR ("client %p: can't create session media", client);
1945     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, ctx);
1946     g_object_unref (media);
1947     goto cleanup_session;
1948   }
1949 configure_media_failed_no_reply:
1950   {
1951     GST_ERROR ("client %p: configure_media failed", client);
1952     /* error reply is already sent */
1953     goto cleanup_session;
1954   }
1955 unsupported_transports:
1956   {
1957     GST_ERROR ("client %p: unsupported transports", client);
1958     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, ctx);
1959     goto cleanup_transport;
1960   }
1961 unsupported_client_transport:
1962   {
1963     GST_ERROR ("client %p: unsupported client transport", client);
1964     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, ctx);
1965     goto cleanup_transport;
1966   }
1967 keymgmt_error:
1968   {
1969     GST_ERROR ("client %p: keymgmt error", client);
1970     send_generic_response (client, GST_RTSP_STS_KEY_MANAGEMENT_FAILURE, ctx);
1971     goto cleanup_transport;
1972   }
1973   {
1974   cleanup_transport:
1975     gst_rtsp_transport_free (ct);
1976   cleanup_session:
1977     if (new_session)
1978       gst_rtsp_session_pool_remove (priv->session_pool, session);
1979     g_object_unref (session);
1980   cleanup_path:
1981     g_free (path);
1982     return FALSE;
1983   }
1984 }
1985
1986 static GstSDPMessage *
1987 create_sdp (GstRTSPClient * client, GstRTSPMedia * media)
1988 {
1989   GstRTSPClientPrivate *priv = client->priv;
1990   GstSDPMessage *sdp;
1991   GstSDPInfo info;
1992   const gchar *proto;
1993
1994   gst_sdp_message_new (&sdp);
1995
1996   /* some standard things first */
1997   gst_sdp_message_set_version (sdp, "0");
1998
1999   if (priv->is_ipv6)
2000     proto = "IP6";
2001   else
2002     proto = "IP4";
2003
2004   gst_sdp_message_set_origin (sdp, "-", "1188340656180883", "1", "IN", proto,
2005       priv->server_ip);
2006
2007   gst_sdp_message_set_session_name (sdp, "Session streamed with GStreamer");
2008   gst_sdp_message_set_information (sdp, "rtsp-server");
2009   gst_sdp_message_add_time (sdp, "0", "0", NULL);
2010   gst_sdp_message_add_attribute (sdp, "tool", "GStreamer");
2011   gst_sdp_message_add_attribute (sdp, "type", "broadcast");
2012   gst_sdp_message_add_attribute (sdp, "control", "*");
2013
2014   info.is_ipv6 = priv->is_ipv6;
2015   info.server_ip = priv->server_ip;
2016
2017   /* create an SDP for the media object */
2018   if (!gst_rtsp_media_setup_sdp (media, sdp, &info))
2019     goto no_sdp;
2020
2021   return sdp;
2022
2023   /* ERRORS */
2024 no_sdp:
2025   {
2026     GST_ERROR ("client %p: could not create SDP", client);
2027     gst_sdp_message_free (sdp);
2028     return NULL;
2029   }
2030 }
2031
2032 /* for the describe we must generate an SDP */
2033 static gboolean
2034 handle_describe_request (GstRTSPClient * client, GstRTSPContext * ctx)
2035 {
2036   GstRTSPClientPrivate *priv = client->priv;
2037   GstRTSPResult res;
2038   GstSDPMessage *sdp;
2039   guint i;
2040   gchar *path, *str;
2041   GstRTSPMedia *media;
2042   GstRTSPClientClass *klass;
2043
2044   klass = GST_RTSP_CLIENT_GET_CLASS (client);
2045
2046   if (!ctx->uri)
2047     goto no_uri;
2048
2049   /* check what kind of format is accepted, we don't really do anything with it
2050    * and always return SDP for now. */
2051   for (i = 0;; i++) {
2052     gchar *accept;
2053
2054     res =
2055         gst_rtsp_message_get_header (ctx->request, GST_RTSP_HDR_ACCEPT,
2056         &accept, i);
2057     if (res == GST_RTSP_ENOTIMPL)
2058       break;
2059
2060     if (g_ascii_strcasecmp (accept, "application/sdp") == 0)
2061       break;
2062   }
2063
2064   if (!priv->mount_points)
2065     goto no_mount_points;
2066
2067   if (!(path = gst_rtsp_mount_points_make_path (priv->mount_points, ctx->uri)))
2068     goto no_path;
2069
2070   /* find the media object for the uri */
2071   if (!(media = find_media (client, ctx, path, NULL)))
2072     goto no_media;
2073
2074   /* create an SDP for the media object on this client */
2075   if (!(sdp = klass->create_sdp (client, media)))
2076     goto no_sdp;
2077
2078   /* we suspend after the describe */
2079   gst_rtsp_media_suspend (media);
2080   g_object_unref (media);
2081
2082   gst_rtsp_message_init_response (ctx->response, GST_RTSP_STS_OK,
2083       gst_rtsp_status_as_text (GST_RTSP_STS_OK), ctx->request);
2084
2085   gst_rtsp_message_add_header (ctx->response, GST_RTSP_HDR_CONTENT_TYPE,
2086       "application/sdp");
2087
2088   /* content base for some clients that might screw up creating the setup uri */
2089   str = make_base_url (client, ctx->uri, path);
2090   g_free (path);
2091
2092   GST_INFO ("adding content-base: %s", str);
2093   gst_rtsp_message_take_header (ctx->response, GST_RTSP_HDR_CONTENT_BASE, str);
2094
2095   /* add SDP to the response body */
2096   str = gst_sdp_message_as_text (sdp);
2097   gst_rtsp_message_take_body (ctx->response, (guint8 *) str, strlen (str));
2098   gst_sdp_message_free (sdp);
2099
2100   send_message (client, ctx, ctx->response, FALSE);
2101
2102   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_DESCRIBE_REQUEST],
2103       0, ctx);
2104
2105   return TRUE;
2106
2107   /* ERRORS */
2108 no_uri:
2109   {
2110     GST_ERROR ("client %p: no uri", client);
2111     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
2112     return FALSE;
2113   }
2114 no_mount_points:
2115   {
2116     GST_ERROR ("client %p: no mount points configured", client);
2117     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
2118     return FALSE;
2119   }
2120 no_path:
2121   {
2122     GST_ERROR ("client %p: can't find path for url", client);
2123     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
2124     return FALSE;
2125   }
2126 no_media:
2127   {
2128     GST_ERROR ("client %p: no media", client);
2129     g_free (path);
2130     /* error reply is already sent */
2131     return FALSE;
2132   }
2133 no_sdp:
2134   {
2135     GST_ERROR ("client %p: can't create SDP", client);
2136     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, ctx);
2137     g_free (path);
2138     g_object_unref (media);
2139     return FALSE;
2140   }
2141 }
2142
2143 static gboolean
2144 handle_options_request (GstRTSPClient * client, GstRTSPContext * ctx)
2145 {
2146   GstRTSPMethod options;
2147   gchar *str;
2148
2149   options = GST_RTSP_DESCRIBE |
2150       GST_RTSP_OPTIONS |
2151       GST_RTSP_PAUSE |
2152       GST_RTSP_PLAY |
2153       GST_RTSP_SETUP |
2154       GST_RTSP_GET_PARAMETER | GST_RTSP_SET_PARAMETER | GST_RTSP_TEARDOWN;
2155
2156   str = gst_rtsp_options_as_text (options);
2157
2158   gst_rtsp_message_init_response (ctx->response, GST_RTSP_STS_OK,
2159       gst_rtsp_status_as_text (GST_RTSP_STS_OK), ctx->request);
2160
2161   gst_rtsp_message_add_header (ctx->response, GST_RTSP_HDR_PUBLIC, str);
2162   g_free (str);
2163
2164   send_message (client, ctx, ctx->response, FALSE);
2165
2166   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_OPTIONS_REQUEST],
2167       0, ctx);
2168
2169   return TRUE;
2170 }
2171
2172 /* remove duplicate and trailing '/' */
2173 static void
2174 sanitize_uri (GstRTSPUrl * uri)
2175 {
2176   gint i, len;
2177   gchar *s, *d;
2178   gboolean have_slash, prev_slash;
2179
2180   s = d = uri->abspath;
2181   len = strlen (uri->abspath);
2182
2183   prev_slash = FALSE;
2184
2185   for (i = 0; i < len; i++) {
2186     have_slash = s[i] == '/';
2187     *d = s[i];
2188     if (!have_slash || !prev_slash)
2189       d++;
2190     prev_slash = have_slash;
2191   }
2192   len = d - uri->abspath;
2193   /* don't remove the first slash if that's the only thing left */
2194   if (len > 1 && *(d - 1) == '/')
2195     d--;
2196   *d = '\0';
2197 }
2198
2199 /* is called when the session is removed from its session pool. */
2200 static void
2201 client_session_removed (GstRTSPSessionPool * pool, GstRTSPSession * session,
2202     GstRTSPClient * client)
2203 {
2204   GstRTSPClientPrivate *priv = client->priv;
2205
2206   GST_INFO ("client %p: session %p removed", client, session);
2207
2208   g_mutex_lock (&priv->lock);
2209   if (priv->watch != NULL)
2210     gst_rtsp_watch_set_send_backlog (priv->watch, 0, 0);
2211   client_unwatch_session (client, session, NULL);
2212   if (priv->watch != NULL)
2213     gst_rtsp_watch_set_send_backlog (priv->watch, 0, WATCH_BACKLOG_SIZE);
2214   g_mutex_unlock (&priv->lock);
2215 }
2216
2217 /* Returns TRUE if there are no Require headers, otherwise returns FALSE
2218  * and also returns a newly-allocated string of (comma-separated) unsupported
2219  * options in the unsupported_reqs variable .
2220  *
2221  * There may be multiple Require headers, but we must send one single
2222  * Unsupported header with all the unsupported options as response. If
2223  * an incoming Require header contained a comma-separated list of options
2224  * GstRtspConnection will already have split that list up into multiple
2225  * headers.
2226  *
2227  * TODO: allow the application to decide what features are supported
2228  */
2229 static gboolean
2230 check_request_requirements (GstRTSPMessage * msg, gchar ** unsupported_reqs)
2231 {
2232   GstRTSPResult res;
2233   GPtrArray *arr = NULL;
2234   gchar *reqs = NULL;
2235   gint i;
2236
2237   i = 0;
2238   do {
2239     res = gst_rtsp_message_get_header (msg, GST_RTSP_HDR_REQUIRE, &reqs, i++);
2240
2241     if (res == GST_RTSP_ENOTIMPL)
2242       break;
2243
2244     if (arr == NULL)
2245       arr = g_ptr_array_new_with_free_func ((GDestroyNotify) g_free);
2246
2247     g_ptr_array_add (arr, g_strdup (reqs));
2248   }
2249   while (TRUE);
2250
2251   /* if we don't have any Require headers at all, all is fine */
2252   if (i == 1)
2253     return TRUE;
2254
2255   /* otherwise we've now processed at all the Require headers */
2256   g_ptr_array_add (arr, NULL);
2257
2258   /* for now we don't commit to supporting anything, so will just report
2259    * all of the required options as unsupported */
2260   *unsupported_reqs = g_strjoinv (", ", (gchar **) arr->pdata);
2261
2262   g_ptr_array_unref (arr);
2263   return FALSE;
2264 }
2265
2266 static void
2267 handle_request (GstRTSPClient * client, GstRTSPMessage * request)
2268 {
2269   GstRTSPClientPrivate *priv = client->priv;
2270   GstRTSPMethod method;
2271   const gchar *uristr;
2272   GstRTSPUrl *uri = NULL;
2273   GstRTSPVersion version;
2274   GstRTSPResult res;
2275   GstRTSPSession *session = NULL;
2276   GstRTSPContext sctx = { NULL }, *ctx;
2277   GstRTSPMessage response = { 0 };
2278   gchar *unsupported_reqs = NULL;
2279   gchar *sessid;
2280
2281   if (!(ctx = gst_rtsp_context_get_current ())) {
2282     ctx = &sctx;
2283     ctx->auth = priv->auth;
2284     gst_rtsp_context_push_current (ctx);
2285   }
2286
2287   ctx->conn = priv->connection;
2288   ctx->client = client;
2289   ctx->request = request;
2290   ctx->response = &response;
2291
2292   if (gst_debug_category_get_threshold (rtsp_client_debug) >= GST_LEVEL_LOG) {
2293     gst_rtsp_message_dump (request);
2294   }
2295
2296   gst_rtsp_message_parse_request (request, &method, &uristr, &version);
2297
2298   GST_INFO ("client %p: received a request %s %s %s", client,
2299       gst_rtsp_method_as_text (method), uristr,
2300       gst_rtsp_version_as_text (version));
2301
2302   /* we can only handle 1.0 requests */
2303   if (version != GST_RTSP_VERSION_1_0)
2304     goto not_supported;
2305
2306   ctx->method = method;
2307
2308   /* we always try to parse the url first */
2309   if (strcmp (uristr, "*") == 0) {
2310     /* special case where we have * as uri, keep uri = NULL */
2311   } else if (gst_rtsp_url_parse (uristr, &uri) != GST_RTSP_OK) {
2312     /* check if the uristr is an absolute path <=> scheme and host information
2313      * is missing */
2314     gchar *scheme;
2315
2316     scheme = g_uri_parse_scheme (uristr);
2317     if (scheme == NULL && g_str_has_prefix (uristr, "/")) {
2318       gchar *absolute_uristr = NULL;
2319
2320       GST_WARNING_OBJECT (client, "request doesn't contain absolute url");
2321       if (priv->server_ip == NULL) {
2322         GST_WARNING_OBJECT (client, "host information missing");
2323         goto bad_request;
2324       }
2325
2326       absolute_uristr =
2327           g_strdup_printf ("rtsp://%s%s", priv->server_ip, uristr);
2328
2329       GST_DEBUG_OBJECT (client, "absolute url: %s", absolute_uristr);
2330       if (gst_rtsp_url_parse (absolute_uristr, &uri) != GST_RTSP_OK) {
2331         g_free (absolute_uristr);
2332         goto bad_request;
2333       }
2334       g_free (absolute_uristr);
2335     } else {
2336       g_free (scheme);
2337       goto bad_request;
2338     }
2339   }
2340
2341   /* get the session if there is any */
2342   res = gst_rtsp_message_get_header (request, GST_RTSP_HDR_SESSION, &sessid, 0);
2343   if (res == GST_RTSP_OK) {
2344     if (priv->session_pool == NULL)
2345       goto no_pool;
2346
2347     /* we had a session in the request, find it again */
2348     if (!(session = gst_rtsp_session_pool_find (priv->session_pool, sessid)))
2349       goto session_not_found;
2350
2351     /* we add the session to the client list of watched sessions. When a session
2352      * disappears because it times out, we will be notified. If all sessions are
2353      * gone, we will close the connection */
2354     client_watch_session (client, session);
2355   }
2356
2357   /* sanitize the uri */
2358   if (uri)
2359     sanitize_uri (uri);
2360   ctx->uri = uri;
2361   ctx->session = session;
2362
2363   if (!gst_rtsp_auth_check (GST_RTSP_AUTH_CHECK_URL))
2364     goto not_authorized;
2365
2366   /* handle any 'Require' headers */
2367   if (!check_request_requirements (ctx->request, &unsupported_reqs))
2368     goto unsupported_requirement;
2369
2370   /* the backlog must be unlimited while processing requests.
2371    * the causes of this are two cases of deadlocks while streaming over TCP:
2372    *
2373    * 1. consider the scenario where the media pipeline's streaming thread
2374    * is blocking in the appsink (taking the appsink's preroll lock) because
2375    * the backlog is full. when a PAUSE request is received by the RTSP
2376    * client thread then the the state of the session media ought to change
2377    * to PAUSED. while most elements in the pipeline can change state this
2378    * can never happen for the appsink since its preroll lock is taken by
2379    * another thread.
2380    *
2381    * 2. consider the scenario where the media pipeline's streaming thread
2382    * is blocking in the appsink new_sample callback (taking the send lock
2383    * in RTSP client) because the backlog is full. when e.g. a GET request
2384    * is received by the RTSP client thread then a response ought to be sent
2385    * but this can never happen since it requires taking the send lock
2386    * already taken by another thread.
2387    *
2388    * the reason that the backlog is never emptied is that the source used
2389    * for dequeing messages from the backlog is never dispatched because it
2390    * is attached to the same mainloop as the source receving RTSP requests and
2391    * therefore run by the RTSP client thread which is alreayd blocking.
2392    *
2393    * without significant changes the easiest way to cope with this is to
2394    * not block indefinitely when the backlog is full, but rather let the
2395    * backlog grow in size. this in effect means that there can not be any
2396    * upper boundary on its size.
2397    */
2398   if (priv->watch != NULL)
2399     gst_rtsp_watch_set_send_backlog (priv->watch, 0, 0);
2400
2401   /* now see what is asked and dispatch to a dedicated handler */
2402   switch (method) {
2403     case GST_RTSP_OPTIONS:
2404       handle_options_request (client, ctx);
2405       break;
2406     case GST_RTSP_DESCRIBE:
2407       handle_describe_request (client, ctx);
2408       break;
2409     case GST_RTSP_SETUP:
2410       handle_setup_request (client, ctx);
2411       break;
2412     case GST_RTSP_PLAY:
2413       handle_play_request (client, ctx);
2414       break;
2415     case GST_RTSP_PAUSE:
2416       handle_pause_request (client, ctx);
2417       break;
2418     case GST_RTSP_TEARDOWN:
2419       handle_teardown_request (client, ctx);
2420       break;
2421     case GST_RTSP_SET_PARAMETER:
2422       handle_set_param_request (client, ctx);
2423       break;
2424     case GST_RTSP_GET_PARAMETER:
2425       handle_get_param_request (client, ctx);
2426       break;
2427     case GST_RTSP_ANNOUNCE:
2428     case GST_RTSP_RECORD:
2429     case GST_RTSP_REDIRECT:
2430       if (priv->watch != NULL)
2431         gst_rtsp_watch_set_send_backlog (priv->watch, 0, WATCH_BACKLOG_SIZE);
2432       goto not_implemented;
2433     case GST_RTSP_INVALID:
2434     default:
2435       if (priv->watch != NULL)
2436         gst_rtsp_watch_set_send_backlog (priv->watch, 0, WATCH_BACKLOG_SIZE);
2437       goto bad_request;
2438   }
2439
2440   if (priv->watch != NULL)
2441     gst_rtsp_watch_set_send_backlog (priv->watch, 0, WATCH_BACKLOG_SIZE);
2442
2443 done:
2444   if (ctx == &sctx)
2445     gst_rtsp_context_pop_current (ctx);
2446   if (session)
2447     g_object_unref (session);
2448   if (uri)
2449     gst_rtsp_url_free (uri);
2450   return;
2451
2452   /* ERRORS */
2453 not_supported:
2454   {
2455     GST_ERROR ("client %p: version %d not supported", client, version);
2456     send_generic_response (client, GST_RTSP_STS_RTSP_VERSION_NOT_SUPPORTED,
2457         ctx);
2458     goto done;
2459   }
2460 bad_request:
2461   {
2462     GST_ERROR ("client %p: bad request", client);
2463     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
2464     goto done;
2465   }
2466 no_pool:
2467   {
2468     GST_ERROR ("client %p: no pool configured", client);
2469     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
2470     goto done;
2471   }
2472 session_not_found:
2473   {
2474     GST_ERROR ("client %p: session not found", client);
2475     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
2476     goto done;
2477   }
2478 not_authorized:
2479   {
2480     GST_ERROR ("client %p: not allowed", client);
2481     /* error reply is already sent */
2482     goto done;
2483   }
2484 unsupported_requirement:
2485   {
2486     GST_ERROR ("client %p: Required option is not supported (%s)", client,
2487         unsupported_reqs);
2488     send_option_not_supported_response (client, ctx, unsupported_reqs);
2489     g_free (unsupported_reqs);
2490     goto done;
2491   }
2492 not_implemented:
2493   {
2494     GST_ERROR ("client %p: method %d not implemented", client, method);
2495     send_generic_response (client, GST_RTSP_STS_NOT_IMPLEMENTED, ctx);
2496     goto done;
2497   }
2498 }
2499
2500
2501 static void
2502 handle_response (GstRTSPClient * client, GstRTSPMessage * response)
2503 {
2504   GstRTSPClientPrivate *priv = client->priv;
2505   GstRTSPResult res;
2506   GstRTSPSession *session = NULL;
2507   GstRTSPContext sctx = { NULL }, *ctx;
2508   gchar *sessid;
2509
2510   if (!(ctx = gst_rtsp_context_get_current ())) {
2511     ctx = &sctx;
2512     ctx->auth = priv->auth;
2513     gst_rtsp_context_push_current (ctx);
2514   }
2515
2516   ctx->conn = priv->connection;
2517   ctx->client = client;
2518   ctx->request = NULL;
2519   ctx->uri = NULL;
2520   ctx->method = GST_RTSP_INVALID;
2521   ctx->response = response;
2522
2523   if (gst_debug_category_get_threshold (rtsp_client_debug) >= GST_LEVEL_LOG) {
2524     gst_rtsp_message_dump (response);
2525   }
2526
2527   GST_INFO ("client %p: received a response", client);
2528
2529   /* get the session if there is any */
2530   res =
2531       gst_rtsp_message_get_header (response, GST_RTSP_HDR_SESSION, &sessid, 0);
2532   if (res == GST_RTSP_OK) {
2533     if (priv->session_pool == NULL)
2534       goto no_pool;
2535
2536     /* we had a session in the request, find it again */
2537     if (!(session = gst_rtsp_session_pool_find (priv->session_pool, sessid)))
2538       goto session_not_found;
2539
2540     /* we add the session to the client list of watched sessions. When a session
2541      * disappears because it times out, we will be notified. If all sessions are
2542      * gone, we will close the connection */
2543     client_watch_session (client, session);
2544   }
2545
2546   ctx->session = session;
2547
2548   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_HANDLE_RESPONSE],
2549       0, ctx);
2550
2551 done:
2552   if (ctx == &sctx)
2553     gst_rtsp_context_pop_current (ctx);
2554   if (session)
2555     g_object_unref (session);
2556   return;
2557
2558 no_pool:
2559   {
2560     GST_ERROR ("client %p: no pool configured", client);
2561     goto done;
2562   }
2563 session_not_found:
2564   {
2565     GST_ERROR ("client %p: session not found", client);
2566     goto done;
2567   }
2568 }
2569
2570 static void
2571 handle_data (GstRTSPClient * client, GstRTSPMessage * message)
2572 {
2573   GstRTSPClientPrivate *priv = client->priv;
2574   GstRTSPResult res;
2575   guint8 channel;
2576   guint8 *data;
2577   guint size;
2578   GstBuffer *buffer;
2579   GstRTSPStreamTransport *trans;
2580
2581   /* find the stream for this message */
2582   res = gst_rtsp_message_parse_data (message, &channel);
2583   if (res != GST_RTSP_OK)
2584     return;
2585
2586   gst_rtsp_message_steal_body (message, &data, &size);
2587
2588   buffer = gst_buffer_new_wrapped (data, size);
2589
2590   trans =
2591       g_hash_table_lookup (priv->transports, GINT_TO_POINTER ((gint) channel));
2592   if (trans) {
2593     /* dispatch to the stream based on the channel number */
2594     gst_rtsp_stream_transport_recv_data (trans, channel, buffer);
2595   } else {
2596     gst_buffer_unref (buffer);
2597   }
2598 }
2599
2600 /**
2601  * gst_rtsp_client_set_session_pool:
2602  * @client: a #GstRTSPClient
2603  * @pool: (transfer none): a #GstRTSPSessionPool
2604  *
2605  * Set @pool as the sessionpool for @client which it will use to find
2606  * or allocate sessions. the sessionpool is usually inherited from the server
2607  * that created the client but can be overridden later.
2608  */
2609 void
2610 gst_rtsp_client_set_session_pool (GstRTSPClient * client,
2611     GstRTSPSessionPool * pool)
2612 {
2613   GstRTSPSessionPool *old;
2614   GstRTSPClientPrivate *priv;
2615
2616   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2617
2618   priv = client->priv;
2619
2620   if (pool)
2621     g_object_ref (pool);
2622
2623   g_mutex_lock (&priv->lock);
2624   old = priv->session_pool;
2625   priv->session_pool = pool;
2626
2627   if (priv->session_removed_id) {
2628     g_signal_handler_disconnect (old, priv->session_removed_id);
2629     priv->session_removed_id = 0;
2630   }
2631   g_mutex_unlock (&priv->lock);
2632
2633   /* FIXME, should remove all sessions from the old pool for this client */
2634   if (old)
2635     g_object_unref (old);
2636 }
2637
2638 /**
2639  * gst_rtsp_client_get_session_pool:
2640  * @client: a #GstRTSPClient
2641  *
2642  * Get the #GstRTSPSessionPool object that @client uses to manage its sessions.
2643  *
2644  * Returns: (transfer full): a #GstRTSPSessionPool, unref after usage.
2645  */
2646 GstRTSPSessionPool *
2647 gst_rtsp_client_get_session_pool (GstRTSPClient * client)
2648 {
2649   GstRTSPClientPrivate *priv;
2650   GstRTSPSessionPool *result;
2651
2652   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2653
2654   priv = client->priv;
2655
2656   g_mutex_lock (&priv->lock);
2657   if ((result = priv->session_pool))
2658     g_object_ref (result);
2659   g_mutex_unlock (&priv->lock);
2660
2661   return result;
2662 }
2663
2664 /**
2665  * gst_rtsp_client_set_mount_points:
2666  * @client: a #GstRTSPClient
2667  * @mounts: (transfer none): a #GstRTSPMountPoints
2668  *
2669  * Set @mounts as the mount points for @client which it will use to map urls
2670  * to media streams. These mount points are usually inherited from the server that
2671  * created the client but can be overriden later.
2672  */
2673 void
2674 gst_rtsp_client_set_mount_points (GstRTSPClient * client,
2675     GstRTSPMountPoints * mounts)
2676 {
2677   GstRTSPClientPrivate *priv;
2678   GstRTSPMountPoints *old;
2679
2680   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2681
2682   priv = client->priv;
2683
2684   if (mounts)
2685     g_object_ref (mounts);
2686
2687   g_mutex_lock (&priv->lock);
2688   old = priv->mount_points;
2689   priv->mount_points = mounts;
2690   g_mutex_unlock (&priv->lock);
2691
2692   if (old)
2693     g_object_unref (old);
2694 }
2695
2696 /**
2697  * gst_rtsp_client_get_mount_points:
2698  * @client: a #GstRTSPClient
2699  *
2700  * Get the #GstRTSPMountPoints object that @client uses to manage its sessions.
2701  *
2702  * Returns: (transfer full): a #GstRTSPMountPoints, unref after usage.
2703  */
2704 GstRTSPMountPoints *
2705 gst_rtsp_client_get_mount_points (GstRTSPClient * client)
2706 {
2707   GstRTSPClientPrivate *priv;
2708   GstRTSPMountPoints *result;
2709
2710   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2711
2712   priv = client->priv;
2713
2714   g_mutex_lock (&priv->lock);
2715   if ((result = priv->mount_points))
2716     g_object_ref (result);
2717   g_mutex_unlock (&priv->lock);
2718
2719   return result;
2720 }
2721
2722 /**
2723  * gst_rtsp_client_set_auth:
2724  * @client: a #GstRTSPClient
2725  * @auth: (transfer none): a #GstRTSPAuth
2726  *
2727  * configure @auth to be used as the authentication manager of @client.
2728  */
2729 void
2730 gst_rtsp_client_set_auth (GstRTSPClient * client, GstRTSPAuth * auth)
2731 {
2732   GstRTSPClientPrivate *priv;
2733   GstRTSPAuth *old;
2734
2735   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2736
2737   priv = client->priv;
2738
2739   if (auth)
2740     g_object_ref (auth);
2741
2742   g_mutex_lock (&priv->lock);
2743   old = priv->auth;
2744   priv->auth = auth;
2745   g_mutex_unlock (&priv->lock);
2746
2747   if (old)
2748     g_object_unref (old);
2749 }
2750
2751
2752 /**
2753  * gst_rtsp_client_get_auth:
2754  * @client: a #GstRTSPClient
2755  *
2756  * Get the #GstRTSPAuth used as the authentication manager of @client.
2757  *
2758  * Returns: (transfer full): the #GstRTSPAuth of @client. g_object_unref() after
2759  * usage.
2760  */
2761 GstRTSPAuth *
2762 gst_rtsp_client_get_auth (GstRTSPClient * client)
2763 {
2764   GstRTSPClientPrivate *priv;
2765   GstRTSPAuth *result;
2766
2767   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2768
2769   priv = client->priv;
2770
2771   g_mutex_lock (&priv->lock);
2772   if ((result = priv->auth))
2773     g_object_ref (result);
2774   g_mutex_unlock (&priv->lock);
2775
2776   return result;
2777 }
2778
2779 /**
2780  * gst_rtsp_client_set_thread_pool:
2781  * @client: a #GstRTSPClient
2782  * @pool: (transfer none): a #GstRTSPThreadPool
2783  *
2784  * configure @pool to be used as the thread pool of @client.
2785  */
2786 void
2787 gst_rtsp_client_set_thread_pool (GstRTSPClient * client,
2788     GstRTSPThreadPool * pool)
2789 {
2790   GstRTSPClientPrivate *priv;
2791   GstRTSPThreadPool *old;
2792
2793   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2794
2795   priv = client->priv;
2796
2797   if (pool)
2798     g_object_ref (pool);
2799
2800   g_mutex_lock (&priv->lock);
2801   old = priv->thread_pool;
2802   priv->thread_pool = pool;
2803   g_mutex_unlock (&priv->lock);
2804
2805   if (old)
2806     g_object_unref (old);
2807 }
2808
2809 /**
2810  * gst_rtsp_client_get_thread_pool:
2811  * @client: a #GstRTSPClient
2812  *
2813  * Get the #GstRTSPThreadPool used as the thread pool of @client.
2814  *
2815  * Returns: (transfer full): the #GstRTSPThreadPool of @client. g_object_unref() after
2816  * usage.
2817  */
2818 GstRTSPThreadPool *
2819 gst_rtsp_client_get_thread_pool (GstRTSPClient * client)
2820 {
2821   GstRTSPClientPrivate *priv;
2822   GstRTSPThreadPool *result;
2823
2824   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2825
2826   priv = client->priv;
2827
2828   g_mutex_lock (&priv->lock);
2829   if ((result = priv->thread_pool))
2830     g_object_ref (result);
2831   g_mutex_unlock (&priv->lock);
2832
2833   return result;
2834 }
2835
2836 /**
2837  * gst_rtsp_client_set_connection:
2838  * @client: a #GstRTSPClient
2839  * @conn: (transfer full): a #GstRTSPConnection
2840  *
2841  * Set the #GstRTSPConnection of @client. This function takes ownership of
2842  * @conn.
2843  *
2844  * Returns: %TRUE on success.
2845  */
2846 gboolean
2847 gst_rtsp_client_set_connection (GstRTSPClient * client,
2848     GstRTSPConnection * conn)
2849 {
2850   GstRTSPClientPrivate *priv;
2851   GSocket *read_socket;
2852   GSocketAddress *address;
2853   GstRTSPUrl *url;
2854   GError *error = NULL;
2855
2856   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), FALSE);
2857   g_return_val_if_fail (conn != NULL, FALSE);
2858
2859   priv = client->priv;
2860
2861   read_socket = gst_rtsp_connection_get_read_socket (conn);
2862
2863   if (!(address = g_socket_get_local_address (read_socket, &error)))
2864     goto no_address;
2865
2866   g_free (priv->server_ip);
2867   /* keep the original ip that the client connected to */
2868   if (G_IS_INET_SOCKET_ADDRESS (address)) {
2869     GInetAddress *iaddr;
2870
2871     iaddr = g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (address));
2872
2873     /* socket might be ipv6 but adress still ipv4 */
2874     priv->is_ipv6 = g_inet_address_get_family (iaddr) == G_SOCKET_FAMILY_IPV6;
2875     priv->server_ip = g_inet_address_to_string (iaddr);
2876     g_object_unref (address);
2877   } else {
2878     priv->is_ipv6 = g_socket_get_family (read_socket) == G_SOCKET_FAMILY_IPV6;
2879     priv->server_ip = g_strdup ("unknown");
2880   }
2881
2882   GST_INFO ("client %p connected to server ip %s, ipv6 = %d", client,
2883       priv->server_ip, priv->is_ipv6);
2884
2885   url = gst_rtsp_connection_get_url (conn);
2886   GST_INFO ("added new client %p ip %s:%d", client, url->host, url->port);
2887
2888   priv->connection = conn;
2889
2890   return TRUE;
2891
2892   /* ERRORS */
2893 no_address:
2894   {
2895     GST_ERROR ("could not get local address %s", error->message);
2896     g_error_free (error);
2897     return FALSE;
2898   }
2899 }
2900
2901 /**
2902  * gst_rtsp_client_get_connection:
2903  * @client: a #GstRTSPClient
2904  *
2905  * Get the #GstRTSPConnection of @client.
2906  *
2907  * Returns: (transfer none): the #GstRTSPConnection of @client.
2908  * The connection object returned remains valid until the client is freed.
2909  */
2910 GstRTSPConnection *
2911 gst_rtsp_client_get_connection (GstRTSPClient * client)
2912 {
2913   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2914
2915   return client->priv->connection;
2916 }
2917
2918 /**
2919  * gst_rtsp_client_set_send_func:
2920  * @client: a #GstRTSPClient
2921  * @func: (scope notified): a #GstRTSPClientSendFunc
2922  * @user_data: (closure): user data passed to @func
2923  * @notify: (allow-none): called when @user_data is no longer in use
2924  *
2925  * Set @func as the callback that will be called when a new message needs to be
2926  * sent to the client. @user_data is passed to @func and @notify is called when
2927  * @user_data is no longer in use.
2928  *
2929  * By default, the client will send the messages on the #GstRTSPConnection that
2930  * was configured with gst_rtsp_client_attach() was called.
2931  */
2932 void
2933 gst_rtsp_client_set_send_func (GstRTSPClient * client,
2934     GstRTSPClientSendFunc func, gpointer user_data, GDestroyNotify notify)
2935 {
2936   GstRTSPClientPrivate *priv;
2937   GDestroyNotify old_notify;
2938   gpointer old_data;
2939
2940   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2941
2942   priv = client->priv;
2943
2944   g_mutex_lock (&priv->send_lock);
2945   priv->send_func = func;
2946   old_notify = priv->send_notify;
2947   old_data = priv->send_data;
2948   priv->send_notify = notify;
2949   priv->send_data = user_data;
2950   g_mutex_unlock (&priv->send_lock);
2951
2952   if (old_notify)
2953     old_notify (old_data);
2954 }
2955
2956 /**
2957  * gst_rtsp_client_handle_message:
2958  * @client: a #GstRTSPClient
2959  * @message: (transfer none): an #GstRTSPMessage
2960  *
2961  * Let the client handle @message.
2962  *
2963  * Returns: a #GstRTSPResult.
2964  */
2965 GstRTSPResult
2966 gst_rtsp_client_handle_message (GstRTSPClient * client,
2967     GstRTSPMessage * message)
2968 {
2969   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), GST_RTSP_EINVAL);
2970   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2971
2972   switch (message->type) {
2973     case GST_RTSP_MESSAGE_REQUEST:
2974       handle_request (client, message);
2975       break;
2976     case GST_RTSP_MESSAGE_RESPONSE:
2977       handle_response (client, message);
2978       break;
2979     case GST_RTSP_MESSAGE_DATA:
2980       handle_data (client, message);
2981       break;
2982     default:
2983       break;
2984   }
2985   return GST_RTSP_OK;
2986 }
2987
2988 /**
2989  * gst_rtsp_client_send_message:
2990  * @client: a #GstRTSPClient
2991  * @session: (allow-none) (transfer none): a #GstRTSPSession to send
2992  *   the message to or %NULL
2993  * @message: (transfer none): The #GstRTSPMessage to send
2994  *
2995  * Send a message message to the remote end. @message must be a
2996  * #GST_RTSP_MESSAGE_REQUEST or a #GST_RTSP_MESSAGE_RESPONSE.
2997  */
2998 GstRTSPResult
2999 gst_rtsp_client_send_message (GstRTSPClient * client, GstRTSPSession * session,
3000     GstRTSPMessage * message)
3001 {
3002   GstRTSPContext sctx = { NULL }
3003   , *ctx;
3004   GstRTSPClientPrivate *priv;
3005
3006   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), GST_RTSP_EINVAL);
3007   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
3008   g_return_val_if_fail (message->type == GST_RTSP_MESSAGE_REQUEST ||
3009       message->type == GST_RTSP_MESSAGE_RESPONSE, GST_RTSP_EINVAL);
3010
3011   priv = client->priv;
3012
3013   if (!(ctx = gst_rtsp_context_get_current ())) {
3014     ctx = &sctx;
3015     ctx->auth = priv->auth;
3016     gst_rtsp_context_push_current (ctx);
3017   }
3018
3019   ctx->conn = priv->connection;
3020   ctx->client = client;
3021   ctx->session = session;
3022
3023   send_message (client, ctx, message, FALSE);
3024
3025   if (ctx == &sctx)
3026     gst_rtsp_context_pop_current (ctx);
3027
3028   return GST_RTSP_OK;
3029 }
3030
3031 static GstRTSPResult
3032 do_send_message (GstRTSPClient * client, GstRTSPMessage * message,
3033     gboolean close, gpointer user_data)
3034 {
3035   GstRTSPClientPrivate *priv = client->priv;
3036   GstRTSPResult ret;
3037   GTimeVal time;
3038
3039   time.tv_sec = 1;
3040   time.tv_usec = 0;
3041
3042   do {
3043     /* send the response and store the seq number so we can wait until it's
3044      * written to the client to close the connection */
3045     ret =
3046         gst_rtsp_watch_send_message (priv->watch, message,
3047         close ? &priv->close_seq : NULL);
3048     if (ret == GST_RTSP_OK)
3049       break;
3050
3051     if (ret != GST_RTSP_ENOMEM)
3052       goto error;
3053
3054     /* drop backlog */
3055     if (priv->drop_backlog)
3056       break;
3057
3058     /* queue was full, wait for more space */
3059     GST_DEBUG_OBJECT (client, "waiting for backlog");
3060     ret = gst_rtsp_watch_wait_backlog (priv->watch, &time);
3061     GST_DEBUG_OBJECT (client, "Resend due to backlog full");
3062   } while (ret != GST_RTSP_EINTR);
3063
3064   return ret;
3065
3066   /* ERRORS */
3067 error:
3068   {
3069     GST_DEBUG_OBJECT (client, "got error %d", ret);
3070     return ret;
3071   }
3072 }
3073
3074 static GstRTSPResult
3075 message_received (GstRTSPWatch * watch, GstRTSPMessage * message,
3076     gpointer user_data)
3077 {
3078   return gst_rtsp_client_handle_message (GST_RTSP_CLIENT (user_data), message);
3079 }
3080
3081 static GstRTSPResult
3082 message_sent (GstRTSPWatch * watch, guint cseq, gpointer user_data)
3083 {
3084   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3085   GstRTSPClientPrivate *priv = client->priv;
3086
3087   if (priv->close_seq && priv->close_seq == cseq) {
3088     GST_INFO ("client %p: send close message", client);
3089     priv->close_seq = 0;
3090     gst_rtsp_client_close (client);
3091   }
3092
3093   return GST_RTSP_OK;
3094 }
3095
3096 static GstRTSPResult
3097 closed (GstRTSPWatch * watch, gpointer user_data)
3098 {
3099   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3100   GstRTSPClientPrivate *priv = client->priv;
3101   const gchar *tunnelid;
3102
3103   GST_INFO ("client %p: connection closed", client);
3104
3105   if ((tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection))) {
3106     g_mutex_lock (&tunnels_lock);
3107     /* remove from tunnelids */
3108     g_hash_table_remove (tunnels, tunnelid);
3109     g_mutex_unlock (&tunnels_lock);
3110   }
3111
3112   gst_rtsp_watch_set_flushing (watch, TRUE);
3113   g_mutex_lock (&priv->watch_lock);
3114   gst_rtsp_client_set_send_func (client, NULL, NULL, NULL);
3115   g_mutex_unlock (&priv->watch_lock);
3116
3117   return GST_RTSP_OK;
3118 }
3119
3120 static GstRTSPResult
3121 error (GstRTSPWatch * watch, GstRTSPResult result, gpointer user_data)
3122 {
3123   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3124   gchar *str;
3125
3126   str = gst_rtsp_strresult (result);
3127   GST_INFO ("client %p: received an error %s", client, str);
3128   g_free (str);
3129
3130   return GST_RTSP_OK;
3131 }
3132
3133 static GstRTSPResult
3134 error_full (GstRTSPWatch * watch, GstRTSPResult result,
3135     GstRTSPMessage * message, guint id, gpointer user_data)
3136 {
3137   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3138   gchar *str;
3139
3140   str = gst_rtsp_strresult (result);
3141   GST_INFO
3142       ("client %p: error when handling message %p with id %d: %s",
3143       client, message, id, str);
3144   g_free (str);
3145
3146   return GST_RTSP_OK;
3147 }
3148
3149 static gboolean
3150 remember_tunnel (GstRTSPClient * client)
3151 {
3152   GstRTSPClientPrivate *priv = client->priv;
3153   const gchar *tunnelid;
3154
3155   /* store client in the pending tunnels */
3156   tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection);
3157   if (tunnelid == NULL)
3158     goto no_tunnelid;
3159
3160   GST_INFO ("client %p: inserting tunnel session %s", client, tunnelid);
3161
3162   /* we can't have two clients connecting with the same tunnelid */
3163   g_mutex_lock (&tunnels_lock);
3164   if (g_hash_table_lookup (tunnels, tunnelid))
3165     goto tunnel_existed;
3166
3167   g_hash_table_insert (tunnels, g_strdup (tunnelid), g_object_ref (client));
3168   g_mutex_unlock (&tunnels_lock);
3169
3170   return TRUE;
3171
3172   /* ERRORS */
3173 no_tunnelid:
3174   {
3175     GST_ERROR ("client %p: no tunnelid provided", client);
3176     return FALSE;
3177   }
3178 tunnel_existed:
3179   {
3180     g_mutex_unlock (&tunnels_lock);
3181     GST_ERROR ("client %p: tunnel session %s already existed", client,
3182         tunnelid);
3183     return FALSE;
3184   }
3185 }
3186
3187 static GstRTSPResult
3188 tunnel_lost (GstRTSPWatch * watch, gpointer user_data)
3189 {
3190   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3191   GstRTSPClientPrivate *priv = client->priv;
3192
3193   GST_WARNING ("client %p: tunnel lost (connection %p)", client,
3194       priv->connection);
3195
3196   /* ignore error, it'll only be a problem when the client does a POST again */
3197   remember_tunnel (client);
3198
3199   return GST_RTSP_OK;
3200 }
3201
3202 static gboolean
3203 handle_tunnel (GstRTSPClient * client)
3204 {
3205   GstRTSPClientPrivate *priv = client->priv;
3206   GstRTSPClient *oclient;
3207   GstRTSPClientPrivate *opriv;
3208   const gchar *tunnelid;
3209
3210   tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection);
3211   if (tunnelid == NULL)
3212     goto no_tunnelid;
3213
3214   /* check for previous tunnel */
3215   g_mutex_lock (&tunnels_lock);
3216   oclient = g_hash_table_lookup (tunnels, tunnelid);
3217
3218   if (oclient == NULL) {
3219     /* no previous tunnel, remember tunnel */
3220     g_hash_table_insert (tunnels, g_strdup (tunnelid), g_object_ref (client));
3221     g_mutex_unlock (&tunnels_lock);
3222
3223     GST_INFO ("client %p: no previous tunnel found, remembering tunnel (%p)",
3224         client, priv->connection);
3225   } else {
3226     /* merge both tunnels into the first client */
3227     /* remove the old client from the table. ref before because removing it will
3228      * remove the ref to it. */
3229     g_object_ref (oclient);
3230     g_hash_table_remove (tunnels, tunnelid);
3231     g_mutex_unlock (&tunnels_lock);
3232
3233     opriv = oclient->priv;
3234
3235     g_mutex_lock (&opriv->watch_lock);
3236     if (opriv->watch == NULL)
3237       goto tunnel_closed;
3238
3239     GST_INFO ("client %p: found previous tunnel %p (old %p, new %p)", client,
3240         oclient, opriv->connection, priv->connection);
3241
3242     gst_rtsp_connection_do_tunnel (opriv->connection, priv->connection);
3243     gst_rtsp_watch_reset (priv->watch);
3244     gst_rtsp_watch_reset (opriv->watch);
3245     g_mutex_unlock (&opriv->watch_lock);
3246     g_object_unref (oclient);
3247
3248     /* the old client owns the tunnel now, the new one will be freed */
3249     g_source_destroy ((GSource *) priv->watch);
3250     priv->watch = NULL;
3251     gst_rtsp_client_set_send_func (client, NULL, NULL, NULL);
3252   }
3253
3254   return TRUE;
3255
3256   /* ERRORS */
3257 no_tunnelid:
3258   {
3259     GST_ERROR ("client %p: no tunnelid provided", client);
3260     return FALSE;
3261   }
3262 tunnel_closed:
3263   {
3264     GST_ERROR ("client %p: tunnel session %s was closed", client, tunnelid);
3265     g_mutex_unlock (&opriv->watch_lock);
3266     g_object_unref (oclient);
3267     return FALSE;
3268   }
3269 }
3270
3271 static GstRTSPStatusCode
3272 tunnel_get (GstRTSPWatch * watch, gpointer user_data)
3273 {
3274   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3275
3276   GST_INFO ("client %p: tunnel get (connection %p)", client,
3277       client->priv->connection);
3278
3279   if (!handle_tunnel (client)) {
3280     return GST_RTSP_STS_SERVICE_UNAVAILABLE;
3281   }
3282
3283   return GST_RTSP_STS_OK;
3284 }
3285
3286 static GstRTSPResult
3287 tunnel_post (GstRTSPWatch * watch, gpointer user_data)
3288 {
3289   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3290
3291   GST_INFO ("client %p: tunnel post (connection %p)", client,
3292       client->priv->connection);
3293
3294   if (!handle_tunnel (client)) {
3295     return GST_RTSP_ERROR;
3296   }
3297
3298   return GST_RTSP_OK;
3299 }
3300
3301 static GstRTSPResult
3302 tunnel_http_response (GstRTSPWatch * watch, GstRTSPMessage * request,
3303     GstRTSPMessage * response, gpointer user_data)
3304 {
3305   GstRTSPClientClass *klass;
3306
3307   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3308   klass = GST_RTSP_CLIENT_GET_CLASS (client);
3309
3310   if (klass->tunnel_http_response) {
3311     klass->tunnel_http_response (client, request, response);
3312   }
3313
3314   return GST_RTSP_OK;
3315 }
3316
3317 static GstRTSPWatchFuncs watch_funcs = {
3318   message_received,
3319   message_sent,
3320   closed,
3321   error,
3322   tunnel_get,
3323   tunnel_post,
3324   error_full,
3325   tunnel_lost,
3326   tunnel_http_response
3327 };
3328
3329 static void
3330 client_watch_notify (GstRTSPClient * client)
3331 {
3332   GstRTSPClientPrivate *priv = client->priv;
3333
3334   GST_INFO ("client %p: watch destroyed", client);
3335   priv->watch = NULL;
3336   /* remove all sessions and so drop the extra client ref */
3337   gst_rtsp_client_session_filter (client, cleanup_session, NULL);
3338   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_CLOSED], 0, NULL);
3339   g_object_unref (client);
3340 }
3341
3342 /**
3343  * gst_rtsp_client_attach:
3344  * @client: a #GstRTSPClient
3345  * @context: (allow-none): a #GMainContext
3346  *
3347  * Attaches @client to @context. When the mainloop for @context is run, the
3348  * client will be dispatched. When @context is %NULL, the default context will be
3349  * used).
3350  *
3351  * This function should be called when the client properties and urls are fully
3352  * configured and the client is ready to start.
3353  *
3354  * Returns: the ID (greater than 0) for the source within the GMainContext.
3355  */
3356 guint
3357 gst_rtsp_client_attach (GstRTSPClient * client, GMainContext * context)
3358 {
3359   GstRTSPClientPrivate *priv;
3360   guint res;
3361
3362   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), 0);
3363   priv = client->priv;
3364   g_return_val_if_fail (priv->connection != NULL, 0);
3365   g_return_val_if_fail (priv->watch == NULL, 0);
3366
3367   /* make sure noone will free the context before the watch is destroyed */
3368   priv->watch_context = g_main_context_ref (context);
3369
3370   /* create watch for the connection and attach */
3371   priv->watch = gst_rtsp_watch_new (priv->connection, &watch_funcs,
3372       g_object_ref (client), (GDestroyNotify) client_watch_notify);
3373   gst_rtsp_client_set_send_func (client, do_send_message, priv->watch,
3374       (GDestroyNotify) gst_rtsp_watch_unref);
3375
3376   gst_rtsp_watch_set_send_backlog (priv->watch, 0, WATCH_BACKLOG_SIZE);
3377
3378   GST_INFO ("client %p: attaching to context %p", client, context);
3379   res = gst_rtsp_watch_attach (priv->watch, context);
3380
3381   return res;
3382 }
3383
3384 /**
3385  * gst_rtsp_client_session_filter:
3386  * @client: a #GstRTSPClient
3387  * @func: (scope call) (allow-none): a callback
3388  * @user_data: user data passed to @func
3389  *
3390  * Call @func for each session managed by @client. The result value of @func
3391  * determines what happens to the session. @func will be called with @client
3392  * locked so no further actions on @client can be performed from @func.
3393  *
3394  * If @func returns #GST_RTSP_FILTER_REMOVE, the session will be removed from
3395  * @client.
3396  *
3397  * If @func returns #GST_RTSP_FILTER_KEEP, the session will remain in @client.
3398  *
3399  * If @func returns #GST_RTSP_FILTER_REF, the session will remain in @client but
3400  * will also be added with an additional ref to the result #GList of this
3401  * function..
3402  *
3403  * When @func is %NULL, #GST_RTSP_FILTER_REF will be assumed for each session.
3404  *
3405  * Returns: (element-type GstRTSPSession) (transfer full): a #GList with all
3406  * sessions for which @func returned #GST_RTSP_FILTER_REF. After usage, each
3407  * element in the #GList should be unreffed before the list is freed.
3408  */
3409 GList *
3410 gst_rtsp_client_session_filter (GstRTSPClient * client,
3411     GstRTSPClientSessionFilterFunc func, gpointer user_data)
3412 {
3413   GstRTSPClientPrivate *priv;
3414   GList *result, *walk, *next;
3415   GHashTable *visited;
3416   guint cookie;
3417
3418   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
3419
3420   priv = client->priv;
3421
3422   result = NULL;
3423   if (func)
3424     visited = g_hash_table_new_full (NULL, NULL, g_object_unref, NULL);
3425
3426   g_mutex_lock (&priv->lock);
3427 restart:
3428   cookie = priv->sessions_cookie;
3429   for (walk = priv->sessions; walk; walk = next) {
3430     GstRTSPSession *sess = walk->data;
3431     GstRTSPFilterResult res;
3432     gboolean changed;
3433
3434     next = g_list_next (walk);
3435
3436     if (func) {
3437       /* only visit each session once */
3438       if (g_hash_table_contains (visited, sess))
3439         continue;
3440
3441       g_hash_table_add (visited, g_object_ref (sess));
3442       g_mutex_unlock (&priv->lock);
3443
3444       res = func (client, sess, user_data);
3445
3446       g_mutex_lock (&priv->lock);
3447     } else
3448       res = GST_RTSP_FILTER_REF;
3449
3450     changed = (cookie != priv->sessions_cookie);
3451
3452     switch (res) {
3453       case GST_RTSP_FILTER_REMOVE:
3454         /* stop watching the session and pretend it went away, if the list was
3455          * changed, we can't use the current list position, try to see if we
3456          * still have the session */
3457         client_unwatch_session (client, sess, changed ? NULL : walk);
3458         cookie = priv->sessions_cookie;
3459         break;
3460       case GST_RTSP_FILTER_REF:
3461         result = g_list_prepend (result, g_object_ref (sess));
3462         break;
3463       case GST_RTSP_FILTER_KEEP:
3464       default:
3465         break;
3466     }
3467     if (changed)
3468       goto restart;
3469   }
3470   g_mutex_unlock (&priv->lock);
3471
3472   if (func)
3473     g_hash_table_unref (visited);
3474
3475   return result;
3476 }