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