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