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