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