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