rtsp-client: do not free main context before rtsp watch
[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     g_main_context_unref (priv->watch_context);
754     priv->watch_context = NULL;
755   }
756 }
757
758 static gchar *
759 default_make_path_from_uri (GstRTSPClient * client, const GstRTSPUrl * uri)
760 {
761   gchar *path;
762
763   if (uri->query)
764     path = g_strconcat (uri->abspath, "?", uri->query, NULL);
765   else
766     path = g_strdup (uri->abspath);
767
768   return path;
769 }
770
771 static gboolean
772 handle_teardown_request (GstRTSPClient * client, GstRTSPContext * ctx)
773 {
774   GstRTSPClientPrivate *priv = client->priv;
775   GstRTSPClientClass *klass;
776   GstRTSPSession *session;
777   GstRTSPSessionMedia *sessmedia;
778   GstRTSPStatusCode code;
779   gchar *path;
780   gint matched;
781   gboolean keep_session;
782
783   if (!ctx->session)
784     goto no_session;
785
786   session = ctx->session;
787
788   if (!ctx->uri)
789     goto no_uri;
790
791   klass = GST_RTSP_CLIENT_GET_CLASS (client);
792   path = klass->make_path_from_uri (client, ctx->uri);
793
794   /* get a handle to the configuration of the media in the session */
795   sessmedia = gst_rtsp_session_get_media (session, path, &matched);
796   if (!sessmedia)
797     goto not_found;
798
799   /* only aggregate control for now.. */
800   if (path[matched] != '\0')
801     goto no_aggregate;
802
803   g_free (path);
804
805   ctx->sessmedia = sessmedia;
806
807   /* we emit the signal before closing the connection */
808   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_TEARDOWN_REQUEST],
809       0, ctx);
810
811   /* make sure we unblock the backlog and don't accept new messages
812    * on the watch */
813   if (priv->watch != NULL)
814     gst_rtsp_watch_set_flushing (priv->watch, TRUE);
815
816   gst_rtsp_session_media_set_state (sessmedia, GST_STATE_NULL);
817
818   /* allow messages again so that we can send the reply */
819   if (priv->watch != NULL)
820     gst_rtsp_watch_set_flushing (priv->watch, FALSE);
821
822   /* unmanage the media in the session, returns false if all media session
823    * are torn down. */
824   keep_session = gst_rtsp_session_release_media (session, sessmedia);
825
826   /* construct the response now */
827   code = GST_RTSP_STS_OK;
828   gst_rtsp_message_init_response (ctx->response, code,
829       gst_rtsp_status_as_text (code), ctx->request);
830
831   send_message (client, ctx, ctx->response, TRUE);
832
833   if (!keep_session) {
834     /* remove the session */
835     gst_rtsp_session_pool_remove (priv->session_pool, session);
836   }
837
838   return TRUE;
839
840   /* ERRORS */
841 no_session:
842   {
843     GST_ERROR ("client %p: no session", client);
844     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
845     return FALSE;
846   }
847 no_uri:
848   {
849     GST_ERROR ("client %p: no uri supplied", client);
850     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
851     return FALSE;
852   }
853 not_found:
854   {
855     GST_ERROR ("client %p: no media for uri", client);
856     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
857     g_free (path);
858     return FALSE;
859   }
860 no_aggregate:
861   {
862     GST_ERROR ("client %p: no aggregate path %s", client, path);
863     send_generic_response (client,
864         GST_RTSP_STS_ONLY_AGGREGATE_OPERATION_ALLOWED, ctx);
865     g_free (path);
866     return FALSE;
867   }
868 }
869
870 static GstRTSPResult
871 default_params_set (GstRTSPClient * client, GstRTSPContext * ctx)
872 {
873   GstRTSPResult res;
874
875   res = gst_rtsp_params_set (client, ctx);
876
877   return res;
878 }
879
880 static GstRTSPResult
881 default_params_get (GstRTSPClient * client, GstRTSPContext * ctx)
882 {
883   GstRTSPResult res;
884
885   res = gst_rtsp_params_get (client, ctx);
886
887   return res;
888 }
889
890 static gboolean
891 handle_get_param_request (GstRTSPClient * client, GstRTSPContext * ctx)
892 {
893   GstRTSPResult res;
894   guint8 *data;
895   guint size;
896
897   res = gst_rtsp_message_get_body (ctx->request, &data, &size);
898   if (res != GST_RTSP_OK)
899     goto bad_request;
900
901   if (size == 0) {
902     /* no body, keep-alive request */
903     send_generic_response (client, GST_RTSP_STS_OK, ctx);
904   } else {
905     /* there is a body, handle the params */
906     res = GST_RTSP_CLIENT_GET_CLASS (client)->params_get (client, ctx);
907     if (res != GST_RTSP_OK)
908       goto bad_request;
909
910     send_message (client, ctx, ctx->response, FALSE);
911   }
912
913   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_GET_PARAMETER_REQUEST],
914       0, ctx);
915
916   return TRUE;
917
918   /* ERRORS */
919 bad_request:
920   {
921     GST_ERROR ("client %p: bad request", client);
922     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
923     return FALSE;
924   }
925 }
926
927 static gboolean
928 handle_set_param_request (GstRTSPClient * client, GstRTSPContext * ctx)
929 {
930   GstRTSPResult res;
931   guint8 *data;
932   guint size;
933
934   res = gst_rtsp_message_get_body (ctx->request, &data, &size);
935   if (res != GST_RTSP_OK)
936     goto bad_request;
937
938   if (size == 0) {
939     /* no body, keep-alive request */
940     send_generic_response (client, GST_RTSP_STS_OK, ctx);
941   } else {
942     /* there is a body, handle the params */
943     res = GST_RTSP_CLIENT_GET_CLASS (client)->params_set (client, ctx);
944     if (res != GST_RTSP_OK)
945       goto bad_request;
946
947     send_message (client, ctx, ctx->response, FALSE);
948   }
949
950   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_SET_PARAMETER_REQUEST],
951       0, ctx);
952
953   return TRUE;
954
955   /* ERRORS */
956 bad_request:
957   {
958     GST_ERROR ("client %p: bad request", client);
959     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
960     return FALSE;
961   }
962 }
963
964 static gboolean
965 handle_pause_request (GstRTSPClient * client, GstRTSPContext * ctx)
966 {
967   GstRTSPClientPrivate *priv = client->priv;
968   GstRTSPSession *session;
969   GstRTSPClientClass *klass;
970   GstRTSPSessionMedia *sessmedia;
971   GstRTSPStatusCode code;
972   GstRTSPState rtspstate;
973   gchar *path;
974   gint matched;
975
976   if (!(session = ctx->session))
977     goto no_session;
978
979   if (!ctx->uri)
980     goto no_uri;
981
982   klass = GST_RTSP_CLIENT_GET_CLASS (client);
983   path = klass->make_path_from_uri (client, ctx->uri);
984
985   /* get a handle to the configuration of the media in the session */
986   sessmedia = gst_rtsp_session_get_media (session, path, &matched);
987   if (!sessmedia)
988     goto not_found;
989
990   if (path[matched] != '\0')
991     goto no_aggregate;
992
993   g_free (path);
994
995   ctx->sessmedia = sessmedia;
996
997   rtspstate = gst_rtsp_session_media_get_rtsp_state (sessmedia);
998   /* the session state must be playing or recording */
999   if (rtspstate != GST_RTSP_STATE_PLAYING &&
1000       rtspstate != GST_RTSP_STATE_RECORDING)
1001     goto invalid_state;
1002
1003   /* No limit on watch queue because else we might be blocking in the appsink
1004    * render method and the PAUSE below will hang */
1005   if (priv->watch != NULL)
1006     gst_rtsp_watch_set_send_backlog (priv->watch, 0, 0);
1007
1008   /* then pause sending */
1009   gst_rtsp_session_media_set_state (sessmedia, GST_STATE_PAUSED);
1010
1011   /* construct the response now */
1012   code = GST_RTSP_STS_OK;
1013   gst_rtsp_message_init_response (ctx->response, code,
1014       gst_rtsp_status_as_text (code), ctx->request);
1015
1016   send_message (client, ctx, ctx->response, FALSE);
1017
1018   if (priv->watch != NULL)
1019     gst_rtsp_watch_set_send_backlog (priv->watch, 0, WATCH_BACKLOG_SIZE);
1020
1021   /* the state is now READY */
1022   gst_rtsp_session_media_set_rtsp_state (sessmedia, GST_RTSP_STATE_READY);
1023
1024   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_PAUSE_REQUEST], 0, ctx);
1025
1026   return TRUE;
1027
1028   /* ERRORS */
1029 no_session:
1030   {
1031     GST_ERROR ("client %p: no seesion", client);
1032     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
1033     return FALSE;
1034   }
1035 no_uri:
1036   {
1037     GST_ERROR ("client %p: no uri supplied", client);
1038     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
1039     return FALSE;
1040   }
1041 not_found:
1042   {
1043     GST_ERROR ("client %p: no media for uri", client);
1044     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
1045     g_free (path);
1046     return FALSE;
1047   }
1048 no_aggregate:
1049   {
1050     GST_ERROR ("client %p: no aggregate path %s", client, path);
1051     send_generic_response (client,
1052         GST_RTSP_STS_ONLY_AGGREGATE_OPERATION_ALLOWED, ctx);
1053     g_free (path);
1054     return FALSE;
1055   }
1056 invalid_state:
1057   {
1058     GST_ERROR ("client %p: not PLAYING or RECORDING", client);
1059     send_generic_response (client, GST_RTSP_STS_METHOD_NOT_VALID_IN_THIS_STATE,
1060         ctx);
1061     return FALSE;
1062   }
1063 }
1064
1065 /* convert @url and @path to a URL used as a content base for the factory
1066  * located at @path */
1067 static gchar *
1068 make_base_url (GstRTSPClient * client, GstRTSPUrl * url, const gchar * path)
1069 {
1070   GstRTSPUrl tmp;
1071   gchar *result;
1072   const gchar *trail;
1073
1074   /* check for trailing '/' and append one */
1075   trail = (path[strlen (path) - 1] != '/' ? "/" : "");
1076
1077   tmp = *url;
1078   tmp.user = NULL;
1079   tmp.passwd = NULL;
1080   tmp.abspath = g_strdup_printf ("%s%s", path, trail);
1081   tmp.query = NULL;
1082   result = gst_rtsp_url_get_request_uri (&tmp);
1083   g_free (tmp.abspath);
1084
1085   return result;
1086 }
1087
1088 static gboolean
1089 handle_play_request (GstRTSPClient * client, GstRTSPContext * ctx)
1090 {
1091   GstRTSPSession *session;
1092   GstRTSPClientClass *klass;
1093   GstRTSPSessionMedia *sessmedia;
1094   GstRTSPMedia *media;
1095   GstRTSPStatusCode code;
1096   GstRTSPUrl *uri;
1097   gchar *str;
1098   GstRTSPTimeRange *range;
1099   GstRTSPResult res;
1100   GstRTSPState rtspstate;
1101   GstRTSPRangeUnit unit = GST_RTSP_RANGE_NPT;
1102   gchar *path, *rtpinfo;
1103   gint matched;
1104
1105   if (!(session = ctx->session))
1106     goto no_session;
1107
1108   if (!(uri = ctx->uri))
1109     goto no_uri;
1110
1111   klass = GST_RTSP_CLIENT_GET_CLASS (client);
1112   path = klass->make_path_from_uri (client, uri);
1113
1114   /* get a handle to the configuration of the media in the session */
1115   sessmedia = gst_rtsp_session_get_media (session, path, &matched);
1116   if (!sessmedia)
1117     goto not_found;
1118
1119   if (path[matched] != '\0')
1120     goto no_aggregate;
1121
1122   g_free (path);
1123
1124   ctx->sessmedia = sessmedia;
1125   ctx->media = media = gst_rtsp_session_media_get_media (sessmedia);
1126
1127   /* the session state must be playing or ready */
1128   rtspstate = gst_rtsp_session_media_get_rtsp_state (sessmedia);
1129   if (rtspstate != GST_RTSP_STATE_PLAYING && rtspstate != GST_RTSP_STATE_READY)
1130     goto invalid_state;
1131
1132   /* in play we first unsuspend, media could be suspended from SDP or PAUSED */
1133   if (!gst_rtsp_media_unsuspend (media))
1134     goto unsuspend_failed;
1135
1136   /* parse the range header if we have one */
1137   res = gst_rtsp_message_get_header (ctx->request, GST_RTSP_HDR_RANGE, &str, 0);
1138   if (res == GST_RTSP_OK) {
1139     if (gst_rtsp_range_parse (str, &range) == GST_RTSP_OK) {
1140       /* we have a range, seek to the position */
1141       unit = range->unit;
1142       gst_rtsp_media_seek (media, range);
1143       gst_rtsp_range_free (range);
1144     }
1145   }
1146
1147   /* grab RTPInfo from the media now */
1148   rtpinfo = gst_rtsp_session_media_get_rtpinfo (sessmedia);
1149
1150   /* construct the response now */
1151   code = GST_RTSP_STS_OK;
1152   gst_rtsp_message_init_response (ctx->response, code,
1153       gst_rtsp_status_as_text (code), ctx->request);
1154
1155   /* add the RTP-Info header */
1156   if (rtpinfo)
1157     gst_rtsp_message_take_header (ctx->response, GST_RTSP_HDR_RTP_INFO,
1158         rtpinfo);
1159
1160   /* add the range */
1161   str = gst_rtsp_media_get_range_string (media, TRUE, unit);
1162   if (str)
1163     gst_rtsp_message_take_header (ctx->response, GST_RTSP_HDR_RANGE, str);
1164
1165   send_message (client, ctx, ctx->response, FALSE);
1166
1167   /* start playing after sending the response */
1168   gst_rtsp_session_media_set_state (sessmedia, GST_STATE_PLAYING);
1169
1170   gst_rtsp_session_media_set_rtsp_state (sessmedia, GST_RTSP_STATE_PLAYING);
1171
1172   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_PLAY_REQUEST], 0, ctx);
1173
1174   return TRUE;
1175
1176   /* ERRORS */
1177 no_session:
1178   {
1179     GST_ERROR ("client %p: no session", client);
1180     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
1181     return FALSE;
1182   }
1183 no_uri:
1184   {
1185     GST_ERROR ("client %p: no uri supplied", client);
1186     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
1187     return FALSE;
1188   }
1189 not_found:
1190   {
1191     GST_ERROR ("client %p: media not found", client);
1192     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
1193     return FALSE;
1194   }
1195 no_aggregate:
1196   {
1197     GST_ERROR ("client %p: no aggregate path %s", client, path);
1198     send_generic_response (client,
1199         GST_RTSP_STS_ONLY_AGGREGATE_OPERATION_ALLOWED, ctx);
1200     g_free (path);
1201     return FALSE;
1202   }
1203 invalid_state:
1204   {
1205     GST_ERROR ("client %p: not PLAYING or READY", client);
1206     send_generic_response (client, GST_RTSP_STS_METHOD_NOT_VALID_IN_THIS_STATE,
1207         ctx);
1208     return FALSE;
1209   }
1210 unsuspend_failed:
1211   {
1212     GST_ERROR ("client %p: unsuspend failed", client);
1213     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, ctx);
1214     return FALSE;
1215   }
1216 }
1217
1218 static void
1219 do_keepalive (GstRTSPSession * session)
1220 {
1221   GST_INFO ("keep session %p alive", session);
1222   gst_rtsp_session_touch (session);
1223 }
1224
1225 /* parse @transport and return a valid transport in @tr. only transports
1226  * supported by @stream are returned. Returns FALSE if no valid transport
1227  * was found. */
1228 static gboolean
1229 parse_transport (const char *transport, GstRTSPStream * stream,
1230     GstRTSPTransport * tr)
1231 {
1232   gint i;
1233   gboolean res;
1234   gchar **transports;
1235
1236   res = FALSE;
1237   gst_rtsp_transport_init (tr);
1238
1239   GST_DEBUG ("parsing transports %s", transport);
1240
1241   transports = g_strsplit (transport, ",", 0);
1242
1243   /* loop through the transports, try to parse */
1244   for (i = 0; transports[i]; i++) {
1245     res = gst_rtsp_transport_parse (transports[i], tr);
1246     if (res != GST_RTSP_OK) {
1247       /* no valid transport, search some more */
1248       GST_WARNING ("could not parse transport %s", transports[i]);
1249       goto next;
1250     }
1251
1252     /* we have a transport, see if it's supported */
1253     if (!gst_rtsp_stream_is_transport_supported (stream, tr)) {
1254       GST_WARNING ("unsupported transport %s", transports[i]);
1255       goto next;
1256     }
1257
1258     /* we have a valid transport */
1259     GST_INFO ("found valid transport %s", transports[i]);
1260     res = TRUE;
1261     break;
1262
1263   next:
1264     gst_rtsp_transport_init (tr);
1265   }
1266   g_strfreev (transports);
1267
1268   return res;
1269 }
1270
1271 static gboolean
1272 default_configure_client_media (GstRTSPClient * client, GstRTSPMedia * media,
1273     GstRTSPStream * stream, GstRTSPContext * ctx)
1274 {
1275   GstRTSPMessage *request = ctx->request;
1276   gchar *blocksize_str;
1277
1278   if (gst_rtsp_message_get_header (request, GST_RTSP_HDR_BLOCKSIZE,
1279           &blocksize_str, 0) == GST_RTSP_OK) {
1280     guint64 blocksize;
1281     gchar *end;
1282
1283     blocksize = g_ascii_strtoull (blocksize_str, &end, 10);
1284     if (end == blocksize_str)
1285       goto parse_failed;
1286
1287     /* we don't want to change the mtu when this media
1288      * can be shared because it impacts other clients */
1289     if (gst_rtsp_media_is_shared (media))
1290       goto done;
1291
1292     if (blocksize > G_MAXUINT)
1293       blocksize = G_MAXUINT;
1294
1295     gst_rtsp_stream_set_mtu (stream, blocksize);
1296   }
1297 done:
1298   return TRUE;
1299
1300   /* ERRORS */
1301 parse_failed:
1302   {
1303     GST_ERROR_OBJECT (client, "failed to parse blocksize");
1304     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
1305     return FALSE;
1306   }
1307 }
1308
1309 static gboolean
1310 default_configure_client_transport (GstRTSPClient * client,
1311     GstRTSPContext * ctx, GstRTSPTransport * ct)
1312 {
1313   GstRTSPClientPrivate *priv = client->priv;
1314
1315   /* we have a valid transport now, set the destination of the client. */
1316   if (ct->lower_transport == GST_RTSP_LOWER_TRANS_UDP_MCAST) {
1317     gboolean use_client_settings;
1318
1319     use_client_settings =
1320         gst_rtsp_auth_check (GST_RTSP_AUTH_CHECK_TRANSPORT_CLIENT_SETTINGS);
1321
1322     if (ct->destination && use_client_settings) {
1323       GstRTSPAddress *addr;
1324
1325       addr = gst_rtsp_stream_reserve_address (ctx->stream, ct->destination,
1326           ct->port.min, ct->port.max - ct->port.min + 1, ct->ttl);
1327
1328       if (addr == NULL)
1329         goto no_address;
1330
1331       gst_rtsp_address_free (addr);
1332     } else {
1333       GstRTSPAddress *addr;
1334       GSocketFamily family;
1335
1336       family = priv->is_ipv6 ? G_SOCKET_FAMILY_IPV6 : G_SOCKET_FAMILY_IPV4;
1337
1338       addr = gst_rtsp_stream_get_multicast_address (ctx->stream, family);
1339       if (addr == NULL)
1340         goto no_address;
1341
1342       g_free (ct->destination);
1343       ct->destination = g_strdup (addr->address);
1344       ct->port.min = addr->port;
1345       ct->port.max = addr->port + addr->n_ports - 1;
1346       ct->ttl = addr->ttl;
1347
1348       gst_rtsp_address_free (addr);
1349     }
1350   } else {
1351     GstRTSPUrl *url;
1352
1353     url = gst_rtsp_connection_get_url (priv->connection);
1354     g_free (ct->destination);
1355     ct->destination = g_strdup (url->host);
1356
1357     if (ct->lower_transport & GST_RTSP_LOWER_TRANS_TCP) {
1358       GSocket *sock;
1359       GSocketAddress *addr;
1360
1361       sock = gst_rtsp_connection_get_read_socket (priv->connection);
1362       if ((addr = g_socket_get_remote_address (sock, NULL))) {
1363         /* our read port is the sender port of client */
1364         ct->client_port.min =
1365             g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (addr));
1366         g_object_unref (addr);
1367       }
1368       if ((addr = g_socket_get_local_address (sock, NULL))) {
1369         ct->server_port.max =
1370             g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (addr));
1371         g_object_unref (addr);
1372       }
1373       sock = gst_rtsp_connection_get_write_socket (priv->connection);
1374       if ((addr = g_socket_get_remote_address (sock, NULL))) {
1375         /* our write port is the receiver port of client */
1376         ct->client_port.max =
1377             g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (addr));
1378         g_object_unref (addr);
1379       }
1380       if ((addr = g_socket_get_local_address (sock, NULL))) {
1381         ct->server_port.min =
1382             g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (addr));
1383         g_object_unref (addr);
1384       }
1385       /* check if the client selected channels for TCP */
1386       if (ct->interleaved.min == -1 || ct->interleaved.max == -1) {
1387         gst_rtsp_session_media_alloc_channels (ctx->sessmedia,
1388             &ct->interleaved);
1389       }
1390     }
1391   }
1392   return TRUE;
1393
1394   /* ERRORS */
1395 no_address:
1396   {
1397     GST_ERROR_OBJECT (client, "failed to acquire address for stream");
1398     return FALSE;
1399   }
1400 }
1401
1402 static GstRTSPTransport *
1403 make_server_transport (GstRTSPClient * client, GstRTSPContext * ctx,
1404     GstRTSPTransport * ct)
1405 {
1406   GstRTSPTransport *st;
1407   GInetAddress *addr;
1408   GSocketFamily family;
1409
1410   /* prepare the server transport */
1411   gst_rtsp_transport_new (&st);
1412
1413   st->trans = ct->trans;
1414   st->profile = ct->profile;
1415   st->lower_transport = ct->lower_transport;
1416
1417   addr = g_inet_address_new_from_string (ct->destination);
1418
1419   if (!addr) {
1420     GST_ERROR ("failed to get inet addr from client destination");
1421     family = G_SOCKET_FAMILY_IPV4;
1422   } else {
1423     family = g_inet_address_get_family (addr);
1424     g_object_unref (addr);
1425     addr = NULL;
1426   }
1427
1428   switch (st->lower_transport) {
1429     case GST_RTSP_LOWER_TRANS_UDP:
1430       st->client_port = ct->client_port;
1431       gst_rtsp_stream_get_server_port (ctx->stream, &st->server_port, family);
1432       break;
1433     case GST_RTSP_LOWER_TRANS_UDP_MCAST:
1434       st->port = ct->port;
1435       st->destination = g_strdup (ct->destination);
1436       st->ttl = ct->ttl;
1437       break;
1438     case GST_RTSP_LOWER_TRANS_TCP:
1439       st->interleaved = ct->interleaved;
1440       st->client_port = ct->client_port;
1441       st->server_port = ct->server_port;
1442     default:
1443       break;
1444   }
1445
1446   gst_rtsp_stream_get_ssrc (ctx->stream, &st->ssrc);
1447
1448   return st;
1449 }
1450
1451 #define AES_128_KEY_LEN 16
1452 #define AES_256_KEY_LEN 32
1453
1454 #define HMAC_32_KEY_LEN 4
1455 #define HMAC_80_KEY_LEN 10
1456
1457 static gboolean
1458 mikey_apply_policy (GstCaps * caps, GstMIKEYMessage * msg, guint8 policy)
1459 {
1460   const gchar *srtp_cipher;
1461   const gchar *srtp_auth;
1462   const GstMIKEYPayload *sp;
1463   guint i;
1464
1465   /* loop over Security policy until we find one containing policy */
1466   for (i = 0;; i++) {
1467     if ((sp = gst_mikey_message_find_payload (msg, GST_MIKEY_PT_SP, i)) == NULL)
1468       break;
1469
1470     if (((GstMIKEYPayloadSP *) sp)->policy == policy)
1471       break;
1472   }
1473
1474   /* the default ciphers */
1475   srtp_cipher = "aes-128-icm";
1476   srtp_auth = "hmac-sha1-80";
1477
1478   /* now override the defaults with what is in the Security Policy */
1479   if (sp != NULL) {
1480     guint len;
1481
1482     /* collect all the params and go over them */
1483     len = gst_mikey_payload_sp_get_n_params (sp);
1484     for (i = 0; i < len; i++) {
1485       const GstMIKEYPayloadSPParam *param =
1486           gst_mikey_payload_sp_get_param (sp, i);
1487
1488       switch (param->type) {
1489         case GST_MIKEY_SP_SRTP_ENC_ALG:
1490           switch (param->val[0]) {
1491             case 0:
1492               srtp_cipher = "null";
1493               break;
1494             case 2:
1495             case 1:
1496               srtp_cipher = "aes-128-icm";
1497               break;
1498             default:
1499               break;
1500           }
1501           break;
1502         case GST_MIKEY_SP_SRTP_ENC_KEY_LEN:
1503           switch (param->val[0]) {
1504             case AES_128_KEY_LEN:
1505               srtp_cipher = "aes-128-icm";
1506               break;
1507             case AES_256_KEY_LEN:
1508               srtp_cipher = "aes-256-icm";
1509               break;
1510             default:
1511               break;
1512           }
1513           break;
1514         case GST_MIKEY_SP_SRTP_AUTH_ALG:
1515           switch (param->val[0]) {
1516             case 0:
1517               srtp_auth = "null";
1518               break;
1519             case 2:
1520             case 1:
1521               srtp_auth = "hmac-sha1-80";
1522               break;
1523             default:
1524               break;
1525           }
1526           break;
1527         case GST_MIKEY_SP_SRTP_AUTH_KEY_LEN:
1528           switch (param->val[0]) {
1529             case HMAC_32_KEY_LEN:
1530               srtp_auth = "hmac-sha1-32";
1531               break;
1532             case HMAC_80_KEY_LEN:
1533               srtp_auth = "hmac-sha1-80";
1534               break;
1535             default:
1536               break;
1537           }
1538           break;
1539         case GST_MIKEY_SP_SRTP_SRTP_ENC:
1540           break;
1541         case GST_MIKEY_SP_SRTP_SRTCP_ENC:
1542           break;
1543         default:
1544           break;
1545       }
1546     }
1547   }
1548   /* now configure the SRTP parameters */
1549   gst_caps_set_simple (caps,
1550       "srtp-cipher", G_TYPE_STRING, srtp_cipher,
1551       "srtp-auth", G_TYPE_STRING, srtp_auth,
1552       "srtcp-cipher", G_TYPE_STRING, srtp_cipher,
1553       "srtcp-auth", G_TYPE_STRING, srtp_auth, NULL);
1554
1555   return TRUE;
1556 }
1557
1558 static gboolean
1559 handle_mikey_data (GstRTSPClient * client, GstRTSPContext * ctx,
1560     guint8 * data, gsize size)
1561 {
1562   GstMIKEYMessage *msg;
1563   guint i, n_cs;
1564   GstCaps *caps = NULL;
1565   GstMIKEYPayloadKEMAC *kemac;
1566   const GstMIKEYPayloadKeyData *pkd;
1567   GstBuffer *key;
1568
1569   /* the MIKEY message contains a CSB or crypto session bundle. It is a
1570    * set of Crypto Sessions protected with the same master key.
1571    * In the context of SRTP, an RTP and its RTCP stream is part of a
1572    * crypto session */
1573   if ((msg = gst_mikey_message_new_from_data (data, size, NULL, NULL)) == NULL)
1574     goto parse_failed;
1575
1576   /* we can only handle SRTP crypto sessions for now */
1577   if (msg->map_type != GST_MIKEY_MAP_TYPE_SRTP)
1578     goto invalid_map_type;
1579
1580   /* get the number of crypto sessions. This maps SSRC to its
1581    * security parameters */
1582   n_cs = gst_mikey_message_get_n_cs (msg);
1583   if (n_cs == 0)
1584     goto no_crypto_sessions;
1585
1586   /* we also need keys */
1587   if (!(kemac = (GstMIKEYPayloadKEMAC *) gst_mikey_message_find_payload
1588           (msg, GST_MIKEY_PT_KEMAC, 0)))
1589     goto no_keys;
1590
1591   /* we don't support encrypted keys */
1592   if (kemac->enc_alg != GST_MIKEY_ENC_NULL
1593       || kemac->mac_alg != GST_MIKEY_MAC_NULL)
1594     goto unsupported_encryption;
1595
1596   /* get Key data sub-payload */
1597   pkd = (const GstMIKEYPayloadKeyData *)
1598       gst_mikey_payload_kemac_get_sub (&kemac->pt, 0);
1599
1600   key =
1601       gst_buffer_new_wrapped (g_memdup (pkd->key_data, pkd->key_len),
1602       pkd->key_len);
1603
1604   /* go over all crypto sessions and create the security policy for each
1605    * SSRC */
1606   for (i = 0; i < n_cs; i++) {
1607     const GstMIKEYMapSRTP *map = gst_mikey_message_get_cs_srtp (msg, i);
1608
1609     caps = gst_caps_new_simple ("application/x-srtp",
1610         "ssrc", G_TYPE_UINT, map->ssrc,
1611         "roc", G_TYPE_UINT, map->roc, "srtp-key", GST_TYPE_BUFFER, key, NULL);
1612     mikey_apply_policy (caps, msg, map->policy);
1613
1614     gst_rtsp_stream_update_crypto (ctx->stream, map->ssrc, caps);
1615     gst_caps_unref (caps);
1616   }
1617   gst_mikey_message_unref (msg);
1618
1619   return TRUE;
1620
1621   /* ERRORS */
1622 parse_failed:
1623   {
1624     GST_DEBUG_OBJECT (client, "failed to parse MIKEY message");
1625     return FALSE;
1626   }
1627 invalid_map_type:
1628   {
1629     GST_DEBUG_OBJECT (client, "invalid map type %d", msg->map_type);
1630     goto cleanup_message;
1631   }
1632 no_crypto_sessions:
1633   {
1634     GST_DEBUG_OBJECT (client, "no crypto sessions");
1635     goto cleanup_message;
1636   }
1637 no_keys:
1638   {
1639     GST_DEBUG_OBJECT (client, "no keys found");
1640     goto cleanup_message;
1641   }
1642 unsupported_encryption:
1643   {
1644     GST_DEBUG_OBJECT (client, "unsupported key encryption");
1645     goto cleanup_message;
1646   }
1647 cleanup_message:
1648   {
1649     gst_mikey_message_unref (msg);
1650     return FALSE;
1651   }
1652 }
1653
1654 #define IS_STRIP_CHAR(c) (g_ascii_isspace ((guchar)(c)) || ((c) == '\"'))
1655
1656 static void
1657 strip_chars (gchar * str)
1658 {
1659   gchar *s;
1660   gsize len;
1661
1662   len = strlen (str);
1663   while (len--) {
1664     if (!IS_STRIP_CHAR (str[len]))
1665       break;
1666     str[len] = '\0';
1667   }
1668   for (s = str; *s && IS_STRIP_CHAR (*s); s++);
1669   memmove (str, s, len + 1);
1670 }
1671
1672 /* KeyMgmt = "KeyMgmt" ":" key-mgmt-spec 0*("," key-mgmt-spec)
1673  * key-mgmt-spec = "prot" "=" KMPID ";" ["uri" "=" %x22 URI %x22 ";"]
1674  */
1675 static gboolean
1676 handle_keymgmt (GstRTSPClient * client, GstRTSPContext * ctx, gchar * keymgmt)
1677 {
1678   gchar **specs;
1679   gint i, j;
1680
1681   specs = g_strsplit (keymgmt, ",", 0);
1682   for (i = 0; specs[i]; i++) {
1683     gchar **split;
1684
1685     split = g_strsplit (specs[i], ";", 0);
1686     for (j = 0; split[j]; j++) {
1687       g_strstrip (split[j]);
1688       if (g_str_has_prefix (split[j], "prot=")) {
1689         g_strstrip (split[j] + 5);
1690         if (!g_str_equal (split[j] + 5, "mikey"))
1691           break;
1692         GST_DEBUG ("found mikey");
1693       } else if (g_str_has_prefix (split[j], "uri=")) {
1694         strip_chars (split[j] + 4);
1695         GST_DEBUG ("found uri '%s'", split[j] + 4);
1696       } else if (g_str_has_prefix (split[j], "data=")) {
1697         guchar *data;
1698         gsize size;
1699         strip_chars (split[j] + 5);
1700         GST_DEBUG ("found data '%s'", split[j] + 5);
1701         data = g_base64_decode_inplace (split[j] + 5, &size);
1702         handle_mikey_data (client, ctx, data, size);
1703       }
1704     }
1705   }
1706   return TRUE;
1707 }
1708
1709 static gboolean
1710 handle_setup_request (GstRTSPClient * client, GstRTSPContext * ctx)
1711 {
1712   GstRTSPClientPrivate *priv = client->priv;
1713   GstRTSPResult res;
1714   GstRTSPUrl *uri;
1715   gchar *transport, *keymgmt;
1716   GstRTSPTransport *ct, *st;
1717   GstRTSPStatusCode code;
1718   GstRTSPSession *session;
1719   GstRTSPStreamTransport *trans;
1720   gchar *trans_str;
1721   GstRTSPSessionMedia *sessmedia;
1722   GstRTSPMedia *media;
1723   GstRTSPStream *stream;
1724   GstRTSPState rtspstate;
1725   GstRTSPClientClass *klass;
1726   gchar *path, *control;
1727   gint matched;
1728   gboolean new_session = FALSE;
1729
1730   if (!ctx->uri)
1731     goto no_uri;
1732
1733   uri = ctx->uri;
1734   klass = GST_RTSP_CLIENT_GET_CLASS (client);
1735   path = klass->make_path_from_uri (client, uri);
1736
1737   /* parse the transport */
1738   res =
1739       gst_rtsp_message_get_header (ctx->request, GST_RTSP_HDR_TRANSPORT,
1740       &transport, 0);
1741   if (res != GST_RTSP_OK)
1742     goto no_transport;
1743
1744   /* we create the session after parsing stuff so that we don't make
1745    * a session for malformed requests */
1746   if (priv->session_pool == NULL)
1747     goto no_pool;
1748
1749   session = ctx->session;
1750
1751   if (session) {
1752     g_object_ref (session);
1753     /* get a handle to the configuration of the media in the session, this can
1754      * return NULL if this is a new url to manage in this session. */
1755     sessmedia = gst_rtsp_session_get_media (session, path, &matched);
1756   } else {
1757     /* we need a new media configuration in this session */
1758     sessmedia = NULL;
1759   }
1760
1761   /* we have no session media, find one and manage it */
1762   if (sessmedia == NULL) {
1763     /* get a handle to the configuration of the media in the session */
1764     media = find_media (client, ctx, path, &matched);
1765   } else {
1766     if ((media = gst_rtsp_session_media_get_media (sessmedia)))
1767       g_object_ref (media);
1768     else
1769       goto media_not_found;
1770   }
1771   /* no media, not found then */
1772   if (media == NULL)
1773     goto media_not_found_no_reply;
1774
1775   if (path[matched] == '\0')
1776     goto control_not_found;
1777
1778   /* path is what matched. */
1779   path[matched] = '\0';
1780   /* control is remainder */
1781   control = &path[matched + 1];
1782
1783   /* find the stream now using the control part */
1784   stream = gst_rtsp_media_find_stream (media, control);
1785   if (stream == NULL)
1786     goto stream_not_found;
1787
1788   /* now we have a uri identifying a valid media and stream */
1789   ctx->stream = stream;
1790   ctx->media = media;
1791
1792   if (session == NULL) {
1793     /* create a session if this fails we probably reached our session limit or
1794      * something. */
1795     if (!(session = gst_rtsp_session_pool_create (priv->session_pool)))
1796       goto service_unavailable;
1797
1798     /* make sure this client is closed when the session is closed */
1799     client_watch_session (client, session);
1800
1801     new_session = TRUE;
1802     /* signal new session */
1803     g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_NEW_SESSION], 0,
1804         session);
1805
1806     ctx->session = session;
1807   }
1808
1809   if (!klass->configure_client_media (client, media, stream, ctx))
1810     goto configure_media_failed_no_reply;
1811
1812   gst_rtsp_transport_new (&ct);
1813
1814   /* parse and find a usable supported transport */
1815   if (!parse_transport (transport, stream, ct))
1816     goto unsupported_transports;
1817
1818   /* update the client transport */
1819   if (!klass->configure_client_transport (client, ctx, ct))
1820     goto unsupported_client_transport;
1821
1822   /* parse the keymgmt */
1823   if (gst_rtsp_message_get_header (ctx->request, GST_RTSP_HDR_KEYMGMT,
1824           &keymgmt, 0) == GST_RTSP_OK) {
1825     if (!handle_keymgmt (client, ctx, keymgmt))
1826       goto keymgmt_error;
1827   }
1828
1829   if (sessmedia == NULL) {
1830     /* manage the media in our session now, if not done already  */
1831     sessmedia = gst_rtsp_session_manage_media (session, path, media);
1832     /* if we stil have no media, error */
1833     if (sessmedia == NULL)
1834       goto sessmedia_unavailable;
1835   } else {
1836     g_object_unref (media);
1837   }
1838
1839   ctx->sessmedia = sessmedia;
1840
1841   /* set in the session media transport */
1842   trans = gst_rtsp_session_media_set_transport (sessmedia, stream, ct);
1843
1844   /* configure the url used to set this transport, this we will use when
1845    * generating the response for the PLAY request */
1846   gst_rtsp_stream_transport_set_url (trans, uri);
1847   /* configure keepalive for this transport */
1848   gst_rtsp_stream_transport_set_keepalive (trans,
1849       (GstRTSPKeepAliveFunc) do_keepalive, session, NULL);
1850
1851   if (ct->lower_transport == GST_RTSP_LOWER_TRANS_TCP) {
1852     /* our callbacks to send data on this TCP connection */
1853     gst_rtsp_stream_transport_set_callbacks (trans,
1854         (GstRTSPSendFunc) do_send_data,
1855         (GstRTSPSendFunc) do_send_data, client, NULL);
1856
1857     g_hash_table_insert (priv->transports,
1858         GINT_TO_POINTER (ct->interleaved.min), trans);
1859     g_hash_table_insert (priv->transports,
1860         GINT_TO_POINTER (ct->interleaved.max), trans);
1861   }
1862
1863   /* create and serialize the server transport */
1864   st = make_server_transport (client, ctx, ct);
1865   trans_str = gst_rtsp_transport_as_text (st);
1866   gst_rtsp_transport_free (st);
1867
1868   /* construct the response now */
1869   code = GST_RTSP_STS_OK;
1870   gst_rtsp_message_init_response (ctx->response, code,
1871       gst_rtsp_status_as_text (code), ctx->request);
1872
1873   gst_rtsp_message_add_header (ctx->response, GST_RTSP_HDR_TRANSPORT,
1874       trans_str);
1875   g_free (trans_str);
1876
1877   send_message (client, ctx, ctx->response, FALSE);
1878
1879   /* update the state */
1880   rtspstate = gst_rtsp_session_media_get_rtsp_state (sessmedia);
1881   switch (rtspstate) {
1882     case GST_RTSP_STATE_PLAYING:
1883     case GST_RTSP_STATE_RECORDING:
1884     case GST_RTSP_STATE_READY:
1885       /* no state change */
1886       break;
1887     default:
1888       gst_rtsp_session_media_set_rtsp_state (sessmedia, GST_RTSP_STATE_READY);
1889       break;
1890   }
1891   g_object_unref (session);
1892   g_free (path);
1893
1894   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_SETUP_REQUEST], 0, ctx);
1895
1896   return TRUE;
1897
1898   /* ERRORS */
1899 no_uri:
1900   {
1901     GST_ERROR ("client %p: no uri", client);
1902     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
1903     return FALSE;
1904   }
1905 no_transport:
1906   {
1907     GST_ERROR ("client %p: no transport", client);
1908     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, ctx);
1909     goto cleanup_path;
1910   }
1911 no_pool:
1912   {
1913     GST_ERROR ("client %p: no session pool configured", client);
1914     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
1915     goto cleanup_path;
1916   }
1917 media_not_found_no_reply:
1918   {
1919     GST_ERROR ("client %p: media '%s' not found", client, path);
1920     /* error reply is already sent */
1921     goto cleanup_path;
1922   }
1923 media_not_found:
1924   {
1925     GST_ERROR ("client %p: media '%s' not found", client, path);
1926     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
1927     goto cleanup_path;
1928   }
1929 control_not_found:
1930   {
1931     GST_ERROR ("client %p: no control in path '%s'", client, path);
1932     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
1933     g_object_unref (media);
1934     goto cleanup_path;
1935   }
1936 stream_not_found:
1937   {
1938     GST_ERROR ("client %p: stream '%s' not found", client, control);
1939     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
1940     g_object_unref (media);
1941     goto cleanup_path;
1942   }
1943 service_unavailable:
1944   {
1945     GST_ERROR ("client %p: can't create session", client);
1946     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, ctx);
1947     g_object_unref (media);
1948     goto cleanup_path;
1949   }
1950 sessmedia_unavailable:
1951   {
1952     GST_ERROR ("client %p: can't create session media", client);
1953     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, ctx);
1954     g_object_unref (media);
1955     goto cleanup_session;
1956   }
1957 configure_media_failed_no_reply:
1958   {
1959     GST_ERROR ("client %p: configure_media failed", client);
1960     /* error reply is already sent */
1961     goto cleanup_session;
1962   }
1963 unsupported_transports:
1964   {
1965     GST_ERROR ("client %p: unsupported transports", client);
1966     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, ctx);
1967     goto cleanup_transport;
1968   }
1969 unsupported_client_transport:
1970   {
1971     GST_ERROR ("client %p: unsupported client transport", client);
1972     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, ctx);
1973     goto cleanup_transport;
1974   }
1975 keymgmt_error:
1976   {
1977     GST_ERROR ("client %p: keymgmt error", client);
1978     send_generic_response (client, GST_RTSP_STS_KEY_MANAGEMENT_FAILURE, ctx);
1979     goto cleanup_transport;
1980   }
1981   {
1982   cleanup_transport:
1983     gst_rtsp_transport_free (ct);
1984   cleanup_session:
1985     if (new_session)
1986       gst_rtsp_session_pool_remove (priv->session_pool, session);
1987     g_object_unref (session);
1988   cleanup_path:
1989     g_free (path);
1990     return FALSE;
1991   }
1992 }
1993
1994 static GstSDPMessage *
1995 create_sdp (GstRTSPClient * client, GstRTSPMedia * media)
1996 {
1997   GstRTSPClientPrivate *priv = client->priv;
1998   GstSDPMessage *sdp;
1999   GstSDPInfo info;
2000   const gchar *proto;
2001
2002   gst_sdp_message_new (&sdp);
2003
2004   /* some standard things first */
2005   gst_sdp_message_set_version (sdp, "0");
2006
2007   if (priv->is_ipv6)
2008     proto = "IP6";
2009   else
2010     proto = "IP4";
2011
2012   gst_sdp_message_set_origin (sdp, "-", "1188340656180883", "1", "IN", proto,
2013       priv->server_ip);
2014
2015   gst_sdp_message_set_session_name (sdp, "Session streamed with GStreamer");
2016   gst_sdp_message_set_information (sdp, "rtsp-server");
2017   gst_sdp_message_add_time (sdp, "0", "0", NULL);
2018   gst_sdp_message_add_attribute (sdp, "tool", "GStreamer");
2019   gst_sdp_message_add_attribute (sdp, "type", "broadcast");
2020   gst_sdp_message_add_attribute (sdp, "control", "*");
2021
2022   info.is_ipv6 = priv->is_ipv6;
2023   info.server_ip = priv->server_ip;
2024
2025   /* create an SDP for the media object */
2026   if (!gst_rtsp_media_setup_sdp (media, sdp, &info))
2027     goto no_sdp;
2028
2029   return sdp;
2030
2031   /* ERRORS */
2032 no_sdp:
2033   {
2034     GST_ERROR ("client %p: could not create SDP", client);
2035     gst_sdp_message_free (sdp);
2036     return NULL;
2037   }
2038 }
2039
2040 /* for the describe we must generate an SDP */
2041 static gboolean
2042 handle_describe_request (GstRTSPClient * client, GstRTSPContext * ctx)
2043 {
2044   GstRTSPClientPrivate *priv = client->priv;
2045   GstRTSPResult res;
2046   GstSDPMessage *sdp;
2047   guint i;
2048   gchar *path, *str;
2049   GstRTSPMedia *media;
2050   GstRTSPClientClass *klass;
2051
2052   klass = GST_RTSP_CLIENT_GET_CLASS (client);
2053
2054   if (!ctx->uri)
2055     goto no_uri;
2056
2057   /* check what kind of format is accepted, we don't really do anything with it
2058    * and always return SDP for now. */
2059   for (i = 0;; i++) {
2060     gchar *accept;
2061
2062     res =
2063         gst_rtsp_message_get_header (ctx->request, GST_RTSP_HDR_ACCEPT,
2064         &accept, i);
2065     if (res == GST_RTSP_ENOTIMPL)
2066       break;
2067
2068     if (g_ascii_strcasecmp (accept, "application/sdp") == 0)
2069       break;
2070   }
2071
2072   if (!priv->mount_points)
2073     goto no_mount_points;
2074
2075   if (!(path = gst_rtsp_mount_points_make_path (priv->mount_points, ctx->uri)))
2076     goto no_path;
2077
2078   /* find the media object for the uri */
2079   if (!(media = find_media (client, ctx, path, NULL)))
2080     goto no_media;
2081
2082   /* create an SDP for the media object on this client */
2083   if (!(sdp = klass->create_sdp (client, media)))
2084     goto no_sdp;
2085
2086   /* we suspend after the describe */
2087   gst_rtsp_media_suspend (media);
2088   g_object_unref (media);
2089
2090   gst_rtsp_message_init_response (ctx->response, GST_RTSP_STS_OK,
2091       gst_rtsp_status_as_text (GST_RTSP_STS_OK), ctx->request);
2092
2093   gst_rtsp_message_add_header (ctx->response, GST_RTSP_HDR_CONTENT_TYPE,
2094       "application/sdp");
2095
2096   /* content base for some clients that might screw up creating the setup uri */
2097   str = make_base_url (client, ctx->uri, path);
2098   g_free (path);
2099
2100   GST_INFO ("adding content-base: %s", str);
2101   gst_rtsp_message_take_header (ctx->response, GST_RTSP_HDR_CONTENT_BASE, str);
2102
2103   /* add SDP to the response body */
2104   str = gst_sdp_message_as_text (sdp);
2105   gst_rtsp_message_take_body (ctx->response, (guint8 *) str, strlen (str));
2106   gst_sdp_message_free (sdp);
2107
2108   send_message (client, ctx, ctx->response, FALSE);
2109
2110   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_DESCRIBE_REQUEST],
2111       0, ctx);
2112
2113   return TRUE;
2114
2115   /* ERRORS */
2116 no_uri:
2117   {
2118     GST_ERROR ("client %p: no uri", client);
2119     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
2120     return FALSE;
2121   }
2122 no_mount_points:
2123   {
2124     GST_ERROR ("client %p: no mount points configured", client);
2125     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
2126     return FALSE;
2127   }
2128 no_path:
2129   {
2130     GST_ERROR ("client %p: can't find path for url", client);
2131     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
2132     return FALSE;
2133   }
2134 no_media:
2135   {
2136     GST_ERROR ("client %p: no media", client);
2137     g_free (path);
2138     /* error reply is already sent */
2139     return FALSE;
2140   }
2141 no_sdp:
2142   {
2143     GST_ERROR ("client %p: can't create SDP", client);
2144     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, ctx);
2145     g_free (path);
2146     g_object_unref (media);
2147     return FALSE;
2148   }
2149 }
2150
2151 static gboolean
2152 handle_options_request (GstRTSPClient * client, GstRTSPContext * ctx)
2153 {
2154   GstRTSPMethod options;
2155   gchar *str;
2156
2157   options = GST_RTSP_DESCRIBE |
2158       GST_RTSP_OPTIONS |
2159       GST_RTSP_PAUSE |
2160       GST_RTSP_PLAY |
2161       GST_RTSP_SETUP |
2162       GST_RTSP_GET_PARAMETER | GST_RTSP_SET_PARAMETER | GST_RTSP_TEARDOWN;
2163
2164   str = gst_rtsp_options_as_text (options);
2165
2166   gst_rtsp_message_init_response (ctx->response, GST_RTSP_STS_OK,
2167       gst_rtsp_status_as_text (GST_RTSP_STS_OK), ctx->request);
2168
2169   gst_rtsp_message_add_header (ctx->response, GST_RTSP_HDR_PUBLIC, str);
2170   g_free (str);
2171
2172   send_message (client, ctx, ctx->response, FALSE);
2173
2174   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_OPTIONS_REQUEST],
2175       0, ctx);
2176
2177   return TRUE;
2178 }
2179
2180 /* remove duplicate and trailing '/' */
2181 static void
2182 sanitize_uri (GstRTSPUrl * uri)
2183 {
2184   gint i, len;
2185   gchar *s, *d;
2186   gboolean have_slash, prev_slash;
2187
2188   s = d = uri->abspath;
2189   len = strlen (uri->abspath);
2190
2191   prev_slash = FALSE;
2192
2193   for (i = 0; i < len; i++) {
2194     have_slash = s[i] == '/';
2195     *d = s[i];
2196     if (!have_slash || !prev_slash)
2197       d++;
2198     prev_slash = have_slash;
2199   }
2200   len = d - uri->abspath;
2201   /* don't remove the first slash if that's the only thing left */
2202   if (len > 1 && *(d - 1) == '/')
2203     d--;
2204   *d = '\0';
2205 }
2206
2207 /* is called when the session is removed from its session pool. */
2208 static void
2209 client_session_removed (GstRTSPSessionPool * pool, GstRTSPSession * session,
2210     GstRTSPClient * client)
2211 {
2212   GstRTSPClientPrivate *priv = client->priv;
2213
2214   GST_INFO ("client %p: session %p removed", client, session);
2215
2216   g_mutex_lock (&priv->lock);
2217   if (priv->watch != NULL)
2218     gst_rtsp_watch_set_send_backlog (priv->watch, 0, 0);
2219   client_unwatch_session (client, session, NULL);
2220   if (priv->watch != NULL)
2221     gst_rtsp_watch_set_send_backlog (priv->watch, 0, WATCH_BACKLOG_SIZE);
2222   g_mutex_unlock (&priv->lock);
2223 }
2224
2225 /* Returns TRUE if there are no Require headers, otherwise returns FALSE
2226  * and also returns a newly-allocated string of (comma-separated) unsupported
2227  * options in the unsupported_reqs variable .
2228  *
2229  * There may be multiple Require headers, but we must send one single
2230  * Unsupported header with all the unsupported options as response. If
2231  * an incoming Require header contained a comma-separated list of options
2232  * GstRtspConnection will already have split that list up into multiple
2233  * headers.
2234  *
2235  * TODO: allow the application to decide what features are supported
2236  */
2237 static gboolean
2238 check_request_requirements (GstRTSPMessage * msg, gchar ** unsupported_reqs)
2239 {
2240   GstRTSPResult res;
2241   GPtrArray *arr = NULL;
2242   gchar *reqs = NULL;
2243   gint i;
2244
2245   i = 0;
2246   do {
2247     res = gst_rtsp_message_get_header (msg, GST_RTSP_HDR_REQUIRE, &reqs, i++);
2248
2249     if (res == GST_RTSP_ENOTIMPL)
2250       break;
2251
2252     if (arr == NULL)
2253       arr = g_ptr_array_new_with_free_func ((GDestroyNotify) g_free);
2254
2255     g_ptr_array_add (arr, g_strdup (reqs));
2256   }
2257   while (TRUE);
2258
2259   /* if we don't have any Require headers at all, all is fine */
2260   if (i == 1)
2261     return TRUE;
2262
2263   /* otherwise we've now processed at all the Require headers */
2264   g_ptr_array_add (arr, NULL);
2265
2266   /* for now we don't commit to supporting anything, so will just report
2267    * all of the required options as unsupported */
2268   *unsupported_reqs = g_strjoinv (", ", (gchar **) arr->pdata);
2269
2270   g_ptr_array_unref (arr);
2271   return FALSE;
2272 }
2273
2274 static void
2275 handle_request (GstRTSPClient * client, GstRTSPMessage * request)
2276 {
2277   GstRTSPClientPrivate *priv = client->priv;
2278   GstRTSPMethod method;
2279   const gchar *uristr;
2280   GstRTSPUrl *uri = NULL;
2281   GstRTSPVersion version;
2282   GstRTSPResult res;
2283   GstRTSPSession *session = NULL;
2284   GstRTSPContext sctx = { NULL }, *ctx;
2285   GstRTSPMessage response = { 0 };
2286   gchar *unsupported_reqs = NULL;
2287   gchar *sessid;
2288
2289   if (!(ctx = gst_rtsp_context_get_current ())) {
2290     ctx = &sctx;
2291     ctx->auth = priv->auth;
2292     gst_rtsp_context_push_current (ctx);
2293   }
2294
2295   ctx->conn = priv->connection;
2296   ctx->client = client;
2297   ctx->request = request;
2298   ctx->response = &response;
2299
2300   if (gst_debug_category_get_threshold (rtsp_client_debug) >= GST_LEVEL_LOG) {
2301     gst_rtsp_message_dump (request);
2302   }
2303
2304   gst_rtsp_message_parse_request (request, &method, &uristr, &version);
2305
2306   GST_INFO ("client %p: received a request %s %s %s", client,
2307       gst_rtsp_method_as_text (method), uristr,
2308       gst_rtsp_version_as_text (version));
2309
2310   /* we can only handle 1.0 requests */
2311   if (version != GST_RTSP_VERSION_1_0)
2312     goto not_supported;
2313
2314   ctx->method = method;
2315
2316   /* we always try to parse the url first */
2317   if (strcmp (uristr, "*") == 0) {
2318     /* special case where we have * as uri, keep uri = NULL */
2319   } else if (gst_rtsp_url_parse (uristr, &uri) != GST_RTSP_OK) {
2320     /* check if the uristr is an absolute path <=> scheme and host information
2321      * is missing */
2322     gchar *scheme;
2323
2324     scheme = g_uri_parse_scheme (uristr);
2325     if (scheme == NULL && g_str_has_prefix (uristr, "/")) {
2326       gchar *absolute_uristr = NULL;
2327
2328       GST_WARNING_OBJECT (client, "request doesn't contain absolute url");
2329       if (priv->server_ip == NULL) {
2330         GST_WARNING_OBJECT (client, "host information missing");
2331         goto bad_request;
2332       }
2333
2334       absolute_uristr =
2335           g_strdup_printf ("rtsp://%s%s", priv->server_ip, uristr);
2336
2337       GST_DEBUG_OBJECT (client, "absolute url: %s", absolute_uristr);
2338       if (gst_rtsp_url_parse (absolute_uristr, &uri) != GST_RTSP_OK) {
2339         g_free (absolute_uristr);
2340         goto bad_request;
2341       }
2342       g_free (absolute_uristr);
2343     } else {
2344       g_free (scheme);
2345       goto bad_request;
2346     }
2347   }
2348
2349   /* get the session if there is any */
2350   res = gst_rtsp_message_get_header (request, GST_RTSP_HDR_SESSION, &sessid, 0);
2351   if (res == GST_RTSP_OK) {
2352     if (priv->session_pool == NULL)
2353       goto no_pool;
2354
2355     /* we had a session in the request, find it again */
2356     if (!(session = gst_rtsp_session_pool_find (priv->session_pool, sessid)))
2357       goto session_not_found;
2358
2359     /* we add the session to the client list of watched sessions. When a session
2360      * disappears because it times out, we will be notified. If all sessions are
2361      * gone, we will close the connection */
2362     client_watch_session (client, session);
2363   }
2364
2365   /* sanitize the uri */
2366   if (uri)
2367     sanitize_uri (uri);
2368   ctx->uri = uri;
2369   ctx->session = session;
2370
2371   if (!gst_rtsp_auth_check (GST_RTSP_AUTH_CHECK_URL))
2372     goto not_authorized;
2373
2374   /* handle any 'Require' headers */
2375   if (!check_request_requirements (ctx->request, &unsupported_reqs))
2376     goto unsupported_requirement;
2377
2378   /* now see what is asked and dispatch to a dedicated handler */
2379   switch (method) {
2380     case GST_RTSP_OPTIONS:
2381       handle_options_request (client, ctx);
2382       break;
2383     case GST_RTSP_DESCRIBE:
2384       handle_describe_request (client, ctx);
2385       break;
2386     case GST_RTSP_SETUP:
2387       handle_setup_request (client, ctx);
2388       break;
2389     case GST_RTSP_PLAY:
2390       handle_play_request (client, ctx);
2391       break;
2392     case GST_RTSP_PAUSE:
2393       handle_pause_request (client, ctx);
2394       break;
2395     case GST_RTSP_TEARDOWN:
2396       handle_teardown_request (client, ctx);
2397       break;
2398     case GST_RTSP_SET_PARAMETER:
2399       handle_set_param_request (client, ctx);
2400       break;
2401     case GST_RTSP_GET_PARAMETER:
2402       handle_get_param_request (client, ctx);
2403       break;
2404     case GST_RTSP_ANNOUNCE:
2405     case GST_RTSP_RECORD:
2406     case GST_RTSP_REDIRECT:
2407       goto not_implemented;
2408     case GST_RTSP_INVALID:
2409     default:
2410       goto bad_request;
2411   }
2412
2413 done:
2414   if (ctx == &sctx)
2415     gst_rtsp_context_pop_current (ctx);
2416   if (session)
2417     g_object_unref (session);
2418   if (uri)
2419     gst_rtsp_url_free (uri);
2420   return;
2421
2422   /* ERRORS */
2423 not_supported:
2424   {
2425     GST_ERROR ("client %p: version %d not supported", client, version);
2426     send_generic_response (client, GST_RTSP_STS_RTSP_VERSION_NOT_SUPPORTED,
2427         ctx);
2428     goto done;
2429   }
2430 bad_request:
2431   {
2432     GST_ERROR ("client %p: bad request", client);
2433     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
2434     goto done;
2435   }
2436 no_pool:
2437   {
2438     GST_ERROR ("client %p: no pool configured", client);
2439     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
2440     goto done;
2441   }
2442 session_not_found:
2443   {
2444     GST_ERROR ("client %p: session not found", client);
2445     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
2446     goto done;
2447   }
2448 not_authorized:
2449   {
2450     GST_ERROR ("client %p: not allowed", client);
2451     /* error reply is already sent */
2452     goto done;
2453   }
2454 unsupported_requirement:
2455   {
2456     GST_ERROR ("client %p: Required option is not supported (%s)", client,
2457         unsupported_reqs);
2458     send_option_not_supported_response (client, ctx, unsupported_reqs);
2459     g_free (unsupported_reqs);
2460     goto done;
2461   }
2462 not_implemented:
2463   {
2464     GST_ERROR ("client %p: method %d not implemented", client, method);
2465     send_generic_response (client, GST_RTSP_STS_NOT_IMPLEMENTED, ctx);
2466     goto done;
2467   }
2468 }
2469
2470
2471 static void
2472 handle_response (GstRTSPClient * client, GstRTSPMessage * response)
2473 {
2474   GstRTSPClientPrivate *priv = client->priv;
2475   GstRTSPResult res;
2476   GstRTSPSession *session = NULL;
2477   GstRTSPContext sctx = { NULL }, *ctx;
2478   gchar *sessid;
2479
2480   if (!(ctx = gst_rtsp_context_get_current ())) {
2481     ctx = &sctx;
2482     ctx->auth = priv->auth;
2483     gst_rtsp_context_push_current (ctx);
2484   }
2485
2486   ctx->conn = priv->connection;
2487   ctx->client = client;
2488   ctx->request = NULL;
2489   ctx->uri = NULL;
2490   ctx->method = GST_RTSP_INVALID;
2491   ctx->response = response;
2492
2493   if (gst_debug_category_get_threshold (rtsp_client_debug) >= GST_LEVEL_LOG) {
2494     gst_rtsp_message_dump (response);
2495   }
2496
2497   GST_INFO ("client %p: received a response", client);
2498
2499   /* get the session if there is any */
2500   res =
2501       gst_rtsp_message_get_header (response, GST_RTSP_HDR_SESSION, &sessid, 0);
2502   if (res == GST_RTSP_OK) {
2503     if (priv->session_pool == NULL)
2504       goto no_pool;
2505
2506     /* we had a session in the request, find it again */
2507     if (!(session = gst_rtsp_session_pool_find (priv->session_pool, sessid)))
2508       goto session_not_found;
2509
2510     /* we add the session to the client list of watched sessions. When a session
2511      * disappears because it times out, we will be notified. If all sessions are
2512      * gone, we will close the connection */
2513     client_watch_session (client, session);
2514   }
2515
2516   ctx->session = session;
2517
2518   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_HANDLE_RESPONSE],
2519       0, ctx);
2520
2521 done:
2522   if (ctx == &sctx)
2523     gst_rtsp_context_pop_current (ctx);
2524   if (session)
2525     g_object_unref (session);
2526   return;
2527
2528 no_pool:
2529   {
2530     GST_ERROR ("client %p: no pool configured", client);
2531     goto done;
2532   }
2533 session_not_found:
2534   {
2535     GST_ERROR ("client %p: session not found", client);
2536     goto done;
2537   }
2538 }
2539
2540 static void
2541 handle_data (GstRTSPClient * client, GstRTSPMessage * message)
2542 {
2543   GstRTSPClientPrivate *priv = client->priv;
2544   GstRTSPResult res;
2545   guint8 channel;
2546   guint8 *data;
2547   guint size;
2548   GstBuffer *buffer;
2549   GstRTSPStreamTransport *trans;
2550
2551   /* find the stream for this message */
2552   res = gst_rtsp_message_parse_data (message, &channel);
2553   if (res != GST_RTSP_OK)
2554     return;
2555
2556   gst_rtsp_message_steal_body (message, &data, &size);
2557
2558   buffer = gst_buffer_new_wrapped (data, size);
2559
2560   trans =
2561       g_hash_table_lookup (priv->transports, GINT_TO_POINTER ((gint) channel));
2562   if (trans) {
2563     /* dispatch to the stream based on the channel number */
2564     gst_rtsp_stream_transport_recv_data (trans, channel, buffer);
2565   } else {
2566     gst_buffer_unref (buffer);
2567   }
2568 }
2569
2570 /**
2571  * gst_rtsp_client_set_session_pool:
2572  * @client: a #GstRTSPClient
2573  * @pool: (transfer none): a #GstRTSPSessionPool
2574  *
2575  * Set @pool as the sessionpool for @client which it will use to find
2576  * or allocate sessions. the sessionpool is usually inherited from the server
2577  * that created the client but can be overridden later.
2578  */
2579 void
2580 gst_rtsp_client_set_session_pool (GstRTSPClient * client,
2581     GstRTSPSessionPool * pool)
2582 {
2583   GstRTSPSessionPool *old;
2584   GstRTSPClientPrivate *priv;
2585
2586   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2587
2588   priv = client->priv;
2589
2590   if (pool)
2591     g_object_ref (pool);
2592
2593   g_mutex_lock (&priv->lock);
2594   old = priv->session_pool;
2595   priv->session_pool = pool;
2596
2597   if (priv->session_removed_id) {
2598     g_signal_handler_disconnect (old, priv->session_removed_id);
2599     priv->session_removed_id = 0;
2600   }
2601   g_mutex_unlock (&priv->lock);
2602
2603   /* FIXME, should remove all sessions from the old pool for this client */
2604   if (old)
2605     g_object_unref (old);
2606 }
2607
2608 /**
2609  * gst_rtsp_client_get_session_pool:
2610  * @client: a #GstRTSPClient
2611  *
2612  * Get the #GstRTSPSessionPool object that @client uses to manage its sessions.
2613  *
2614  * Returns: (transfer full): a #GstRTSPSessionPool, unref after usage.
2615  */
2616 GstRTSPSessionPool *
2617 gst_rtsp_client_get_session_pool (GstRTSPClient * client)
2618 {
2619   GstRTSPClientPrivate *priv;
2620   GstRTSPSessionPool *result;
2621
2622   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2623
2624   priv = client->priv;
2625
2626   g_mutex_lock (&priv->lock);
2627   if ((result = priv->session_pool))
2628     g_object_ref (result);
2629   g_mutex_unlock (&priv->lock);
2630
2631   return result;
2632 }
2633
2634 /**
2635  * gst_rtsp_client_set_mount_points:
2636  * @client: a #GstRTSPClient
2637  * @mounts: (transfer none): a #GstRTSPMountPoints
2638  *
2639  * Set @mounts as the mount points for @client which it will use to map urls
2640  * to media streams. These mount points are usually inherited from the server that
2641  * created the client but can be overriden later.
2642  */
2643 void
2644 gst_rtsp_client_set_mount_points (GstRTSPClient * client,
2645     GstRTSPMountPoints * mounts)
2646 {
2647   GstRTSPClientPrivate *priv;
2648   GstRTSPMountPoints *old;
2649
2650   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2651
2652   priv = client->priv;
2653
2654   if (mounts)
2655     g_object_ref (mounts);
2656
2657   g_mutex_lock (&priv->lock);
2658   old = priv->mount_points;
2659   priv->mount_points = mounts;
2660   g_mutex_unlock (&priv->lock);
2661
2662   if (old)
2663     g_object_unref (old);
2664 }
2665
2666 /**
2667  * gst_rtsp_client_get_mount_points:
2668  * @client: a #GstRTSPClient
2669  *
2670  * Get the #GstRTSPMountPoints object that @client uses to manage its sessions.
2671  *
2672  * Returns: (transfer full): a #GstRTSPMountPoints, unref after usage.
2673  */
2674 GstRTSPMountPoints *
2675 gst_rtsp_client_get_mount_points (GstRTSPClient * client)
2676 {
2677   GstRTSPClientPrivate *priv;
2678   GstRTSPMountPoints *result;
2679
2680   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2681
2682   priv = client->priv;
2683
2684   g_mutex_lock (&priv->lock);
2685   if ((result = priv->mount_points))
2686     g_object_ref (result);
2687   g_mutex_unlock (&priv->lock);
2688
2689   return result;
2690 }
2691
2692 /**
2693  * gst_rtsp_client_set_auth:
2694  * @client: a #GstRTSPClient
2695  * @auth: (transfer none): a #GstRTSPAuth
2696  *
2697  * configure @auth to be used as the authentication manager of @client.
2698  */
2699 void
2700 gst_rtsp_client_set_auth (GstRTSPClient * client, GstRTSPAuth * auth)
2701 {
2702   GstRTSPClientPrivate *priv;
2703   GstRTSPAuth *old;
2704
2705   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2706
2707   priv = client->priv;
2708
2709   if (auth)
2710     g_object_ref (auth);
2711
2712   g_mutex_lock (&priv->lock);
2713   old = priv->auth;
2714   priv->auth = auth;
2715   g_mutex_unlock (&priv->lock);
2716
2717   if (old)
2718     g_object_unref (old);
2719 }
2720
2721
2722 /**
2723  * gst_rtsp_client_get_auth:
2724  * @client: a #GstRTSPClient
2725  *
2726  * Get the #GstRTSPAuth used as the authentication manager of @client.
2727  *
2728  * Returns: (transfer full): the #GstRTSPAuth of @client. g_object_unref() after
2729  * usage.
2730  */
2731 GstRTSPAuth *
2732 gst_rtsp_client_get_auth (GstRTSPClient * client)
2733 {
2734   GstRTSPClientPrivate *priv;
2735   GstRTSPAuth *result;
2736
2737   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2738
2739   priv = client->priv;
2740
2741   g_mutex_lock (&priv->lock);
2742   if ((result = priv->auth))
2743     g_object_ref (result);
2744   g_mutex_unlock (&priv->lock);
2745
2746   return result;
2747 }
2748
2749 /**
2750  * gst_rtsp_client_set_thread_pool:
2751  * @client: a #GstRTSPClient
2752  * @pool: (transfer none): a #GstRTSPThreadPool
2753  *
2754  * configure @pool to be used as the thread pool of @client.
2755  */
2756 void
2757 gst_rtsp_client_set_thread_pool (GstRTSPClient * client,
2758     GstRTSPThreadPool * pool)
2759 {
2760   GstRTSPClientPrivate *priv;
2761   GstRTSPThreadPool *old;
2762
2763   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2764
2765   priv = client->priv;
2766
2767   if (pool)
2768     g_object_ref (pool);
2769
2770   g_mutex_lock (&priv->lock);
2771   old = priv->thread_pool;
2772   priv->thread_pool = pool;
2773   g_mutex_unlock (&priv->lock);
2774
2775   if (old)
2776     g_object_unref (old);
2777 }
2778
2779 /**
2780  * gst_rtsp_client_get_thread_pool:
2781  * @client: a #GstRTSPClient
2782  *
2783  * Get the #GstRTSPThreadPool used as the thread pool of @client.
2784  *
2785  * Returns: (transfer full): the #GstRTSPThreadPool of @client. g_object_unref() after
2786  * usage.
2787  */
2788 GstRTSPThreadPool *
2789 gst_rtsp_client_get_thread_pool (GstRTSPClient * client)
2790 {
2791   GstRTSPClientPrivate *priv;
2792   GstRTSPThreadPool *result;
2793
2794   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2795
2796   priv = client->priv;
2797
2798   g_mutex_lock (&priv->lock);
2799   if ((result = priv->thread_pool))
2800     g_object_ref (result);
2801   g_mutex_unlock (&priv->lock);
2802
2803   return result;
2804 }
2805
2806 /**
2807  * gst_rtsp_client_set_connection:
2808  * @client: a #GstRTSPClient
2809  * @conn: (transfer full): a #GstRTSPConnection
2810  *
2811  * Set the #GstRTSPConnection of @client. This function takes ownership of
2812  * @conn.
2813  *
2814  * Returns: %TRUE on success.
2815  */
2816 gboolean
2817 gst_rtsp_client_set_connection (GstRTSPClient * client,
2818     GstRTSPConnection * conn)
2819 {
2820   GstRTSPClientPrivate *priv;
2821   GSocket *read_socket;
2822   GSocketAddress *address;
2823   GstRTSPUrl *url;
2824   GError *error = NULL;
2825
2826   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), FALSE);
2827   g_return_val_if_fail (conn != NULL, FALSE);
2828
2829   priv = client->priv;
2830
2831   read_socket = gst_rtsp_connection_get_read_socket (conn);
2832
2833   if (!(address = g_socket_get_local_address (read_socket, &error)))
2834     goto no_address;
2835
2836   g_free (priv->server_ip);
2837   /* keep the original ip that the client connected to */
2838   if (G_IS_INET_SOCKET_ADDRESS (address)) {
2839     GInetAddress *iaddr;
2840
2841     iaddr = g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (address));
2842
2843     /* socket might be ipv6 but adress still ipv4 */
2844     priv->is_ipv6 = g_inet_address_get_family (iaddr) == G_SOCKET_FAMILY_IPV6;
2845     priv->server_ip = g_inet_address_to_string (iaddr);
2846     g_object_unref (address);
2847   } else {
2848     priv->is_ipv6 = g_socket_get_family (read_socket) == G_SOCKET_FAMILY_IPV6;
2849     priv->server_ip = g_strdup ("unknown");
2850   }
2851
2852   GST_INFO ("client %p connected to server ip %s, ipv6 = %d", client,
2853       priv->server_ip, priv->is_ipv6);
2854
2855   url = gst_rtsp_connection_get_url (conn);
2856   GST_INFO ("added new client %p ip %s:%d", client, url->host, url->port);
2857
2858   priv->connection = conn;
2859
2860   return TRUE;
2861
2862   /* ERRORS */
2863 no_address:
2864   {
2865     GST_ERROR ("could not get local address %s", error->message);
2866     g_error_free (error);
2867     return FALSE;
2868   }
2869 }
2870
2871 /**
2872  * gst_rtsp_client_get_connection:
2873  * @client: a #GstRTSPClient
2874  *
2875  * Get the #GstRTSPConnection of @client.
2876  *
2877  * Returns: (transfer none): the #GstRTSPConnection of @client.
2878  * The connection object returned remains valid until the client is freed.
2879  */
2880 GstRTSPConnection *
2881 gst_rtsp_client_get_connection (GstRTSPClient * client)
2882 {
2883   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2884
2885   return client->priv->connection;
2886 }
2887
2888 /**
2889  * gst_rtsp_client_set_send_func:
2890  * @client: a #GstRTSPClient
2891  * @func: (scope notified): a #GstRTSPClientSendFunc
2892  * @user_data: (closure): user data passed to @func
2893  * @notify: (allow-none): called when @user_data is no longer in use
2894  *
2895  * Set @func as the callback that will be called when a new message needs to be
2896  * sent to the client. @user_data is passed to @func and @notify is called when
2897  * @user_data is no longer in use.
2898  *
2899  * By default, the client will send the messages on the #GstRTSPConnection that
2900  * was configured with gst_rtsp_client_attach() was called.
2901  */
2902 void
2903 gst_rtsp_client_set_send_func (GstRTSPClient * client,
2904     GstRTSPClientSendFunc func, gpointer user_data, GDestroyNotify notify)
2905 {
2906   GstRTSPClientPrivate *priv;
2907   GDestroyNotify old_notify;
2908   gpointer old_data;
2909
2910   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2911
2912   priv = client->priv;
2913
2914   g_mutex_lock (&priv->send_lock);
2915   priv->send_func = func;
2916   old_notify = priv->send_notify;
2917   old_data = priv->send_data;
2918   priv->send_notify = notify;
2919   priv->send_data = user_data;
2920   g_mutex_unlock (&priv->send_lock);
2921
2922   if (old_notify)
2923     old_notify (old_data);
2924 }
2925
2926 /**
2927  * gst_rtsp_client_handle_message:
2928  * @client: a #GstRTSPClient
2929  * @message: (transfer none): an #GstRTSPMessage
2930  *
2931  * Let the client handle @message.
2932  *
2933  * Returns: a #GstRTSPResult.
2934  */
2935 GstRTSPResult
2936 gst_rtsp_client_handle_message (GstRTSPClient * client,
2937     GstRTSPMessage * message)
2938 {
2939   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), GST_RTSP_EINVAL);
2940   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2941
2942   switch (message->type) {
2943     case GST_RTSP_MESSAGE_REQUEST:
2944       handle_request (client, message);
2945       break;
2946     case GST_RTSP_MESSAGE_RESPONSE:
2947       handle_response (client, message);
2948       break;
2949     case GST_RTSP_MESSAGE_DATA:
2950       handle_data (client, message);
2951       break;
2952     default:
2953       break;
2954   }
2955   return GST_RTSP_OK;
2956 }
2957
2958 /**
2959  * gst_rtsp_client_send_message:
2960  * @client: a #GstRTSPClient
2961  * @session: (allow-none) (transfer none): a #GstRTSPSession to send
2962  *   the message to or %NULL
2963  * @message: (transfer none): The #GstRTSPMessage to send
2964  *
2965  * Send a message message to the remote end. @message must be a
2966  * #GST_RTSP_MESSAGE_REQUEST or a #GST_RTSP_MESSAGE_RESPONSE.
2967  */
2968 GstRTSPResult
2969 gst_rtsp_client_send_message (GstRTSPClient * client, GstRTSPSession * session,
2970     GstRTSPMessage * message)
2971 {
2972   GstRTSPContext sctx = { NULL }
2973   , *ctx;
2974   GstRTSPClientPrivate *priv;
2975
2976   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), GST_RTSP_EINVAL);
2977   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2978   g_return_val_if_fail (message->type == GST_RTSP_MESSAGE_REQUEST ||
2979       message->type == GST_RTSP_MESSAGE_RESPONSE, GST_RTSP_EINVAL);
2980
2981   priv = client->priv;
2982
2983   if (!(ctx = gst_rtsp_context_get_current ())) {
2984     ctx = &sctx;
2985     ctx->auth = priv->auth;
2986     gst_rtsp_context_push_current (ctx);
2987   }
2988
2989   ctx->conn = priv->connection;
2990   ctx->client = client;
2991   ctx->session = session;
2992
2993   send_message (client, ctx, message, FALSE);
2994
2995   if (ctx == &sctx)
2996     gst_rtsp_context_pop_current (ctx);
2997
2998   return GST_RTSP_OK;
2999 }
3000
3001 static GstRTSPResult
3002 do_send_message (GstRTSPClient * client, GstRTSPMessage * message,
3003     gboolean close, gpointer user_data)
3004 {
3005   GstRTSPClientPrivate *priv = client->priv;
3006   GstRTSPResult ret;
3007   GTimeVal time;
3008
3009   time.tv_sec = 1;
3010   time.tv_usec = 0;
3011
3012   do {
3013     /* send the response and store the seq number so we can wait until it's
3014      * written to the client to close the connection */
3015     ret =
3016         gst_rtsp_watch_send_message (priv->watch, message,
3017         close ? &priv->close_seq : NULL);
3018     if (ret == GST_RTSP_OK)
3019       break;
3020
3021     if (ret != GST_RTSP_ENOMEM)
3022       goto error;
3023
3024     /* drop backlog */
3025     if (priv->drop_backlog)
3026       break;
3027
3028     /* queue was full, wait for more space */
3029     GST_DEBUG_OBJECT (client, "waiting for backlog");
3030     ret = gst_rtsp_watch_wait_backlog (priv->watch, &time);
3031     GST_DEBUG_OBJECT (client, "Resend due to backlog full");
3032   } while (ret != GST_RTSP_EINTR);
3033
3034   return ret;
3035
3036   /* ERRORS */
3037 error:
3038   {
3039     GST_DEBUG_OBJECT (client, "got error %d", ret);
3040     return ret;
3041   }
3042 }
3043
3044 static GstRTSPResult
3045 message_received (GstRTSPWatch * watch, GstRTSPMessage * message,
3046     gpointer user_data)
3047 {
3048   return gst_rtsp_client_handle_message (GST_RTSP_CLIENT (user_data), message);
3049 }
3050
3051 static GstRTSPResult
3052 message_sent (GstRTSPWatch * watch, guint cseq, gpointer user_data)
3053 {
3054   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3055   GstRTSPClientPrivate *priv = client->priv;
3056
3057   if (priv->close_seq && priv->close_seq == cseq) {
3058     GST_INFO ("client %p: send close message", client);
3059     priv->close_seq = 0;
3060     gst_rtsp_client_close (client);
3061   }
3062
3063   return GST_RTSP_OK;
3064 }
3065
3066 static GstRTSPResult
3067 closed (GstRTSPWatch * watch, gpointer user_data)
3068 {
3069   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3070   GstRTSPClientPrivate *priv = client->priv;
3071   const gchar *tunnelid;
3072
3073   GST_INFO ("client %p: connection closed", client);
3074
3075   if ((tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection))) {
3076     g_mutex_lock (&tunnels_lock);
3077     /* remove from tunnelids */
3078     g_hash_table_remove (tunnels, tunnelid);
3079     g_mutex_unlock (&tunnels_lock);
3080   }
3081
3082   gst_rtsp_watch_set_flushing (watch, TRUE);
3083   g_mutex_lock (&priv->watch_lock);
3084   gst_rtsp_client_set_send_func (client, NULL, NULL, NULL);
3085   g_mutex_unlock (&priv->watch_lock);
3086
3087   return GST_RTSP_OK;
3088 }
3089
3090 static GstRTSPResult
3091 error (GstRTSPWatch * watch, GstRTSPResult result, gpointer user_data)
3092 {
3093   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3094   gchar *str;
3095
3096   str = gst_rtsp_strresult (result);
3097   GST_INFO ("client %p: received an error %s", client, str);
3098   g_free (str);
3099
3100   return GST_RTSP_OK;
3101 }
3102
3103 static GstRTSPResult
3104 error_full (GstRTSPWatch * watch, GstRTSPResult result,
3105     GstRTSPMessage * message, guint id, gpointer user_data)
3106 {
3107   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3108   gchar *str;
3109
3110   str = gst_rtsp_strresult (result);
3111   GST_INFO
3112       ("client %p: error when handling message %p with id %d: %s",
3113       client, message, id, str);
3114   g_free (str);
3115
3116   return GST_RTSP_OK;
3117 }
3118
3119 static gboolean
3120 remember_tunnel (GstRTSPClient * client)
3121 {
3122   GstRTSPClientPrivate *priv = client->priv;
3123   const gchar *tunnelid;
3124
3125   /* store client in the pending tunnels */
3126   tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection);
3127   if (tunnelid == NULL)
3128     goto no_tunnelid;
3129
3130   GST_INFO ("client %p: inserting tunnel session %s", client, tunnelid);
3131
3132   /* we can't have two clients connecting with the same tunnelid */
3133   g_mutex_lock (&tunnels_lock);
3134   if (g_hash_table_lookup (tunnels, tunnelid))
3135     goto tunnel_existed;
3136
3137   g_hash_table_insert (tunnels, g_strdup (tunnelid), g_object_ref (client));
3138   g_mutex_unlock (&tunnels_lock);
3139
3140   return TRUE;
3141
3142   /* ERRORS */
3143 no_tunnelid:
3144   {
3145     GST_ERROR ("client %p: no tunnelid provided", client);
3146     return FALSE;
3147   }
3148 tunnel_existed:
3149   {
3150     g_mutex_unlock (&tunnels_lock);
3151     GST_ERROR ("client %p: tunnel session %s already existed", client,
3152         tunnelid);
3153     return FALSE;
3154   }
3155 }
3156
3157 static GstRTSPResult
3158 tunnel_lost (GstRTSPWatch * watch, gpointer user_data)
3159 {
3160   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3161   GstRTSPClientPrivate *priv = client->priv;
3162
3163   GST_WARNING ("client %p: tunnel lost (connection %p)", client,
3164       priv->connection);
3165
3166   /* ignore error, it'll only be a problem when the client does a POST again */
3167   remember_tunnel (client);
3168
3169   return GST_RTSP_OK;
3170 }
3171
3172 static gboolean
3173 handle_tunnel (GstRTSPClient * client)
3174 {
3175   GstRTSPClientPrivate *priv = client->priv;
3176   GstRTSPClient *oclient;
3177   GstRTSPClientPrivate *opriv;
3178   const gchar *tunnelid;
3179
3180   tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection);
3181   if (tunnelid == NULL)
3182     goto no_tunnelid;
3183
3184   /* check for previous tunnel */
3185   g_mutex_lock (&tunnels_lock);
3186   oclient = g_hash_table_lookup (tunnels, tunnelid);
3187
3188   if (oclient == NULL) {
3189     /* no previous tunnel, remember tunnel */
3190     g_hash_table_insert (tunnels, g_strdup (tunnelid), g_object_ref (client));
3191     g_mutex_unlock (&tunnels_lock);
3192
3193     GST_INFO ("client %p: no previous tunnel found, remembering tunnel (%p)",
3194         client, priv->connection);
3195   } else {
3196     /* merge both tunnels into the first client */
3197     /* remove the old client from the table. ref before because removing it will
3198      * remove the ref to it. */
3199     g_object_ref (oclient);
3200     g_hash_table_remove (tunnels, tunnelid);
3201     g_mutex_unlock (&tunnels_lock);
3202
3203     opriv = oclient->priv;
3204
3205     g_mutex_lock (&opriv->watch_lock);
3206     if (opriv->watch == NULL)
3207       goto tunnel_closed;
3208
3209     GST_INFO ("client %p: found previous tunnel %p (old %p, new %p)", client,
3210         oclient, opriv->connection, priv->connection);
3211
3212     gst_rtsp_connection_do_tunnel (opriv->connection, priv->connection);
3213     gst_rtsp_watch_reset (priv->watch);
3214     gst_rtsp_watch_reset (opriv->watch);
3215     g_mutex_unlock (&opriv->watch_lock);
3216     g_object_unref (oclient);
3217
3218     /* the old client owns the tunnel now, the new one will be freed */
3219     g_source_destroy ((GSource *) priv->watch);
3220     priv->watch = NULL;
3221     gst_rtsp_client_set_send_func (client, NULL, NULL, NULL);
3222   }
3223
3224   return TRUE;
3225
3226   /* ERRORS */
3227 no_tunnelid:
3228   {
3229     GST_ERROR ("client %p: no tunnelid provided", client);
3230     return FALSE;
3231   }
3232 tunnel_closed:
3233   {
3234     GST_ERROR ("client %p: tunnel session %s was closed", client, tunnelid);
3235     g_mutex_unlock (&opriv->watch_lock);
3236     g_object_unref (oclient);
3237     return FALSE;
3238   }
3239 }
3240
3241 static GstRTSPStatusCode
3242 tunnel_get (GstRTSPWatch * watch, gpointer user_data)
3243 {
3244   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3245
3246   GST_INFO ("client %p: tunnel get (connection %p)", client,
3247       client->priv->connection);
3248
3249   if (!handle_tunnel (client)) {
3250     return GST_RTSP_STS_SERVICE_UNAVAILABLE;
3251   }
3252
3253   return GST_RTSP_STS_OK;
3254 }
3255
3256 static GstRTSPResult
3257 tunnel_post (GstRTSPWatch * watch, gpointer user_data)
3258 {
3259   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3260
3261   GST_INFO ("client %p: tunnel post (connection %p)", client,
3262       client->priv->connection);
3263
3264   if (!handle_tunnel (client)) {
3265     return GST_RTSP_ERROR;
3266   }
3267
3268   return GST_RTSP_OK;
3269 }
3270
3271 static GstRTSPResult
3272 tunnel_http_response (GstRTSPWatch * watch, GstRTSPMessage * request,
3273     GstRTSPMessage * response, gpointer user_data)
3274 {
3275   GstRTSPClientClass *klass;
3276
3277   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3278   klass = GST_RTSP_CLIENT_GET_CLASS (client);
3279
3280   if (klass->tunnel_http_response) {
3281     klass->tunnel_http_response (client, request, response);
3282   }
3283
3284   return GST_RTSP_OK;
3285 }
3286
3287 static GstRTSPWatchFuncs watch_funcs = {
3288   message_received,
3289   message_sent,
3290   closed,
3291   error,
3292   tunnel_get,
3293   tunnel_post,
3294   error_full,
3295   tunnel_lost,
3296   tunnel_http_response
3297 };
3298
3299 static void
3300 client_watch_notify (GstRTSPClient * client)
3301 {
3302   GstRTSPClientPrivate *priv = client->priv;
3303
3304   GST_INFO ("client %p: watch destroyed", client);
3305   priv->watch = 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 }