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