30c6b4dd338c74cfe37544534e95413bd4f77a39
[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   const GstMIKEYPayloadKeyData *pkd;
1488   GstBuffer *key;
1489
1490   /* the MIKEY message contains a CSB or crypto session bundle. It is a
1491    * set of Crypto Sessions protected with the same master key.
1492    * In the context of SRTP, an RTP and its RTCP stream is part of a
1493    * crypto session */
1494   if ((msg = gst_mikey_message_new_from_data (data, size, NULL, NULL)) == NULL)
1495     goto parse_failed;
1496
1497   /* we can only handle SRTP crypto sessions for now */
1498   if (msg->map_type != GST_MIKEY_MAP_TYPE_SRTP)
1499     goto invalid_map_type;
1500
1501   /* get the number of crypto sessions. This maps SSRC to its
1502    * security parameters */
1503   n_cs = gst_mikey_message_get_n_cs (msg);
1504   if (n_cs == 0)
1505     goto no_crypto_sessions;
1506
1507   /* we also need keys */
1508   if (!(kemac = (GstMIKEYPayloadKEMAC *) gst_mikey_message_find_payload
1509           (msg, GST_MIKEY_PT_KEMAC, 0)))
1510     goto no_keys;
1511
1512   /* we don't support encrypted keys */
1513   if (kemac->enc_alg != GST_MIKEY_ENC_NULL
1514       || kemac->mac_alg != GST_MIKEY_MAC_NULL)
1515     goto unsupported_encryption;
1516
1517   /* get Key data sub-payload */
1518   pkd = (const GstMIKEYPayloadKeyData *)
1519       gst_mikey_payload_kemac_get_sub (&kemac->pt, 0);
1520
1521   key =
1522       gst_buffer_new_wrapped (g_memdup (pkd->key_data, pkd->key_len),
1523       pkd->key_len);
1524
1525   /* go over all crypto sessions and create the security policy for each
1526    * SSRC */
1527   for (i = 0; i < n_cs; i++) {
1528     const GstMIKEYMapSRTP *map = gst_mikey_message_get_cs_srtp (msg, i);
1529
1530     caps = gst_caps_new_simple ("application/x-srtp",
1531         "ssrc", G_TYPE_UINT, map->ssrc,
1532         "roc", G_TYPE_UINT, map->roc, "srtp-key", GST_TYPE_BUFFER, key, NULL);
1533     mikey_apply_policy (caps, msg, map->policy);
1534
1535     gst_rtsp_stream_update_crypto (ctx->stream, map->ssrc, caps);
1536     gst_caps_unref (caps);
1537   }
1538   gst_mikey_message_free (msg);
1539
1540   return TRUE;
1541
1542   /* ERRORS */
1543 parse_failed:
1544   {
1545     GST_DEBUG_OBJECT (client, "failed to parse MIKEY message");
1546     return FALSE;
1547   }
1548 invalid_map_type:
1549   {
1550     GST_DEBUG_OBJECT (client, "invalid map type %d", msg->map_type);
1551     goto cleanup_message;
1552   }
1553 no_crypto_sessions:
1554   {
1555     GST_DEBUG_OBJECT (client, "no crypto sessions");
1556     goto cleanup_message;
1557   }
1558 no_keys:
1559   {
1560     GST_DEBUG_OBJECT (client, "no keys found");
1561     goto cleanup_message;
1562   }
1563 unsupported_encryption:
1564   {
1565     GST_DEBUG_OBJECT (client, "unsupported key encryption");
1566     goto cleanup_message;
1567   }
1568   {
1569   cleanup_message:
1570     gst_mikey_message_free (msg);
1571     return FALSE;
1572   }
1573 }
1574
1575 #define IS_STRIP_CHAR(c) (g_ascii_isspace ((guchar)(c)) || ((c) == '\"'))
1576
1577 static void
1578 strip_chars (gchar * str)
1579 {
1580   gchar *s;
1581   gsize len;
1582
1583   len = strlen (str);
1584   while (len--) {
1585     if (!IS_STRIP_CHAR (str[len]))
1586       break;
1587     str[len] = '\0';
1588   }
1589   for (s = str; *s && IS_STRIP_CHAR (*s); s++);
1590   memmove (str, s, len + 1);
1591 }
1592
1593 /**
1594  * KeyMgmt = "KeyMgmt" ":" key-mgmt-spec 0*("," key-mgmt-spec)
1595  * key-mgmt-spec = "prot" "=" KMPID ";" ["uri" "=" %x22 URI %x22 ";"]
1596  */
1597 static gboolean
1598 handle_keymgmt (GstRTSPClient * client, GstRTSPContext * ctx, gchar * keymgmt)
1599 {
1600   gchar **specs;
1601   gint i, j;
1602
1603   specs = g_strsplit (keymgmt, ",", 0);
1604   for (i = 0; specs[i]; i++) {
1605     gchar **split;
1606
1607     split = g_strsplit (specs[i], ";", 0);
1608     for (j = 0; split[j]; j++) {
1609       g_strstrip (split[j]);
1610       if (g_str_has_prefix (split[j], "prot=")) {
1611         g_strstrip (split[j] + 5);
1612         if (!g_str_equal (split[j] + 5, "mikey"))
1613           break;
1614         GST_DEBUG ("found mikey");
1615       } else if (g_str_has_prefix (split[j], "uri=")) {
1616         strip_chars (split[j] + 4);
1617         GST_DEBUG ("found uri '%s'", split[j] + 4);
1618       } else if (g_str_has_prefix (split[j], "data=")) {
1619         guchar *data;
1620         gsize size;
1621         strip_chars (split[j] + 5);
1622         GST_DEBUG ("found data '%s'", split[j] + 5);
1623         data = g_base64_decode_inplace (split[j] + 5, &size);
1624         handle_mikey_data (client, ctx, data, size);
1625       }
1626     }
1627   }
1628   return TRUE;
1629 }
1630
1631 static gboolean
1632 handle_setup_request (GstRTSPClient * client, GstRTSPContext * ctx)
1633 {
1634   GstRTSPClientPrivate *priv = client->priv;
1635   GstRTSPResult res;
1636   GstRTSPUrl *uri;
1637   gchar *transport, *keymgmt;
1638   GstRTSPTransport *ct, *st;
1639   GstRTSPStatusCode code;
1640   GstRTSPSession *session;
1641   GstRTSPStreamTransport *trans;
1642   gchar *trans_str;
1643   GstRTSPSessionMedia *sessmedia;
1644   GstRTSPMedia *media;
1645   GstRTSPStream *stream;
1646   GstRTSPState rtspstate;
1647   GstRTSPClientClass *klass;
1648   gchar *path, *control;
1649   gint matched;
1650
1651   if (!ctx->uri)
1652     goto no_uri;
1653
1654   uri = ctx->uri;
1655   klass = GST_RTSP_CLIENT_GET_CLASS (client);
1656   path = klass->make_path_from_uri (client, uri);
1657
1658   /* parse the transport */
1659   res =
1660       gst_rtsp_message_get_header (ctx->request, GST_RTSP_HDR_TRANSPORT,
1661       &transport, 0);
1662   if (res != GST_RTSP_OK)
1663     goto no_transport;
1664
1665   /* we create the session after parsing stuff so that we don't make
1666    * a session for malformed requests */
1667   if (priv->session_pool == NULL)
1668     goto no_pool;
1669
1670   session = ctx->session;
1671
1672   if (session) {
1673     g_object_ref (session);
1674     /* get a handle to the configuration of the media in the session, this can
1675      * return NULL if this is a new url to manage in this session. */
1676     sessmedia = gst_rtsp_session_get_media (session, path, &matched);
1677   } else {
1678     /* we need a new media configuration in this session */
1679     sessmedia = NULL;
1680   }
1681
1682   /* we have no session media, find one and manage it */
1683   if (sessmedia == NULL) {
1684     /* get a handle to the configuration of the media in the session */
1685     media = find_media (client, ctx, path, &matched);
1686   } else {
1687     if ((media = gst_rtsp_session_media_get_media (sessmedia)))
1688       g_object_ref (media);
1689     else
1690       goto media_not_found;
1691   }
1692   /* no media, not found then */
1693   if (media == NULL)
1694     goto media_not_found_no_reply;
1695
1696   if (path[matched] == '\0')
1697     goto control_not_found;
1698
1699   /* path is what matched. */
1700   path[matched] = '\0';
1701   /* control is remainder */
1702   control = &path[matched + 1];
1703
1704   /* find the stream now using the control part */
1705   stream = gst_rtsp_media_find_stream (media, control);
1706   if (stream == NULL)
1707     goto stream_not_found;
1708
1709   /* now we have a uri identifying a valid media and stream */
1710   ctx->stream = stream;
1711   ctx->media = media;
1712
1713   if (session == NULL) {
1714     /* create a session if this fails we probably reached our session limit or
1715      * something. */
1716     if (!(session = gst_rtsp_session_pool_create (priv->session_pool)))
1717       goto service_unavailable;
1718
1719     /* make sure this client is closed when the session is closed */
1720     client_watch_session (client, session);
1721
1722     /* signal new session */
1723     g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_NEW_SESSION], 0,
1724         session);
1725
1726     ctx->session = session;
1727   }
1728
1729   if (sessmedia == NULL) {
1730     /* manage the media in our session now, if not done already  */
1731     sessmedia = gst_rtsp_session_manage_media (session, path, media);
1732     /* if we stil have no media, error */
1733     if (sessmedia == NULL)
1734       goto sessmedia_unavailable;
1735   } else {
1736     g_object_unref (media);
1737   }
1738
1739   ctx->sessmedia = sessmedia;
1740
1741   if (!klass->configure_client_media (client, media, stream, ctx))
1742     goto configure_media_failed_no_reply;
1743
1744   gst_rtsp_transport_new (&ct);
1745
1746   /* parse and find a usable supported transport */
1747   if (!parse_transport (transport, stream, ct))
1748     goto unsupported_transports;
1749
1750   /* update the client transport */
1751   if (!klass->configure_client_transport (client, ctx, ct))
1752     goto unsupported_client_transport;
1753
1754   /* parse the keymgmt */
1755   if (gst_rtsp_message_get_header (ctx->request, GST_RTSP_HDR_KEYMGMT,
1756           &keymgmt, 0) == GST_RTSP_OK) {
1757     if (!handle_keymgmt (client, ctx, keymgmt))
1758       goto keymgmt_error;
1759   }
1760
1761   /* set in the session media transport */
1762   trans = gst_rtsp_session_media_set_transport (sessmedia, stream, ct);
1763
1764   /* configure the url used to set this transport, this we will use when
1765    * generating the response for the PLAY request */
1766   gst_rtsp_stream_transport_set_url (trans, uri);
1767
1768   /* configure keepalive for this transport */
1769   gst_rtsp_stream_transport_set_keepalive (trans,
1770       (GstRTSPKeepAliveFunc) do_keepalive, session, NULL);
1771
1772   /* create and serialize the server transport */
1773   st = make_server_transport (client, ctx, ct);
1774   trans_str = gst_rtsp_transport_as_text (st);
1775   gst_rtsp_transport_free (st);
1776
1777   /* construct the response now */
1778   code = GST_RTSP_STS_OK;
1779   gst_rtsp_message_init_response (ctx->response, code,
1780       gst_rtsp_status_as_text (code), ctx->request);
1781
1782   gst_rtsp_message_add_header (ctx->response, GST_RTSP_HDR_TRANSPORT,
1783       trans_str);
1784   g_free (trans_str);
1785
1786   send_message (client, session, ctx->response, FALSE);
1787
1788   /* update the state */
1789   rtspstate = gst_rtsp_session_media_get_rtsp_state (sessmedia);
1790   switch (rtspstate) {
1791     case GST_RTSP_STATE_PLAYING:
1792     case GST_RTSP_STATE_RECORDING:
1793     case GST_RTSP_STATE_READY:
1794       /* no state change */
1795       break;
1796     default:
1797       gst_rtsp_session_media_set_rtsp_state (sessmedia, GST_RTSP_STATE_READY);
1798       break;
1799   }
1800   g_object_unref (session);
1801   g_free (path);
1802
1803   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_SETUP_REQUEST], 0, ctx);
1804
1805   return TRUE;
1806
1807   /* ERRORS */
1808 no_uri:
1809   {
1810     GST_ERROR ("client %p: no uri", client);
1811     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
1812     return FALSE;
1813   }
1814 no_transport:
1815   {
1816     GST_ERROR ("client %p: no transport", client);
1817     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, ctx);
1818     goto cleanup_path;
1819   }
1820 no_pool:
1821   {
1822     GST_ERROR ("client %p: no session pool configured", client);
1823     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
1824     goto cleanup_path;
1825   }
1826 media_not_found_no_reply:
1827   {
1828     GST_ERROR ("client %p: media '%s' not found", client, path);
1829     /* error reply is already sent */
1830     goto cleanup_path;
1831   }
1832 media_not_found:
1833   {
1834     GST_ERROR ("client %p: media '%s' not found", client, path);
1835     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
1836     goto cleanup_path;
1837   }
1838 control_not_found:
1839   {
1840     GST_ERROR ("client %p: no control in path '%s'", client, path);
1841     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
1842     g_object_unref (media);
1843     goto cleanup_path;
1844   }
1845 stream_not_found:
1846   {
1847     GST_ERROR ("client %p: stream '%s' not found", client, control);
1848     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
1849     g_object_unref (media);
1850     goto cleanup_path;
1851   }
1852 service_unavailable:
1853   {
1854     GST_ERROR ("client %p: can't create session", client);
1855     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, ctx);
1856     g_object_unref (media);
1857     goto cleanup_path;
1858   }
1859 sessmedia_unavailable:
1860   {
1861     GST_ERROR ("client %p: can't create session media", client);
1862     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, ctx);
1863     g_object_unref (media);
1864     goto cleanup_session;
1865   }
1866 configure_media_failed_no_reply:
1867   {
1868     GST_ERROR ("client %p: configure_media failed", client);
1869     /* error reply is already sent */
1870     goto cleanup_session;
1871   }
1872 unsupported_transports:
1873   {
1874     GST_ERROR ("client %p: unsupported transports", client);
1875     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, ctx);
1876     goto cleanup_transport;
1877   }
1878 unsupported_client_transport:
1879   {
1880     GST_ERROR ("client %p: unsupported client transport", client);
1881     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, ctx);
1882     goto cleanup_transport;
1883   }
1884 keymgmt_error:
1885   {
1886     GST_ERROR ("client %p: keymgmt error", client);
1887     send_generic_response (client, GST_RTSP_STS_KEY_MANAGEMENT_FAILURE, ctx);
1888     goto cleanup_transport;
1889   }
1890   {
1891   cleanup_transport:
1892     gst_rtsp_transport_free (ct);
1893   cleanup_session:
1894     g_object_unref (session);
1895   cleanup_path:
1896     g_free (path);
1897     return FALSE;
1898   }
1899 }
1900
1901 static GstSDPMessage *
1902 create_sdp (GstRTSPClient * client, GstRTSPMedia * media)
1903 {
1904   GstRTSPClientPrivate *priv = client->priv;
1905   GstSDPMessage *sdp;
1906   GstSDPInfo info;
1907   const gchar *proto;
1908
1909   gst_sdp_message_new (&sdp);
1910
1911   /* some standard things first */
1912   gst_sdp_message_set_version (sdp, "0");
1913
1914   if (priv->is_ipv6)
1915     proto = "IP6";
1916   else
1917     proto = "IP4";
1918
1919   gst_sdp_message_set_origin (sdp, "-", "1188340656180883", "1", "IN", proto,
1920       priv->server_ip);
1921
1922   gst_sdp_message_set_session_name (sdp, "Session streamed with GStreamer");
1923   gst_sdp_message_set_information (sdp, "rtsp-server");
1924   gst_sdp_message_add_time (sdp, "0", "0", NULL);
1925   gst_sdp_message_add_attribute (sdp, "tool", "GStreamer");
1926   gst_sdp_message_add_attribute (sdp, "type", "broadcast");
1927   gst_sdp_message_add_attribute (sdp, "control", "*");
1928
1929   info.is_ipv6 = priv->is_ipv6;
1930   info.server_ip = priv->server_ip;
1931
1932   /* create an SDP for the media object */
1933   if (!gst_rtsp_media_setup_sdp (media, sdp, &info))
1934     goto no_sdp;
1935
1936   return sdp;
1937
1938   /* ERRORS */
1939 no_sdp:
1940   {
1941     GST_ERROR ("client %p: could not create SDP", client);
1942     gst_sdp_message_free (sdp);
1943     return NULL;
1944   }
1945 }
1946
1947 /* for the describe we must generate an SDP */
1948 static gboolean
1949 handle_describe_request (GstRTSPClient * client, GstRTSPContext * ctx)
1950 {
1951   GstRTSPClientPrivate *priv = client->priv;
1952   GstRTSPResult res;
1953   GstSDPMessage *sdp;
1954   guint i;
1955   gchar *path, *str;
1956   GstRTSPMedia *media;
1957   GstRTSPClientClass *klass;
1958
1959   klass = GST_RTSP_CLIENT_GET_CLASS (client);
1960
1961   if (!ctx->uri)
1962     goto no_uri;
1963
1964   /* check what kind of format is accepted, we don't really do anything with it
1965    * and always return SDP for now. */
1966   for (i = 0;; i++) {
1967     gchar *accept;
1968
1969     res =
1970         gst_rtsp_message_get_header (ctx->request, GST_RTSP_HDR_ACCEPT,
1971         &accept, i);
1972     if (res == GST_RTSP_ENOTIMPL)
1973       break;
1974
1975     if (g_ascii_strcasecmp (accept, "application/sdp") == 0)
1976       break;
1977   }
1978
1979   if (!priv->mount_points)
1980     goto no_mount_points;
1981
1982   if (!(path = gst_rtsp_mount_points_make_path (priv->mount_points, ctx->uri)))
1983     goto no_path;
1984
1985   /* find the media object for the uri */
1986   if (!(media = find_media (client, ctx, path, NULL)))
1987     goto no_media;
1988
1989   /* create an SDP for the media object on this client */
1990   if (!(sdp = klass->create_sdp (client, media)))
1991     goto no_sdp;
1992
1993   /* we suspend after the describe */
1994   gst_rtsp_media_suspend (media);
1995   g_object_unref (media);
1996
1997   gst_rtsp_message_init_response (ctx->response, GST_RTSP_STS_OK,
1998       gst_rtsp_status_as_text (GST_RTSP_STS_OK), ctx->request);
1999
2000   gst_rtsp_message_add_header (ctx->response, GST_RTSP_HDR_CONTENT_TYPE,
2001       "application/sdp");
2002
2003   /* content base for some clients that might screw up creating the setup uri */
2004   str = make_base_url (client, ctx->uri, path);
2005   g_free (path);
2006
2007   GST_INFO ("adding content-base: %s", str);
2008   gst_rtsp_message_take_header (ctx->response, GST_RTSP_HDR_CONTENT_BASE, str);
2009
2010   /* add SDP to the response body */
2011   str = gst_sdp_message_as_text (sdp);
2012   gst_rtsp_message_take_body (ctx->response, (guint8 *) str, strlen (str));
2013   gst_sdp_message_free (sdp);
2014
2015   send_message (client, ctx->session, ctx->response, FALSE);
2016
2017   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_DESCRIBE_REQUEST],
2018       0, ctx);
2019
2020   return TRUE;
2021
2022   /* ERRORS */
2023 no_uri:
2024   {
2025     GST_ERROR ("client %p: no uri", client);
2026     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
2027     return FALSE;
2028   }
2029 no_mount_points:
2030   {
2031     GST_ERROR ("client %p: no mount points configured", client);
2032     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
2033     return FALSE;
2034   }
2035 no_path:
2036   {
2037     GST_ERROR ("client %p: can't find path for url", client);
2038     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
2039     return FALSE;
2040   }
2041 no_media:
2042   {
2043     GST_ERROR ("client %p: no media", client);
2044     g_free (path);
2045     /* error reply is already sent */
2046     return FALSE;
2047   }
2048 no_sdp:
2049   {
2050     GST_ERROR ("client %p: can't create SDP", client);
2051     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, ctx);
2052     g_free (path);
2053     g_object_unref (media);
2054     return FALSE;
2055   }
2056 }
2057
2058 static gboolean
2059 handle_options_request (GstRTSPClient * client, GstRTSPContext * ctx)
2060 {
2061   GstRTSPMethod options;
2062   gchar *str;
2063
2064   options = GST_RTSP_DESCRIBE |
2065       GST_RTSP_OPTIONS |
2066       GST_RTSP_PAUSE |
2067       GST_RTSP_PLAY |
2068       GST_RTSP_SETUP |
2069       GST_RTSP_GET_PARAMETER | GST_RTSP_SET_PARAMETER | GST_RTSP_TEARDOWN;
2070
2071   str = gst_rtsp_options_as_text (options);
2072
2073   gst_rtsp_message_init_response (ctx->response, GST_RTSP_STS_OK,
2074       gst_rtsp_status_as_text (GST_RTSP_STS_OK), ctx->request);
2075
2076   gst_rtsp_message_add_header (ctx->response, GST_RTSP_HDR_PUBLIC, str);
2077   g_free (str);
2078
2079   send_message (client, ctx->session, ctx->response, FALSE);
2080
2081   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_OPTIONS_REQUEST],
2082       0, ctx);
2083
2084   return TRUE;
2085 }
2086
2087 /* remove duplicate and trailing '/' */
2088 static void
2089 sanitize_uri (GstRTSPUrl * uri)
2090 {
2091   gint i, len;
2092   gchar *s, *d;
2093   gboolean have_slash, prev_slash;
2094
2095   s = d = uri->abspath;
2096   len = strlen (uri->abspath);
2097
2098   prev_slash = FALSE;
2099
2100   for (i = 0; i < len; i++) {
2101     have_slash = s[i] == '/';
2102     *d = s[i];
2103     if (!have_slash || !prev_slash)
2104       d++;
2105     prev_slash = have_slash;
2106   }
2107   len = d - uri->abspath;
2108   /* don't remove the first slash if that's the only thing left */
2109   if (len > 1 && *(d - 1) == '/')
2110     d--;
2111   *d = '\0';
2112 }
2113
2114 static void
2115 client_session_finalized (GstRTSPClient * client, GstRTSPSession * session)
2116 {
2117   GstRTSPClientPrivate *priv = client->priv;
2118
2119   GST_INFO ("client %p: session %p finished", client, session);
2120
2121   /* unlink all media managed in this session */
2122   client_unlink_session (client, session);
2123
2124   /* remove the session */
2125   if (!(priv->sessions = g_list_remove (priv->sessions, session))) {
2126     GST_INFO ("client %p: all sessions finalized, close the connection",
2127         client);
2128     close_connection (client);
2129   }
2130 }
2131
2132 static void
2133 handle_request (GstRTSPClient * client, GstRTSPMessage * request)
2134 {
2135   GstRTSPClientPrivate *priv = client->priv;
2136   GstRTSPMethod method;
2137   const gchar *uristr;
2138   GstRTSPUrl *uri = NULL;
2139   GstRTSPVersion version;
2140   GstRTSPResult res;
2141   GstRTSPSession *session = NULL;
2142   GstRTSPContext sctx = { NULL }, *ctx;
2143   GstRTSPMessage response = { 0 };
2144   gchar *sessid;
2145
2146   if (!(ctx = gst_rtsp_context_get_current ())) {
2147     ctx = &sctx;
2148     ctx->auth = priv->auth;
2149     gst_rtsp_context_push_current (ctx);
2150   }
2151
2152   ctx->conn = priv->connection;
2153   ctx->client = client;
2154   ctx->request = request;
2155   ctx->response = &response;
2156
2157   if (gst_debug_category_get_threshold (rtsp_client_debug) >= GST_LEVEL_LOG) {
2158     gst_rtsp_message_dump (request);
2159   }
2160
2161   gst_rtsp_message_parse_request (request, &method, &uristr, &version);
2162
2163   GST_INFO ("client %p: received a request %s %s %s", client,
2164       gst_rtsp_method_as_text (method), uristr,
2165       gst_rtsp_version_as_text (version));
2166
2167   /* we can only handle 1.0 requests */
2168   if (version != GST_RTSP_VERSION_1_0)
2169     goto not_supported;
2170
2171   ctx->method = method;
2172
2173   /* we always try to parse the url first */
2174   if (strcmp (uristr, "*") == 0) {
2175     /* special case where we have * as uri, keep uri = NULL */
2176   } else if (gst_rtsp_url_parse (uristr, &uri) != GST_RTSP_OK) {
2177     /* check if the uristr is an absolute path <=> scheme and host information
2178      * is missing */
2179     gchar *scheme;
2180
2181     scheme = g_uri_parse_scheme (uristr);
2182     if (scheme == NULL && g_str_has_prefix (uristr, "/")) {
2183       gchar *absolute_uristr = NULL;
2184
2185       GST_WARNING_OBJECT (client, "request doesn't contain absolute url");
2186       if (priv->server_ip == NULL) {
2187         GST_WARNING_OBJECT (client, "host information missing");
2188         goto bad_request;
2189       }
2190
2191       absolute_uristr =
2192           g_strdup_printf ("rtsp://%s%s", priv->server_ip, uristr);
2193
2194       GST_DEBUG_OBJECT (client, "absolute url: %s", absolute_uristr);
2195       if (gst_rtsp_url_parse (absolute_uristr, &uri) != GST_RTSP_OK) {
2196         g_free (absolute_uristr);
2197         goto bad_request;
2198       }
2199       g_free (absolute_uristr);
2200     } else {
2201       g_free (scheme);
2202       goto bad_request;
2203     }
2204   }
2205
2206   /* get the session if there is any */
2207   res = gst_rtsp_message_get_header (request, GST_RTSP_HDR_SESSION, &sessid, 0);
2208   if (res == GST_RTSP_OK) {
2209     if (priv->session_pool == NULL)
2210       goto no_pool;
2211
2212     /* we had a session in the request, find it again */
2213     if (!(session = gst_rtsp_session_pool_find (priv->session_pool, sessid)))
2214       goto session_not_found;
2215
2216     /* we add the session to the client list of watched sessions. When a session
2217      * disappears because it times out, we will be notified. If all sessions are
2218      * gone, we will close the connection */
2219     client_watch_session (client, session);
2220   }
2221
2222   /* sanitize the uri */
2223   if (uri)
2224     sanitize_uri (uri);
2225   ctx->uri = uri;
2226   ctx->session = session;
2227
2228   if (!gst_rtsp_auth_check (GST_RTSP_AUTH_CHECK_URL))
2229     goto not_authorized;
2230
2231   /* now see what is asked and dispatch to a dedicated handler */
2232   switch (method) {
2233     case GST_RTSP_OPTIONS:
2234       handle_options_request (client, ctx);
2235       break;
2236     case GST_RTSP_DESCRIBE:
2237       handle_describe_request (client, ctx);
2238       break;
2239     case GST_RTSP_SETUP:
2240       handle_setup_request (client, ctx);
2241       break;
2242     case GST_RTSP_PLAY:
2243       handle_play_request (client, ctx);
2244       break;
2245     case GST_RTSP_PAUSE:
2246       handle_pause_request (client, ctx);
2247       break;
2248     case GST_RTSP_TEARDOWN:
2249       handle_teardown_request (client, ctx);
2250       break;
2251     case GST_RTSP_SET_PARAMETER:
2252       handle_set_param_request (client, ctx);
2253       break;
2254     case GST_RTSP_GET_PARAMETER:
2255       handle_get_param_request (client, ctx);
2256       break;
2257     case GST_RTSP_ANNOUNCE:
2258     case GST_RTSP_RECORD:
2259     case GST_RTSP_REDIRECT:
2260       goto not_implemented;
2261     case GST_RTSP_INVALID:
2262     default:
2263       goto bad_request;
2264   }
2265
2266 done:
2267   if (ctx == &sctx)
2268     gst_rtsp_context_pop_current (ctx);
2269   if (session)
2270     g_object_unref (session);
2271   if (uri)
2272     gst_rtsp_url_free (uri);
2273   return;
2274
2275   /* ERRORS */
2276 not_supported:
2277   {
2278     GST_ERROR ("client %p: version %d not supported", client, version);
2279     send_generic_response (client, GST_RTSP_STS_RTSP_VERSION_NOT_SUPPORTED,
2280         ctx);
2281     goto done;
2282   }
2283 bad_request:
2284   {
2285     GST_ERROR ("client %p: bad request", client);
2286     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
2287     goto done;
2288   }
2289 no_pool:
2290   {
2291     GST_ERROR ("client %p: no pool configured", client);
2292     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
2293     goto done;
2294   }
2295 session_not_found:
2296   {
2297     GST_ERROR ("client %p: session not found", client);
2298     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
2299     goto done;
2300   }
2301 not_authorized:
2302   {
2303     GST_ERROR ("client %p: not allowed", client);
2304     /* error reply is already sent */
2305     goto done;
2306   }
2307 not_implemented:
2308   {
2309     GST_ERROR ("client %p: method %d not implemented", client, method);
2310     send_generic_response (client, GST_RTSP_STS_NOT_IMPLEMENTED, ctx);
2311     goto done;
2312   }
2313 }
2314
2315
2316 static void
2317 handle_response (GstRTSPClient * client, GstRTSPMessage * response)
2318 {
2319   GstRTSPClientPrivate *priv = client->priv;
2320   GstRTSPResult res;
2321   GstRTSPSession *session = NULL;
2322   GstRTSPContext sctx = { NULL }, *ctx;
2323   gchar *sessid;
2324
2325   if (!(ctx = gst_rtsp_context_get_current ())) {
2326     ctx = &sctx;
2327     ctx->auth = priv->auth;
2328     gst_rtsp_context_push_current (ctx);
2329   }
2330
2331   ctx->conn = priv->connection;
2332   ctx->client = client;
2333   ctx->request = NULL;
2334   ctx->uri = NULL;
2335   ctx->method = GST_RTSP_INVALID;
2336   ctx->response = response;
2337
2338   if (gst_debug_category_get_threshold (rtsp_client_debug) >= GST_LEVEL_LOG) {
2339     gst_rtsp_message_dump (response);
2340   }
2341
2342   GST_INFO ("client %p: received a response", client);
2343
2344   /* get the session if there is any */
2345   res =
2346       gst_rtsp_message_get_header (response, GST_RTSP_HDR_SESSION, &sessid, 0);
2347   if (res == GST_RTSP_OK) {
2348     if (priv->session_pool == NULL)
2349       goto no_pool;
2350
2351     /* we had a session in the request, find it again */
2352     if (!(session = gst_rtsp_session_pool_find (priv->session_pool, sessid)))
2353       goto session_not_found;
2354
2355     /* we add the session to the client list of watched sessions. When a session
2356      * disappears because it times out, we will be notified. If all sessions are
2357      * gone, we will close the connection */
2358     client_watch_session (client, session);
2359   }
2360
2361   ctx->session = session;
2362
2363   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_HANDLE_RESPONSE],
2364       0, ctx);
2365
2366 done:
2367   if (ctx == &sctx)
2368     gst_rtsp_context_pop_current (ctx);
2369   if (session)
2370     g_object_unref (session);
2371   return;
2372
2373 no_pool:
2374   {
2375     GST_ERROR ("client %p: no pool configured", client);
2376     goto done;
2377   }
2378 session_not_found:
2379   {
2380     GST_ERROR ("client %p: session not found", client);
2381     goto done;
2382   }
2383 }
2384
2385 static void
2386 handle_data (GstRTSPClient * client, GstRTSPMessage * message)
2387 {
2388   GstRTSPClientPrivate *priv = client->priv;
2389   GstRTSPResult res;
2390   guint8 channel;
2391   GList *walk;
2392   guint8 *data;
2393   guint size;
2394   GstBuffer *buffer;
2395   gboolean handled;
2396
2397   /* find the stream for this message */
2398   res = gst_rtsp_message_parse_data (message, &channel);
2399   if (res != GST_RTSP_OK)
2400     return;
2401
2402   gst_rtsp_message_steal_body (message, &data, &size);
2403
2404   buffer = gst_buffer_new_wrapped (data, size);
2405
2406   handled = FALSE;
2407   for (walk = priv->transports; walk; walk = g_list_next (walk)) {
2408     GstRTSPStreamTransport *trans;
2409     GstRTSPStream *stream;
2410     const GstRTSPTransport *tr;
2411
2412     trans = walk->data;
2413
2414     tr = gst_rtsp_stream_transport_get_transport (trans);
2415     stream = gst_rtsp_stream_transport_get_stream (trans);
2416
2417     /* check for TCP transport */
2418     if (tr->lower_transport == GST_RTSP_LOWER_TRANS_TCP) {
2419       /* dispatch to the stream based on the channel number */
2420       if (tr->interleaved.min == channel) {
2421         gst_rtsp_stream_recv_rtp (stream, buffer);
2422         handled = TRUE;
2423         break;
2424       } else if (tr->interleaved.max == channel) {
2425         gst_rtsp_stream_recv_rtcp (stream, buffer);
2426         handled = TRUE;
2427         break;
2428       }
2429     }
2430   }
2431   if (!handled)
2432     gst_buffer_unref (buffer);
2433 }
2434
2435 /**
2436  * gst_rtsp_client_set_session_pool:
2437  * @client: a #GstRTSPClient
2438  * @pool: (transfer none): a #GstRTSPSessionPool
2439  *
2440  * Set @pool as the sessionpool for @client which it will use to find
2441  * or allocate sessions. the sessionpool is usually inherited from the server
2442  * that created the client but can be overridden later.
2443  */
2444 void
2445 gst_rtsp_client_set_session_pool (GstRTSPClient * client,
2446     GstRTSPSessionPool * pool)
2447 {
2448   GstRTSPSessionPool *old;
2449   GstRTSPClientPrivate *priv;
2450
2451   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2452
2453   priv = client->priv;
2454
2455   if (pool)
2456     g_object_ref (pool);
2457
2458   g_mutex_lock (&priv->lock);
2459   old = priv->session_pool;
2460   priv->session_pool = pool;
2461   g_mutex_unlock (&priv->lock);
2462
2463   if (old)
2464     g_object_unref (old);
2465 }
2466
2467 /**
2468  * gst_rtsp_client_get_session_pool:
2469  * @client: a #GstRTSPClient
2470  *
2471  * Get the #GstRTSPSessionPool object that @client uses to manage its sessions.
2472  *
2473  * Returns: (transfer full): a #GstRTSPSessionPool, unref after usage.
2474  */
2475 GstRTSPSessionPool *
2476 gst_rtsp_client_get_session_pool (GstRTSPClient * client)
2477 {
2478   GstRTSPClientPrivate *priv;
2479   GstRTSPSessionPool *result;
2480
2481   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2482
2483   priv = client->priv;
2484
2485   g_mutex_lock (&priv->lock);
2486   if ((result = priv->session_pool))
2487     g_object_ref (result);
2488   g_mutex_unlock (&priv->lock);
2489
2490   return result;
2491 }
2492
2493 /**
2494  * gst_rtsp_client_set_mount_points:
2495  * @client: a #GstRTSPClient
2496  * @mounts: (transfer none): a #GstRTSPMountPoints
2497  *
2498  * Set @mounts as the mount points for @client which it will use to map urls
2499  * to media streams. These mount points are usually inherited from the server that
2500  * created the client but can be overriden later.
2501  */
2502 void
2503 gst_rtsp_client_set_mount_points (GstRTSPClient * client,
2504     GstRTSPMountPoints * mounts)
2505 {
2506   GstRTSPClientPrivate *priv;
2507   GstRTSPMountPoints *old;
2508
2509   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2510
2511   priv = client->priv;
2512
2513   if (mounts)
2514     g_object_ref (mounts);
2515
2516   g_mutex_lock (&priv->lock);
2517   old = priv->mount_points;
2518   priv->mount_points = mounts;
2519   g_mutex_unlock (&priv->lock);
2520
2521   if (old)
2522     g_object_unref (old);
2523 }
2524
2525 /**
2526  * gst_rtsp_client_get_mount_points:
2527  * @client: a #GstRTSPClient
2528  *
2529  * Get the #GstRTSPMountPoints object that @client uses to manage its sessions.
2530  *
2531  * Returns: (transfer full): a #GstRTSPMountPoints, unref after usage.
2532  */
2533 GstRTSPMountPoints *
2534 gst_rtsp_client_get_mount_points (GstRTSPClient * client)
2535 {
2536   GstRTSPClientPrivate *priv;
2537   GstRTSPMountPoints *result;
2538
2539   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2540
2541   priv = client->priv;
2542
2543   g_mutex_lock (&priv->lock);
2544   if ((result = priv->mount_points))
2545     g_object_ref (result);
2546   g_mutex_unlock (&priv->lock);
2547
2548   return result;
2549 }
2550
2551 /**
2552  * gst_rtsp_client_set_auth:
2553  * @client: a #GstRTSPClient
2554  * @auth: (transfer none): a #GstRTSPAuth
2555  *
2556  * configure @auth to be used as the authentication manager of @client.
2557  */
2558 void
2559 gst_rtsp_client_set_auth (GstRTSPClient * client, GstRTSPAuth * auth)
2560 {
2561   GstRTSPClientPrivate *priv;
2562   GstRTSPAuth *old;
2563
2564   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2565
2566   priv = client->priv;
2567
2568   if (auth)
2569     g_object_ref (auth);
2570
2571   g_mutex_lock (&priv->lock);
2572   old = priv->auth;
2573   priv->auth = auth;
2574   g_mutex_unlock (&priv->lock);
2575
2576   if (old)
2577     g_object_unref (old);
2578 }
2579
2580
2581 /**
2582  * gst_rtsp_client_get_auth:
2583  * @client: a #GstRTSPClient
2584  *
2585  * Get the #GstRTSPAuth used as the authentication manager of @client.
2586  *
2587  * Returns: (transfer full): the #GstRTSPAuth of @client. g_object_unref() after
2588  * usage.
2589  */
2590 GstRTSPAuth *
2591 gst_rtsp_client_get_auth (GstRTSPClient * client)
2592 {
2593   GstRTSPClientPrivate *priv;
2594   GstRTSPAuth *result;
2595
2596   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2597
2598   priv = client->priv;
2599
2600   g_mutex_lock (&priv->lock);
2601   if ((result = priv->auth))
2602     g_object_ref (result);
2603   g_mutex_unlock (&priv->lock);
2604
2605   return result;
2606 }
2607
2608 /**
2609  * gst_rtsp_client_set_thread_pool:
2610  * @client: a #GstRTSPClient
2611  * @pool: (transfer none): a #GstRTSPThreadPool
2612  *
2613  * configure @pool to be used as the thread pool of @client.
2614  */
2615 void
2616 gst_rtsp_client_set_thread_pool (GstRTSPClient * client,
2617     GstRTSPThreadPool * pool)
2618 {
2619   GstRTSPClientPrivate *priv;
2620   GstRTSPThreadPool *old;
2621
2622   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2623
2624   priv = client->priv;
2625
2626   if (pool)
2627     g_object_ref (pool);
2628
2629   g_mutex_lock (&priv->lock);
2630   old = priv->thread_pool;
2631   priv->thread_pool = pool;
2632   g_mutex_unlock (&priv->lock);
2633
2634   if (old)
2635     g_object_unref (old);
2636 }
2637
2638 /**
2639  * gst_rtsp_client_get_thread_pool:
2640  * @client: a #GstRTSPClient
2641  *
2642  * Get the #GstRTSPThreadPool used as the thread pool of @client.
2643  *
2644  * Returns: (transfer full): the #GstRTSPThreadPool of @client. g_object_unref() after
2645  * usage.
2646  */
2647 GstRTSPThreadPool *
2648 gst_rtsp_client_get_thread_pool (GstRTSPClient * client)
2649 {
2650   GstRTSPClientPrivate *priv;
2651   GstRTSPThreadPool *result;
2652
2653   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2654
2655   priv = client->priv;
2656
2657   g_mutex_lock (&priv->lock);
2658   if ((result = priv->thread_pool))
2659     g_object_ref (result);
2660   g_mutex_unlock (&priv->lock);
2661
2662   return result;
2663 }
2664
2665 /**
2666  * gst_rtsp_client_set_connection:
2667  * @client: a #GstRTSPClient
2668  * @conn: (transfer full): a #GstRTSPConnection
2669  *
2670  * Set the #GstRTSPConnection of @client. This function takes ownership of
2671  * @conn.
2672  *
2673  * Returns: %TRUE on success.
2674  */
2675 gboolean
2676 gst_rtsp_client_set_connection (GstRTSPClient * client,
2677     GstRTSPConnection * conn)
2678 {
2679   GstRTSPClientPrivate *priv;
2680   GSocket *read_socket;
2681   GSocketAddress *address;
2682   GstRTSPUrl *url;
2683   GError *error = NULL;
2684
2685   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), FALSE);
2686   g_return_val_if_fail (conn != NULL, FALSE);
2687
2688   priv = client->priv;
2689
2690   read_socket = gst_rtsp_connection_get_read_socket (conn);
2691
2692   if (!(address = g_socket_get_local_address (read_socket, &error)))
2693     goto no_address;
2694
2695   g_free (priv->server_ip);
2696   /* keep the original ip that the client connected to */
2697   if (G_IS_INET_SOCKET_ADDRESS (address)) {
2698     GInetAddress *iaddr;
2699
2700     iaddr = g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (address));
2701
2702     /* socket might be ipv6 but adress still ipv4 */
2703     priv->is_ipv6 = g_inet_address_get_family (iaddr) == G_SOCKET_FAMILY_IPV6;
2704     priv->server_ip = g_inet_address_to_string (iaddr);
2705     g_object_unref (address);
2706   } else {
2707     priv->is_ipv6 = g_socket_get_family (read_socket) == G_SOCKET_FAMILY_IPV6;
2708     priv->server_ip = g_strdup ("unknown");
2709   }
2710
2711   GST_INFO ("client %p connected to server ip %s, ipv6 = %d", client,
2712       priv->server_ip, priv->is_ipv6);
2713
2714   url = gst_rtsp_connection_get_url (conn);
2715   GST_INFO ("added new client %p ip %s:%d", client, url->host, url->port);
2716
2717   priv->connection = conn;
2718
2719   return TRUE;
2720
2721   /* ERRORS */
2722 no_address:
2723   {
2724     GST_ERROR ("could not get local address %s", error->message);
2725     g_error_free (error);
2726     return FALSE;
2727   }
2728 }
2729
2730 /**
2731  * gst_rtsp_client_get_connection:
2732  * @client: a #GstRTSPClient
2733  *
2734  * Get the #GstRTSPConnection of @client.
2735  *
2736  * Returns: (transfer none): the #GstRTSPConnection of @client.
2737  * The connection object returned remains valid until the client is freed.
2738  */
2739 GstRTSPConnection *
2740 gst_rtsp_client_get_connection (GstRTSPClient * client)
2741 {
2742   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2743
2744   return client->priv->connection;
2745 }
2746
2747 /**
2748  * gst_rtsp_client_set_send_func:
2749  * @client: a #GstRTSPClient
2750  * @func: (scope notified): a #GstRTSPClientSendFunc
2751  * @user_data: (closure): user data passed to @func
2752  * @notify: (allow-none): called when @user_data is no longer in use
2753  *
2754  * Set @func as the callback that will be called when a new message needs to be
2755  * sent to the client. @user_data is passed to @func and @notify is called when
2756  * @user_data is no longer in use.
2757  *
2758  * By default, the client will send the messages on the #GstRTSPConnection that
2759  * was configured with gst_rtsp_client_attach() was called.
2760  */
2761 void
2762 gst_rtsp_client_set_send_func (GstRTSPClient * client,
2763     GstRTSPClientSendFunc func, gpointer user_data, GDestroyNotify notify)
2764 {
2765   GstRTSPClientPrivate *priv;
2766   GDestroyNotify old_notify;
2767   gpointer old_data;
2768
2769   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2770
2771   priv = client->priv;
2772
2773   g_mutex_lock (&priv->send_lock);
2774   priv->send_func = func;
2775   old_notify = priv->send_notify;
2776   old_data = priv->send_data;
2777   priv->send_notify = notify;
2778   priv->send_data = user_data;
2779   g_mutex_unlock (&priv->send_lock);
2780
2781   if (old_notify)
2782     old_notify (old_data);
2783 }
2784
2785 /**
2786  * gst_rtsp_client_handle_message:
2787  * @client: a #GstRTSPClient
2788  * @message: (transfer none): an #GstRTSPMessage
2789  *
2790  * Let the client handle @message.
2791  *
2792  * Returns: a #GstRTSPResult.
2793  */
2794 GstRTSPResult
2795 gst_rtsp_client_handle_message (GstRTSPClient * client,
2796     GstRTSPMessage * message)
2797 {
2798   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), GST_RTSP_EINVAL);
2799   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2800
2801   switch (message->type) {
2802     case GST_RTSP_MESSAGE_REQUEST:
2803       handle_request (client, message);
2804       break;
2805     case GST_RTSP_MESSAGE_RESPONSE:
2806       handle_response (client, message);
2807       break;
2808     case GST_RTSP_MESSAGE_DATA:
2809       handle_data (client, message);
2810       break;
2811     default:
2812       break;
2813   }
2814   return GST_RTSP_OK;
2815 }
2816
2817 /**
2818  * gst_rtsp_client_send_message:
2819  * @client: a #GstRTSPClient
2820  * @session: (transfer none): a #GstRTSPSession to send the message to or %NULL
2821  * @message: (transfer none): The #GstRTSPMessage to send
2822  *
2823  * Send a message message to the remote end. @message must be a
2824  * #GST_RTSP_MESSAGE_REQUEST or a #GST_RTSP_MESSAGE_RESPONSE.
2825  */
2826 GstRTSPResult
2827 gst_rtsp_client_send_message (GstRTSPClient * client, GstRTSPSession * session,
2828     GstRTSPMessage * message)
2829 {
2830   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), GST_RTSP_EINVAL);
2831   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2832   g_return_val_if_fail (message->type == GST_RTSP_MESSAGE_REQUEST ||
2833       message->type == GST_RTSP_MESSAGE_RESPONSE, GST_RTSP_EINVAL);
2834
2835   send_message (client, session, message, FALSE);
2836
2837   return GST_RTSP_OK;
2838 }
2839
2840 static GstRTSPResult
2841 do_send_message (GstRTSPClient * client, GstRTSPMessage * message,
2842     gboolean close, gpointer user_data)
2843 {
2844   GstRTSPClientPrivate *priv = client->priv;
2845
2846   /* send the response and store the seq number so we can wait until it's
2847    * written to the client to close the connection */
2848   return gst_rtsp_watch_send_message (priv->watch, message, close ?
2849       &priv->close_seq : NULL);
2850 }
2851
2852 static GstRTSPResult
2853 message_received (GstRTSPWatch * watch, GstRTSPMessage * message,
2854     gpointer user_data)
2855 {
2856   return gst_rtsp_client_handle_message (GST_RTSP_CLIENT (user_data), message);
2857 }
2858
2859 static GstRTSPResult
2860 message_sent (GstRTSPWatch * watch, guint cseq, gpointer user_data)
2861 {
2862   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2863   GstRTSPClientPrivate *priv = client->priv;
2864
2865   if (priv->close_seq && priv->close_seq == cseq) {
2866     priv->close_seq = 0;
2867     close_connection (client);
2868   }
2869
2870   return GST_RTSP_OK;
2871 }
2872
2873 static GstRTSPResult
2874 closed (GstRTSPWatch * watch, gpointer user_data)
2875 {
2876   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2877   GstRTSPClientPrivate *priv = client->priv;
2878   const gchar *tunnelid;
2879
2880   GST_INFO ("client %p: connection closed", client);
2881
2882   if ((tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection))) {
2883     g_mutex_lock (&tunnels_lock);
2884     /* remove from tunnelids */
2885     g_hash_table_remove (tunnels, tunnelid);
2886     g_mutex_unlock (&tunnels_lock);
2887   }
2888
2889   gst_rtsp_client_set_send_func (client, NULL, NULL, NULL);
2890
2891   return GST_RTSP_OK;
2892 }
2893
2894 static GstRTSPResult
2895 error (GstRTSPWatch * watch, GstRTSPResult result, gpointer user_data)
2896 {
2897   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2898   gchar *str;
2899
2900   str = gst_rtsp_strresult (result);
2901   GST_INFO ("client %p: received an error %s", client, str);
2902   g_free (str);
2903
2904   return GST_RTSP_OK;
2905 }
2906
2907 static GstRTSPResult
2908 error_full (GstRTSPWatch * watch, GstRTSPResult result,
2909     GstRTSPMessage * message, guint id, gpointer user_data)
2910 {
2911   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2912   gchar *str;
2913
2914   str = gst_rtsp_strresult (result);
2915   GST_INFO
2916       ("client %p: error when handling message %p with id %d: %s",
2917       client, message, id, str);
2918   g_free (str);
2919
2920   return GST_RTSP_OK;
2921 }
2922
2923 static gboolean
2924 remember_tunnel (GstRTSPClient * client)
2925 {
2926   GstRTSPClientPrivate *priv = client->priv;
2927   const gchar *tunnelid;
2928
2929   /* store client in the pending tunnels */
2930   tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection);
2931   if (tunnelid == NULL)
2932     goto no_tunnelid;
2933
2934   GST_INFO ("client %p: inserting tunnel session %s", client, tunnelid);
2935
2936   /* we can't have two clients connecting with the same tunnelid */
2937   g_mutex_lock (&tunnels_lock);
2938   if (g_hash_table_lookup (tunnels, tunnelid))
2939     goto tunnel_existed;
2940
2941   g_hash_table_insert (tunnels, g_strdup (tunnelid), g_object_ref (client));
2942   g_mutex_unlock (&tunnels_lock);
2943
2944   return TRUE;
2945
2946   /* ERRORS */
2947 no_tunnelid:
2948   {
2949     GST_ERROR ("client %p: no tunnelid provided", client);
2950     return FALSE;
2951   }
2952 tunnel_existed:
2953   {
2954     g_mutex_unlock (&tunnels_lock);
2955     GST_ERROR ("client %p: tunnel session %s already existed", client,
2956         tunnelid);
2957     return FALSE;
2958   }
2959 }
2960
2961 static GstRTSPStatusCode
2962 tunnel_start (GstRTSPWatch * watch, gpointer user_data)
2963 {
2964   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2965   GstRTSPClientPrivate *priv = client->priv;
2966
2967   GST_INFO ("client %p: tunnel start (connection %p)", client,
2968       priv->connection);
2969
2970   if (!remember_tunnel (client))
2971     goto tunnel_error;
2972
2973   return GST_RTSP_STS_OK;
2974
2975   /* ERRORS */
2976 tunnel_error:
2977   {
2978     GST_ERROR ("client %p: error starting tunnel", client);
2979     return GST_RTSP_STS_SERVICE_UNAVAILABLE;
2980   }
2981 }
2982
2983 static GstRTSPResult
2984 tunnel_lost (GstRTSPWatch * watch, gpointer user_data)
2985 {
2986   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2987   GstRTSPClientPrivate *priv = client->priv;
2988
2989   GST_WARNING ("client %p: tunnel lost (connection %p)", client,
2990       priv->connection);
2991
2992   /* ignore error, it'll only be a problem when the client does a POST again */
2993   remember_tunnel (client);
2994
2995   return GST_RTSP_OK;
2996 }
2997
2998 static GstRTSPResult
2999 tunnel_complete (GstRTSPWatch * watch, gpointer user_data)
3000 {
3001   const gchar *tunnelid;
3002   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3003   GstRTSPClientPrivate *priv = client->priv;
3004   GstRTSPClient *oclient;
3005   GstRTSPClientPrivate *opriv;
3006
3007   GST_INFO ("client %p: tunnel complete", client);
3008
3009   /* find previous tunnel */
3010   tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection);
3011   if (tunnelid == NULL)
3012     goto no_tunnelid;
3013
3014   g_mutex_lock (&tunnels_lock);
3015   if (!(oclient = g_hash_table_lookup (tunnels, tunnelid)))
3016     goto no_tunnel;
3017
3018   /* remove the old client from the table. ref before because removing it will
3019    * remove the ref to it. */
3020   g_object_ref (oclient);
3021   g_hash_table_remove (tunnels, tunnelid);
3022
3023   opriv = oclient->priv;
3024
3025   if (opriv->watch == NULL)
3026     goto tunnel_closed;
3027   g_mutex_unlock (&tunnels_lock);
3028
3029   GST_INFO ("client %p: found tunnel %p (old %p, new %p)", client, oclient,
3030       opriv->connection, priv->connection);
3031
3032   /* merge the tunnels into the first client */
3033   gst_rtsp_connection_do_tunnel (opriv->connection, priv->connection);
3034   gst_rtsp_watch_reset (opriv->watch);
3035   g_object_unref (oclient);
3036
3037   return GST_RTSP_OK;
3038
3039   /* ERRORS */
3040 no_tunnelid:
3041   {
3042     GST_ERROR ("client %p: no tunnelid provided", client);
3043     return GST_RTSP_ERROR;
3044   }
3045 no_tunnel:
3046   {
3047     g_mutex_unlock (&tunnels_lock);
3048     GST_ERROR ("client %p: tunnel session %s not found", client, tunnelid);
3049     return GST_RTSP_ERROR;
3050   }
3051 tunnel_closed:
3052   {
3053     g_mutex_unlock (&tunnels_lock);
3054     GST_ERROR ("client %p: tunnel session %s was closed", client, tunnelid);
3055     g_object_unref (oclient);
3056     return GST_RTSP_ERROR;
3057   }
3058 }
3059
3060 static GstRTSPResult
3061 tunnel_http_response (GstRTSPWatch * watch, GstRTSPMessage * request,
3062     GstRTSPMessage * response, gpointer user_data)
3063 {
3064   GstRTSPClientClass *klass;
3065
3066   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
3067   klass = GST_RTSP_CLIENT_GET_CLASS (client);
3068
3069   if (klass->tunnel_http_response) {
3070     klass->tunnel_http_response (client, request, response);
3071   }
3072
3073   return GST_RTSP_OK;
3074 }
3075
3076 static GstRTSPWatchFuncs watch_funcs = {
3077   message_received,
3078   message_sent,
3079   closed,
3080   error,
3081   tunnel_start,
3082   tunnel_complete,
3083   error_full,
3084   tunnel_lost,
3085   tunnel_http_response
3086 };
3087
3088 static void
3089 client_watch_notify (GstRTSPClient * client)
3090 {
3091   GstRTSPClientPrivate *priv = client->priv;
3092
3093   GST_INFO ("client %p: watch destroyed", client);
3094   priv->watch = NULL;
3095   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_CLOSED], 0, NULL);
3096   g_object_unref (client);
3097 }
3098
3099 /**
3100  * gst_rtsp_client_attach:
3101  * @client: a #GstRTSPClient
3102  * @context: (allow-none): a #GMainContext
3103  *
3104  * Attaches @client to @context. When the mainloop for @context is run, the
3105  * client will be dispatched. When @context is %NULL, the default context will be
3106  * used).
3107  *
3108  * This function should be called when the client properties and urls are fully
3109  * configured and the client is ready to start.
3110  *
3111  * Returns: the ID (greater than 0) for the source within the GMainContext.
3112  */
3113 guint
3114 gst_rtsp_client_attach (GstRTSPClient * client, GMainContext * context)
3115 {
3116   GstRTSPClientPrivate *priv;
3117   guint res;
3118
3119   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), 0);
3120   priv = client->priv;
3121   g_return_val_if_fail (priv->connection != NULL, 0);
3122   g_return_val_if_fail (priv->watch == NULL, 0);
3123
3124   /* create watch for the connection and attach */
3125   priv->watch = gst_rtsp_watch_new (priv->connection, &watch_funcs,
3126       g_object_ref (client), (GDestroyNotify) client_watch_notify);
3127   gst_rtsp_client_set_send_func (client, do_send_message, priv->watch,
3128       (GDestroyNotify) gst_rtsp_watch_unref);
3129
3130   /* FIXME make this configurable. We don't want to do this yet because it will
3131    * be superceeded by a cache object later */
3132   gst_rtsp_watch_set_send_backlog (priv->watch, 0, 100);
3133
3134   GST_INFO ("attaching to context %p", context);
3135   res = gst_rtsp_watch_attach (priv->watch, context);
3136
3137   return res;
3138 }
3139
3140 /**
3141  * gst_rtsp_client_session_filter:
3142  * @client: a #GstRTSPClient
3143  * @func: (scope call) (allow-none): a callback
3144  * @user_data: user data passed to @func
3145  *
3146  * Call @func for each session managed by @client. The result value of @func
3147  * determines what happens to the session. @func will be called with @client
3148  * locked so no further actions on @client can be performed from @func.
3149  *
3150  * If @func returns #GST_RTSP_FILTER_REMOVE, the session will be removed from
3151  * @client.
3152  *
3153  * If @func returns #GST_RTSP_FILTER_KEEP, the session will remain in @client.
3154  *
3155  * If @func returns #GST_RTSP_FILTER_REF, the session will remain in @client but
3156  * will also be added with an additional ref to the result #GList of this
3157  * function..
3158  *
3159  * When @func is %NULL, #GST_RTSP_FILTER_REF will be assumed for each session.
3160  *
3161  * Returns: (element-type GstRTSPSession) (transfer full): a #GList with all
3162  * sessions for which @func returned #GST_RTSP_FILTER_REF. After usage, each
3163  * element in the #GList should be unreffed before the list is freed.
3164  */
3165 GList *
3166 gst_rtsp_client_session_filter (GstRTSPClient * client,
3167     GstRTSPClientSessionFilterFunc func, gpointer user_data)
3168 {
3169   GstRTSPClientPrivate *priv;
3170   GList *result, *walk, *next;
3171
3172   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
3173
3174   priv = client->priv;
3175
3176   result = NULL;
3177
3178   g_mutex_lock (&priv->lock);
3179   for (walk = priv->sessions; walk; walk = next) {
3180     GstRTSPSession *sess = walk->data;
3181     GstRTSPFilterResult res;
3182
3183     next = g_list_next (walk);
3184
3185     if (func)
3186       res = func (client, sess, user_data);
3187     else
3188       res = GST_RTSP_FILTER_REF;
3189
3190     switch (res) {
3191       case GST_RTSP_FILTER_REMOVE:
3192         /* stop watching the session and pretent it went away */
3193         client_cleanup_session (client, sess);
3194         break;
3195       case GST_RTSP_FILTER_REF:
3196         result = g_list_prepend (result, g_object_ref (sess));
3197         break;
3198       case GST_RTSP_FILTER_KEEP:
3199       default:
3200         break;
3201     }
3202   }
3203   g_mutex_unlock (&priv->lock);
3204
3205   return result;
3206 }