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