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