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