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