client: never call gst_rtsp_media_unprepare, let gst_rtsp_media_finalize do it
[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 #include <stdio.h>
21 #include <string.h>
22
23 #include "rtsp-client.h"
24 #include "rtsp-sdp.h"
25 #include "rtsp-params.h"
26
27 #define GST_RTSP_CLIENT_GET_PRIVATE(obj)  \
28    (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_RTSP_CLIENT, GstRTSPClientPrivate))
29
30 struct _GstRTSPClientPrivate
31 {
32   GMutex lock;
33   GstRTSPConnection *connection;
34   GstRTSPWatch *watch;
35   guint close_seq;
36   gchar *server_ip;
37   gboolean is_ipv6;
38   gboolean use_client_settings;
39
40   GstRTSPClientSendFunc send_func;
41   gpointer send_data;
42   GDestroyNotify send_notify;
43
44   GstRTSPSessionPool *session_pool;
45   GstRTSPMountPoints *mount_points;
46   GstRTSPAuth *auth;
47
48   GstRTSPUrl *uri;
49   GstRTSPMedia *media;
50
51   GList *transports;
52   GList *sessions;
53 };
54
55 static GMutex tunnels_lock;
56 static GHashTable *tunnels;
57
58 #define DEFAULT_SESSION_POOL            NULL
59 #define DEFAULT_MOUNT_POINTS            NULL
60 #define DEFAULT_USE_CLIENT_SETTINGS     FALSE
61
62 enum
63 {
64   PROP_0,
65   PROP_SESSION_POOL,
66   PROP_MOUNT_POINTS,
67   PROP_USE_CLIENT_SETTINGS,
68   PROP_LAST
69 };
70
71 enum
72 {
73   SIGNAL_CLOSED,
74   SIGNAL_NEW_SESSION,
75   SIGNAL_OPTIONS_REQUEST,
76   SIGNAL_DESCRIBE_REQUEST,
77   SIGNAL_SETUP_REQUEST,
78   SIGNAL_PLAY_REQUEST,
79   SIGNAL_PAUSE_REQUEST,
80   SIGNAL_TEARDOWN_REQUEST,
81   SIGNAL_SET_PARAMETER_REQUEST,
82   SIGNAL_GET_PARAMETER_REQUEST,
83   SIGNAL_LAST
84 };
85
86 GST_DEBUG_CATEGORY_STATIC (rtsp_client_debug);
87 #define GST_CAT_DEFAULT rtsp_client_debug
88
89 static guint gst_rtsp_client_signals[SIGNAL_LAST] = { 0 };
90
91 static void gst_rtsp_client_get_property (GObject * object, guint propid,
92     GValue * value, GParamSpec * pspec);
93 static void gst_rtsp_client_set_property (GObject * object, guint propid,
94     const GValue * value, GParamSpec * pspec);
95 static void gst_rtsp_client_finalize (GObject * obj);
96
97 static GstSDPMessage *create_sdp (GstRTSPClient * client, GstRTSPMedia * media);
98 static void client_session_finalized (GstRTSPClient * client,
99     GstRTSPSession * session);
100 static void unlink_session_transports (GstRTSPClient * client,
101     GstRTSPSession * session, GstRTSPSessionMedia * media);
102
103 G_DEFINE_TYPE (GstRTSPClient, gst_rtsp_client, G_TYPE_OBJECT);
104
105 static void
106 gst_rtsp_client_class_init (GstRTSPClientClass * klass)
107 {
108   GObjectClass *gobject_class;
109
110   g_type_class_add_private (klass, sizeof (GstRTSPClientPrivate));
111
112   gobject_class = G_OBJECT_CLASS (klass);
113
114   gobject_class->get_property = gst_rtsp_client_get_property;
115   gobject_class->set_property = gst_rtsp_client_set_property;
116   gobject_class->finalize = gst_rtsp_client_finalize;
117
118   klass->create_sdp = create_sdp;
119
120   g_object_class_install_property (gobject_class, PROP_SESSION_POOL,
121       g_param_spec_object ("session-pool", "Session Pool",
122           "The session pool to use for client session",
123           GST_TYPE_RTSP_SESSION_POOL,
124           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
125
126   g_object_class_install_property (gobject_class, PROP_MOUNT_POINTS,
127       g_param_spec_object ("mount-points", "Mount Points",
128           "The mount points to use for client session",
129           GST_TYPE_RTSP_MOUNT_POINTS,
130           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
131
132   g_object_class_install_property (gobject_class, PROP_USE_CLIENT_SETTINGS,
133       g_param_spec_boolean ("use-client-settings", "Use Client Settings",
134           "Use client settings for ttl and destination in multicast",
135           DEFAULT_USE_CLIENT_SETTINGS,
136           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
137
138   gst_rtsp_client_signals[SIGNAL_CLOSED] =
139       g_signal_new ("closed", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
140       G_STRUCT_OFFSET (GstRTSPClientClass, closed), NULL, NULL,
141       g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0, G_TYPE_NONE);
142
143   gst_rtsp_client_signals[SIGNAL_NEW_SESSION] =
144       g_signal_new ("new-session", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
145       G_STRUCT_OFFSET (GstRTSPClientClass, new_session), NULL, NULL,
146       g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1, GST_TYPE_RTSP_SESSION);
147
148   gst_rtsp_client_signals[SIGNAL_OPTIONS_REQUEST] =
149       g_signal_new ("options-request", G_TYPE_FROM_CLASS (klass),
150       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, options_request),
151       NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1,
152       G_TYPE_POINTER);
153
154   gst_rtsp_client_signals[SIGNAL_DESCRIBE_REQUEST] =
155       g_signal_new ("describe-request", G_TYPE_FROM_CLASS (klass),
156       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, describe_request),
157       NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1,
158       G_TYPE_POINTER);
159
160   gst_rtsp_client_signals[SIGNAL_SETUP_REQUEST] =
161       g_signal_new ("setup-request", G_TYPE_FROM_CLASS (klass),
162       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, setup_request),
163       NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1,
164       G_TYPE_POINTER);
165
166   gst_rtsp_client_signals[SIGNAL_PLAY_REQUEST] =
167       g_signal_new ("play-request", G_TYPE_FROM_CLASS (klass),
168       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, play_request),
169       NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1,
170       G_TYPE_POINTER);
171
172   gst_rtsp_client_signals[SIGNAL_PAUSE_REQUEST] =
173       g_signal_new ("pause-request", G_TYPE_FROM_CLASS (klass),
174       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, pause_request),
175       NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1,
176       G_TYPE_POINTER);
177
178   gst_rtsp_client_signals[SIGNAL_TEARDOWN_REQUEST] =
179       g_signal_new ("teardown-request", G_TYPE_FROM_CLASS (klass),
180       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, teardown_request),
181       NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1,
182       G_TYPE_POINTER);
183
184   gst_rtsp_client_signals[SIGNAL_SET_PARAMETER_REQUEST] =
185       g_signal_new ("set-parameter-request", G_TYPE_FROM_CLASS (klass),
186       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass,
187           set_parameter_request), NULL, NULL, g_cclosure_marshal_VOID__POINTER,
188       G_TYPE_NONE, 1, G_TYPE_POINTER);
189
190   gst_rtsp_client_signals[SIGNAL_GET_PARAMETER_REQUEST] =
191       g_signal_new ("get-parameter-request", G_TYPE_FROM_CLASS (klass),
192       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass,
193           get_parameter_request), NULL, NULL, g_cclosure_marshal_VOID__POINTER,
194       G_TYPE_NONE, 1, G_TYPE_POINTER);
195
196   tunnels =
197       g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_object_unref);
198   g_mutex_init (&tunnels_lock);
199
200   GST_DEBUG_CATEGORY_INIT (rtsp_client_debug, "rtspclient", 0, "GstRTSPClient");
201 }
202
203 static void
204 gst_rtsp_client_init (GstRTSPClient * client)
205 {
206   GstRTSPClientPrivate *priv = GST_RTSP_CLIENT_GET_PRIVATE (client);
207
208   client->priv = priv;
209
210   g_mutex_init (&priv->lock);
211   priv->use_client_settings = DEFAULT_USE_CLIENT_SETTINGS;
212   priv->close_seq = 0;
213 }
214
215 static GstRTSPFilterResult
216 filter_session (GstRTSPSession * sess, GstRTSPSessionMedia * media,
217     gpointer user_data)
218 {
219   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
220
221   gst_rtsp_session_media_set_state (media, GST_STATE_NULL);
222   unlink_session_transports (client, sess, media);
223
224   /* unmanage the media in the session */
225   return GST_RTSP_FILTER_REMOVE;
226 }
227
228 static void
229 client_unlink_session (GstRTSPClient * client, GstRTSPSession * session)
230 {
231   /* unlink all media managed in this session */
232   gst_rtsp_session_filter (session, filter_session, client);
233 }
234
235 static void
236 client_cleanup_sessions (GstRTSPClient * client)
237 {
238   GstRTSPClientPrivate *priv = client->priv;
239   GList *sessions;
240
241   /* remove weak-ref from sessions */
242   for (sessions = priv->sessions; sessions; sessions = g_list_next (sessions)) {
243     GstRTSPSession *session = (GstRTSPSession *) sessions->data;
244     g_object_weak_unref (G_OBJECT (session),
245         (GWeakNotify) client_session_finalized, client);
246     client_unlink_session (client, session);
247   }
248   g_list_free (priv->sessions);
249   priv->sessions = NULL;
250 }
251
252 /* A client is finalized when the connection is broken */
253 static void
254 gst_rtsp_client_finalize (GObject * obj)
255 {
256   GstRTSPClient *client = GST_RTSP_CLIENT (obj);
257   GstRTSPClientPrivate *priv = client->priv;
258
259   GST_INFO ("finalize client %p", client);
260
261   if (priv->watch)
262     g_source_destroy ((GSource *) priv->watch);
263
264   if (priv->send_notify)
265     priv->send_notify (priv->send_data);
266
267   client_cleanup_sessions (client);
268
269   if (priv->connection)
270     gst_rtsp_connection_free (priv->connection);
271   if (priv->session_pool)
272     g_object_unref (priv->session_pool);
273   if (priv->mount_points)
274     g_object_unref (priv->mount_points);
275   if (priv->auth)
276     g_object_unref (priv->auth);
277
278   if (priv->uri)
279     gst_rtsp_url_free (priv->uri);
280   if (priv->media) {
281     g_object_unref (priv->media);
282   }
283
284   g_free (priv->server_ip);
285   g_mutex_clear (&priv->lock);
286
287   G_OBJECT_CLASS (gst_rtsp_client_parent_class)->finalize (obj);
288 }
289
290 static void
291 gst_rtsp_client_get_property (GObject * object, guint propid,
292     GValue * value, GParamSpec * pspec)
293 {
294   GstRTSPClient *client = GST_RTSP_CLIENT (object);
295
296   switch (propid) {
297     case PROP_SESSION_POOL:
298       g_value_take_object (value, gst_rtsp_client_get_session_pool (client));
299       break;
300     case PROP_MOUNT_POINTS:
301       g_value_take_object (value, gst_rtsp_client_get_mount_points (client));
302       break;
303     case PROP_USE_CLIENT_SETTINGS:
304       g_value_set_boolean (value,
305           gst_rtsp_client_get_use_client_settings (client));
306       break;
307     default:
308       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, propid, pspec);
309   }
310 }
311
312 static void
313 gst_rtsp_client_set_property (GObject * object, guint propid,
314     const GValue * value, GParamSpec * pspec)
315 {
316   GstRTSPClient *client = GST_RTSP_CLIENT (object);
317
318   switch (propid) {
319     case PROP_SESSION_POOL:
320       gst_rtsp_client_set_session_pool (client, g_value_get_object (value));
321       break;
322     case PROP_MOUNT_POINTS:
323       gst_rtsp_client_set_mount_points (client, g_value_get_object (value));
324       break;
325     case PROP_USE_CLIENT_SETTINGS:
326       gst_rtsp_client_set_use_client_settings (client,
327           g_value_get_boolean (value));
328       break;
329     default:
330       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, propid, pspec);
331   }
332 }
333
334 /**
335  * gst_rtsp_client_new:
336  *
337  * Create a new #GstRTSPClient instance.
338  *
339  * Returns: a new #GstRTSPClient
340  */
341 GstRTSPClient *
342 gst_rtsp_client_new (void)
343 {
344   GstRTSPClient *result;
345
346   result = g_object_new (GST_TYPE_RTSP_CLIENT, NULL);
347
348   return result;
349 }
350
351 static void
352 send_response (GstRTSPClient * client, GstRTSPSession * session,
353     GstRTSPMessage * response, gboolean close)
354 {
355   GstRTSPClientPrivate *priv = client->priv;
356
357   gst_rtsp_message_add_header (response, GST_RTSP_HDR_SERVER,
358       "GStreamer RTSP server");
359
360   /* remove any previous header */
361   gst_rtsp_message_remove_header (response, GST_RTSP_HDR_SESSION, -1);
362
363   /* add the new session header for new session ids */
364   if (session) {
365     gst_rtsp_message_take_header (response, GST_RTSP_HDR_SESSION,
366         gst_rtsp_session_get_header (session));
367   }
368
369   if (gst_debug_category_get_threshold (rtsp_client_debug) >= GST_LEVEL_LOG) {
370     gst_rtsp_message_dump (response);
371   }
372
373   if (close)
374     gst_rtsp_message_add_header (response, GST_RTSP_HDR_CONNECTION, "close");
375
376   if (priv->send_func)
377     priv->send_func (client, response, close, priv->send_data);
378
379   gst_rtsp_message_unset (response);
380 }
381
382 static void
383 send_generic_response (GstRTSPClient * client, GstRTSPStatusCode code,
384     GstRTSPClientState * state)
385 {
386   gst_rtsp_message_init_response (state->response, code,
387       gst_rtsp_status_as_text (code), state->request);
388
389   send_response (client, NULL, state->response, FALSE);
390 }
391
392 static void
393 handle_unauthorized_request (GstRTSPClient * client, GstRTSPAuth * auth,
394     GstRTSPClientState * state)
395 {
396   gst_rtsp_message_init_response (state->response, GST_RTSP_STS_UNAUTHORIZED,
397       gst_rtsp_status_as_text (GST_RTSP_STS_UNAUTHORIZED), state->request);
398
399   if (auth) {
400     /* and let the authentication manager setup the auth tokens */
401     gst_rtsp_auth_setup_auth (auth, client, 0, state);
402   }
403
404   send_response (client, state->session, state->response, FALSE);
405 }
406
407
408 static gboolean
409 compare_uri (const GstRTSPUrl * uri1, const GstRTSPUrl * uri2)
410 {
411   if (uri1 == NULL || uri2 == NULL)
412     return FALSE;
413
414   if (strcmp (uri1->abspath, uri2->abspath))
415     return FALSE;
416
417   return TRUE;
418 }
419
420 /* this function is called to initially find the media for the DESCRIBE request
421  * but is cached for when the same client (without breaking the connection) is
422  * doing a setup for the exact same url. */
423 static GstRTSPMedia *
424 find_media (GstRTSPClient * client, GstRTSPClientState * state)
425 {
426   GstRTSPClientPrivate *priv = client->priv;
427   GstRTSPMediaFactory *factory;
428   GstRTSPMedia *media;
429   GstRTSPAuth *auth;
430
431   if (!compare_uri (priv->uri, state->uri)) {
432     /* remove any previously cached values before we try to construct a new
433      * media for uri */
434     if (priv->uri)
435       gst_rtsp_url_free (priv->uri);
436     priv->uri = NULL;
437     if (priv->media) {
438       g_object_unref (priv->media);
439     }
440     priv->media = NULL;
441
442     if (!priv->mount_points)
443       goto no_mount_points;
444
445     /* find the factory for the uri first */
446     if (!(factory =
447             gst_rtsp_mount_points_find_factory (priv->mount_points,
448                 state->uri)))
449       goto no_factory;
450
451     /* check if we have access to the factory */
452     if ((auth = gst_rtsp_media_factory_get_auth (factory))) {
453       state->factory = factory;
454
455       if (!gst_rtsp_auth_check (auth, client, 0, state))
456         goto not_allowed;
457
458       state->factory = NULL;
459       g_object_unref (auth);
460     }
461
462     /* prepare the media and add it to the pipeline */
463     if (!(media = gst_rtsp_media_factory_construct (factory, state->uri)))
464       goto no_media;
465
466     g_object_unref (factory);
467     factory = NULL;
468
469     /* prepare the media */
470     if (!(gst_rtsp_media_prepare (media)))
471       goto no_prepare;
472
473     /* now keep track of the uri and the media */
474     priv->uri = gst_rtsp_url_copy (state->uri);
475     priv->media = media;
476     state->media = media;
477   } else {
478     /* we have seen this uri before, used cached media */
479     media = priv->media;
480     state->media = media;
481     GST_INFO ("reusing cached media %p", media);
482   }
483
484   if (media)
485     g_object_ref (media);
486
487   return media;
488
489   /* ERRORS */
490 no_mount_points:
491   {
492     GST_ERROR ("client %p: no mount points configured", client);
493     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, state);
494     return NULL;
495   }
496 no_factory:
497   {
498     GST_ERROR ("client %p: no factory for uri", client);
499     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, state);
500     return NULL;
501   }
502 not_allowed:
503   {
504     GST_ERROR ("client %p: unauthorized request", client);
505     handle_unauthorized_request (client, auth, state);
506     g_object_unref (factory);
507     state->factory = NULL;
508     g_object_unref (auth);
509     return NULL;
510   }
511 no_media:
512   {
513     GST_ERROR ("client %p: can't create media", client);
514     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, state);
515     g_object_unref (factory);
516     return NULL;
517   }
518 no_prepare:
519   {
520     GST_ERROR ("client %p: can't prepare media", client);
521     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, state);
522     g_object_unref (media);
523     return NULL;
524   }
525 }
526
527 static gboolean
528 do_send_data (GstBuffer * buffer, guint8 channel, GstRTSPClient * client)
529 {
530   GstRTSPClientPrivate *priv = client->priv;
531   GstRTSPMessage message = { 0 };
532   GstMapInfo map_info;
533   guint8 *data;
534   guint usize;
535
536   gst_rtsp_message_init_data (&message, channel);
537
538   /* FIXME, need some sort of iovec RTSPMessage here */
539   if (!gst_buffer_map (buffer, &map_info, GST_MAP_READ))
540     return FALSE;
541
542   gst_rtsp_message_take_body (&message, map_info.data, map_info.size);
543
544   if (priv->send_func)
545     priv->send_func (client, &message, FALSE, priv->send_data);
546
547   gst_rtsp_message_steal_body (&message, &data, &usize);
548   gst_buffer_unmap (buffer, &map_info);
549
550   gst_rtsp_message_unset (&message);
551
552   return TRUE;
553 }
554
555 static void
556 link_transport (GstRTSPClient * client, GstRTSPSession * session,
557     GstRTSPStreamTransport * trans)
558 {
559   GstRTSPClientPrivate *priv = client->priv;
560
561   GST_DEBUG ("client %p: linking transport %p", client, trans);
562
563   gst_rtsp_stream_transport_set_callbacks (trans,
564       (GstRTSPSendFunc) do_send_data,
565       (GstRTSPSendFunc) do_send_data, client, NULL);
566
567   priv->transports = g_list_prepend (priv->transports, trans);
568
569   /* make sure our session can't expire */
570   gst_rtsp_session_prevent_expire (session);
571 }
572
573 static void
574 unlink_transport (GstRTSPClient * client, GstRTSPSession * session,
575     GstRTSPStreamTransport * trans)
576 {
577   GstRTSPClientPrivate *priv = client->priv;
578
579   GST_DEBUG ("client %p: unlinking transport %p", client, trans);
580
581   gst_rtsp_stream_transport_set_callbacks (trans, NULL, NULL, NULL, NULL);
582
583   priv->transports = g_list_remove (priv->transports, trans);
584
585   /* our session can now expire */
586   gst_rtsp_session_allow_expire (session);
587 }
588
589 static void
590 unlink_session_transports (GstRTSPClient * client, GstRTSPSession * session,
591     GstRTSPSessionMedia * media)
592 {
593   guint n_streams, i;
594
595   n_streams =
596       gst_rtsp_media_n_streams (gst_rtsp_session_media_get_media (media));
597   for (i = 0; i < n_streams; i++) {
598     GstRTSPStreamTransport *trans;
599     const GstRTSPTransport *tr;
600
601     /* get the transport, if there is no transport configured, skip this stream */
602     trans = gst_rtsp_session_media_get_transport (media, i);
603     if (trans == NULL)
604       continue;
605
606     tr = gst_rtsp_stream_transport_get_transport (trans);
607
608     if (tr->lower_transport == GST_RTSP_LOWER_TRANS_TCP) {
609       /* for TCP, unlink the stream from the TCP connection of the client */
610       unlink_transport (client, session, trans);
611     }
612   }
613 }
614
615 static void
616 close_connection (GstRTSPClient * client)
617 {
618   GstRTSPClientPrivate *priv = client->priv;
619   const gchar *tunnelid;
620
621   GST_DEBUG ("client %p: closing connection", client);
622
623   if ((tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection))) {
624     g_mutex_lock (&tunnels_lock);
625     /* remove from tunnelids */
626     g_hash_table_remove (tunnels, tunnelid);
627     g_mutex_unlock (&tunnels_lock);
628   }
629
630   gst_rtsp_connection_close (priv->connection);
631 }
632
633 static gboolean
634 handle_teardown_request (GstRTSPClient * client, GstRTSPClientState * state)
635 {
636   GstRTSPClientPrivate *priv = client->priv;
637   GstRTSPSession *session;
638   GstRTSPSessionMedia *media;
639   GstRTSPStatusCode code;
640
641   if (!state->session)
642     goto no_session;
643
644   session = state->session;
645
646   /* get a handle to the configuration of the media in the session */
647   media = gst_rtsp_session_get_media (session, state->uri);
648   if (!media)
649     goto not_found;
650
651   state->sessmedia = media;
652
653   /* unlink the all TCP callbacks */
654   unlink_session_transports (client, session, media);
655
656   /* remove the session from the watched sessions */
657   g_object_weak_unref (G_OBJECT (session),
658       (GWeakNotify) client_session_finalized, client);
659   priv->sessions = g_list_remove (priv->sessions, session);
660
661   gst_rtsp_session_media_set_state (media, GST_STATE_NULL);
662
663   /* unmanage the media in the session, returns false if all media session
664    * are torn down. */
665   if (!gst_rtsp_session_release_media (session, media)) {
666     /* remove the session */
667     gst_rtsp_session_pool_remove (priv->session_pool, session);
668   }
669   /* construct the response now */
670   code = GST_RTSP_STS_OK;
671   gst_rtsp_message_init_response (state->response, code,
672       gst_rtsp_status_as_text (code), state->request);
673
674   send_response (client, session, state->response, TRUE);
675
676   /* we emit the signal before closing the connection */
677   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_TEARDOWN_REQUEST],
678       0, state);
679
680   return TRUE;
681
682   /* ERRORS */
683 no_session:
684   {
685     GST_ERROR ("client %p: no session", client);
686     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, state);
687     return FALSE;
688   }
689 not_found:
690   {
691     GST_ERROR ("client %p: no media for uri", client);
692     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, state);
693     return FALSE;
694   }
695 }
696
697 static gboolean
698 handle_get_param_request (GstRTSPClient * client, GstRTSPClientState * state)
699 {
700   GstRTSPResult res;
701   guint8 *data;
702   guint size;
703
704   res = gst_rtsp_message_get_body (state->request, &data, &size);
705   if (res != GST_RTSP_OK)
706     goto bad_request;
707
708   if (size == 0) {
709     /* no body, keep-alive request */
710     send_generic_response (client, GST_RTSP_STS_OK, state);
711   } else {
712     /* there is a body, handle the params */
713     res = gst_rtsp_params_get (client, state);
714     if (res != GST_RTSP_OK)
715       goto bad_request;
716
717     send_response (client, state->session, state->response, FALSE);
718   }
719
720   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_GET_PARAMETER_REQUEST],
721       0, state);
722
723   return TRUE;
724
725   /* ERRORS */
726 bad_request:
727   {
728     GST_ERROR ("client %p: bad request", client);
729     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, state);
730     return FALSE;
731   }
732 }
733
734 static gboolean
735 handle_set_param_request (GstRTSPClient * client, GstRTSPClientState * state)
736 {
737   GstRTSPResult res;
738   guint8 *data;
739   guint size;
740
741   res = gst_rtsp_message_get_body (state->request, &data, &size);
742   if (res != GST_RTSP_OK)
743     goto bad_request;
744
745   if (size == 0) {
746     /* no body, keep-alive request */
747     send_generic_response (client, GST_RTSP_STS_OK, state);
748   } else {
749     /* there is a body, handle the params */
750     res = gst_rtsp_params_set (client, state);
751     if (res != GST_RTSP_OK)
752       goto bad_request;
753
754     send_response (client, state->session, state->response, FALSE);
755   }
756
757   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_SET_PARAMETER_REQUEST],
758       0, state);
759
760   return TRUE;
761
762   /* ERRORS */
763 bad_request:
764   {
765     GST_ERROR ("client %p: bad request", client);
766     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, state);
767     return FALSE;
768   }
769 }
770
771 static gboolean
772 handle_pause_request (GstRTSPClient * client, GstRTSPClientState * state)
773 {
774   GstRTSPSession *session;
775   GstRTSPSessionMedia *media;
776   GstRTSPStatusCode code;
777   GstRTSPState rtspstate;
778
779   if (!(session = state->session))
780     goto no_session;
781
782   /* get a handle to the configuration of the media in the session */
783   media = gst_rtsp_session_get_media (session, state->uri);
784   if (!media)
785     goto not_found;
786
787   state->sessmedia = media;
788
789   rtspstate = gst_rtsp_session_media_get_rtsp_state (media);
790   /* the session state must be playing or recording */
791   if (rtspstate != GST_RTSP_STATE_PLAYING &&
792       rtspstate != GST_RTSP_STATE_RECORDING)
793     goto invalid_state;
794
795   /* unlink the all TCP callbacks */
796   unlink_session_transports (client, session, media);
797
798   /* then pause sending */
799   gst_rtsp_session_media_set_state (media, GST_STATE_PAUSED);
800
801   /* construct the response now */
802   code = GST_RTSP_STS_OK;
803   gst_rtsp_message_init_response (state->response, code,
804       gst_rtsp_status_as_text (code), state->request);
805
806   send_response (client, session, state->response, FALSE);
807
808   /* the state is now READY */
809   gst_rtsp_session_media_set_rtsp_state (media, GST_RTSP_STATE_READY);
810
811   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_PAUSE_REQUEST],
812       0, state);
813
814   return TRUE;
815
816   /* ERRORS */
817 no_session:
818   {
819     GST_ERROR ("client %p: no seesion", client);
820     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, state);
821     return FALSE;
822   }
823 not_found:
824   {
825     GST_ERROR ("client %p: no media for uri", client);
826     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, state);
827     return FALSE;
828   }
829 invalid_state:
830   {
831     GST_ERROR ("client %p: not PLAYING or RECORDING", client);
832     send_generic_response (client, GST_RTSP_STS_METHOD_NOT_VALID_IN_THIS_STATE,
833         state);
834     return FALSE;
835   }
836 }
837
838 static gboolean
839 handle_play_request (GstRTSPClient * client, GstRTSPClientState * state)
840 {
841   GstRTSPSession *session;
842   GstRTSPSessionMedia *media;
843   GstRTSPStatusCode code;
844   GString *rtpinfo;
845   guint n_streams, i, infocount;
846   gchar *str;
847   GstRTSPTimeRange *range;
848   GstRTSPResult res;
849   GstRTSPState rtspstate;
850
851   if (!(session = state->session))
852     goto no_session;
853
854   /* get a handle to the configuration of the media in the session */
855   media = gst_rtsp_session_get_media (session, state->uri);
856   if (!media)
857     goto not_found;
858
859   state->sessmedia = media;
860
861   /* the session state must be playing or ready */
862   rtspstate = gst_rtsp_session_media_get_rtsp_state (media);
863   if (rtspstate != GST_RTSP_STATE_PLAYING && rtspstate != GST_RTSP_STATE_READY)
864     goto invalid_state;
865
866   /* parse the range header if we have one */
867   res =
868       gst_rtsp_message_get_header (state->request, GST_RTSP_HDR_RANGE, &str, 0);
869   if (res == GST_RTSP_OK) {
870     if (gst_rtsp_range_parse (str, &range) == GST_RTSP_OK) {
871       /* we have a range, seek to the position */
872       gst_rtsp_media_seek (gst_rtsp_session_media_get_media (media), range);
873       gst_rtsp_range_free (range);
874     }
875   }
876
877   /* grab RTPInfo from the payloaders now */
878   rtpinfo = g_string_new ("");
879
880   n_streams =
881       gst_rtsp_media_n_streams (gst_rtsp_session_media_get_media (media));
882   for (i = 0, infocount = 0; i < n_streams; i++) {
883     GstRTSPStreamTransport *trans;
884     GstRTSPStream *stream;
885     const GstRTSPTransport *tr;
886     gchar *uristr;
887     guint rtptime, seq;
888
889     /* get the transport, if there is no transport configured, skip this stream */
890     trans = gst_rtsp_session_media_get_transport (media, i);
891     if (trans == NULL) {
892       GST_INFO ("stream %d is not configured", i);
893       continue;
894     }
895     tr = gst_rtsp_stream_transport_get_transport (trans);
896
897     if (tr->lower_transport == GST_RTSP_LOWER_TRANS_TCP) {
898       /* for TCP, link the stream to the TCP connection of the client */
899       link_transport (client, session, trans);
900     }
901
902     stream = gst_rtsp_stream_transport_get_stream (trans);
903     if (gst_rtsp_stream_get_rtpinfo (stream, &rtptime, &seq)) {
904       if (infocount > 0)
905         g_string_append (rtpinfo, ", ");
906
907       uristr = gst_rtsp_url_get_request_uri (state->uri);
908       g_string_append_printf (rtpinfo, "url=%s/stream=%d;seq=%u;rtptime=%u",
909           uristr, i, seq, rtptime);
910       g_free (uristr);
911
912       infocount++;
913     } else {
914       GST_WARNING ("RTP-Info cannot be determined for stream %d", i);
915     }
916   }
917
918   /* construct the response now */
919   code = GST_RTSP_STS_OK;
920   gst_rtsp_message_init_response (state->response, code,
921       gst_rtsp_status_as_text (code), state->request);
922
923   /* add the RTP-Info header */
924   if (infocount > 0) {
925     str = g_string_free (rtpinfo, FALSE);
926     gst_rtsp_message_take_header (state->response, GST_RTSP_HDR_RTP_INFO, str);
927   } else {
928     g_string_free (rtpinfo, TRUE);
929   }
930
931   /* add the range */
932   str =
933       gst_rtsp_media_get_range_string (gst_rtsp_session_media_get_media (media),
934       TRUE);
935   gst_rtsp_message_take_header (state->response, GST_RTSP_HDR_RANGE, str);
936
937   send_response (client, session, state->response, FALSE);
938
939   /* start playing after sending the request */
940   gst_rtsp_session_media_set_state (media, GST_STATE_PLAYING);
941
942   gst_rtsp_session_media_set_rtsp_state (media, GST_RTSP_STATE_PLAYING);
943
944   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_PLAY_REQUEST],
945       0, state);
946
947   return TRUE;
948
949   /* ERRORS */
950 no_session:
951   {
952     GST_ERROR ("client %p: no session", client);
953     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, state);
954     return FALSE;
955   }
956 not_found:
957   {
958     GST_ERROR ("client %p: media not found", client);
959     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, state);
960     return FALSE;
961   }
962 invalid_state:
963   {
964     GST_ERROR ("client %p: not PLAYING or READY", client);
965     send_generic_response (client, GST_RTSP_STS_METHOD_NOT_VALID_IN_THIS_STATE,
966         state);
967     return FALSE;
968   }
969 }
970
971 static void
972 do_keepalive (GstRTSPSession * session)
973 {
974   GST_INFO ("keep session %p alive", session);
975   gst_rtsp_session_touch (session);
976 }
977
978 /* parse @transport and return a valid transport in @tr. only transports
979  * from @supported are returned. Returns FALSE if no valid transport
980  * was found. */
981 static gboolean
982 parse_transport (const char *transport, GstRTSPLowerTrans supported,
983     GstRTSPTransport * tr)
984 {
985   gint i;
986   gboolean res;
987   gchar **transports;
988
989   res = FALSE;
990   gst_rtsp_transport_init (tr);
991
992   GST_DEBUG ("parsing transports %s", transport);
993
994   transports = g_strsplit (transport, ",", 0);
995
996   /* loop through the transports, try to parse */
997   for (i = 0; transports[i]; i++) {
998     res = gst_rtsp_transport_parse (transports[i], tr);
999     if (res != GST_RTSP_OK) {
1000       /* no valid transport, search some more */
1001       GST_WARNING ("could not parse transport %s", transports[i]);
1002       goto next;
1003     }
1004
1005     /* we have a transport, see if it's RTP/AVP */
1006     if (tr->trans != GST_RTSP_TRANS_RTP || tr->profile != GST_RTSP_PROFILE_AVP) {
1007       GST_WARNING ("invalid transport %s", transports[i]);
1008       goto next;
1009     }
1010
1011     if (!(tr->lower_transport & supported)) {
1012       GST_WARNING ("unsupported transport %s", transports[i]);
1013       goto next;
1014     }
1015
1016     /* we have a valid transport */
1017     GST_INFO ("found valid transport %s", transports[i]);
1018     res = TRUE;
1019     break;
1020
1021   next:
1022     gst_rtsp_transport_init (tr);
1023   }
1024   g_strfreev (transports);
1025
1026   return res;
1027 }
1028
1029 static gboolean
1030 handle_blocksize (GstRTSPMedia * media, GstRTSPStream * stream,
1031     GstRTSPMessage * request)
1032 {
1033   gchar *blocksize_str;
1034   gboolean ret = TRUE;
1035
1036   if (gst_rtsp_message_get_header (request, GST_RTSP_HDR_BLOCKSIZE,
1037           &blocksize_str, 0) == GST_RTSP_OK) {
1038     guint64 blocksize;
1039     gchar *end;
1040
1041     blocksize = g_ascii_strtoull (blocksize_str, &end, 10);
1042     if (end == blocksize_str) {
1043       GST_ERROR ("failed to parse blocksize");
1044       ret = FALSE;
1045     } else {
1046       /* we don't want to change the mtu when this media
1047        * can be shared because it impacts other clients */
1048       if (gst_rtsp_media_is_shared (media))
1049         return TRUE;
1050
1051       if (blocksize > G_MAXUINT)
1052         blocksize = G_MAXUINT;
1053       gst_rtsp_stream_set_mtu (stream, blocksize);
1054     }
1055   }
1056   return ret;
1057 }
1058
1059 static gboolean
1060 configure_client_transport (GstRTSPClient * client, GstRTSPClientState * state,
1061     GstRTSPTransport * ct)
1062 {
1063   GstRTSPClientPrivate *priv = client->priv;
1064
1065   /* we have a valid transport now, set the destination of the client. */
1066   if (ct->lower_transport == GST_RTSP_LOWER_TRANS_UDP_MCAST) {
1067     if (ct->destination == NULL || !priv->use_client_settings) {
1068       GstRTSPAddress *addr;
1069
1070       addr = gst_rtsp_stream_get_address (state->stream);
1071       if (addr == NULL)
1072         goto no_address;
1073
1074       g_free (ct->destination);
1075       ct->destination = g_strdup (addr->address);
1076       ct->port.min = addr->port;
1077       ct->port.max = addr->port + addr->n_ports - 1;
1078       ct->ttl = addr->ttl;
1079     }
1080   } else {
1081     GstRTSPUrl *url;
1082
1083     url = gst_rtsp_connection_get_url (priv->connection);
1084     g_free (ct->destination);
1085     ct->destination = g_strdup (url->host);
1086
1087     if (ct->lower_transport & GST_RTSP_LOWER_TRANS_TCP) {
1088       /* check if the client selected channels for TCP */
1089       if (ct->interleaved.min == -1 || ct->interleaved.max == -1) {
1090         gst_rtsp_session_media_alloc_channels (state->sessmedia,
1091             &ct->interleaved);
1092       }
1093     }
1094   }
1095   return TRUE;
1096
1097   /* ERRORS */
1098 no_address:
1099   {
1100     GST_ERROR_OBJECT (client, "failed to acquire address for stream");
1101     return FALSE;
1102   }
1103 }
1104
1105 static GstRTSPTransport *
1106 make_server_transport (GstRTSPClient * client, GstRTSPClientState * state,
1107     GstRTSPTransport * ct)
1108 {
1109   GstRTSPTransport *st;
1110
1111   /* prepare the server transport */
1112   gst_rtsp_transport_new (&st);
1113
1114   st->trans = ct->trans;
1115   st->profile = ct->profile;
1116   st->lower_transport = ct->lower_transport;
1117
1118   switch (st->lower_transport) {
1119     case GST_RTSP_LOWER_TRANS_UDP:
1120       st->client_port = ct->client_port;
1121       gst_rtsp_stream_get_server_port (state->stream, &st->server_port);
1122       break;
1123     case GST_RTSP_LOWER_TRANS_UDP_MCAST:
1124       st->port = ct->port;
1125       st->destination = g_strdup (ct->destination);
1126       st->ttl = ct->ttl;
1127       break;
1128     case GST_RTSP_LOWER_TRANS_TCP:
1129       st->interleaved = ct->interleaved;
1130     default:
1131       break;
1132   }
1133
1134   gst_rtsp_stream_get_ssrc (state->stream, &st->ssrc);
1135
1136   return st;
1137 }
1138
1139 static gboolean
1140 handle_setup_request (GstRTSPClient * client, GstRTSPClientState * state)
1141 {
1142   GstRTSPClientPrivate *priv = client->priv;
1143   GstRTSPResult res;
1144   GstRTSPUrl *uri;
1145   gchar *transport;
1146   GstRTSPTransport *ct, *st;
1147   GstRTSPLowerTrans supported;
1148   GstRTSPStatusCode code;
1149   GstRTSPSession *session;
1150   GstRTSPStreamTransport *trans;
1151   gchar *trans_str, *pos;
1152   guint streamid;
1153   GstRTSPSessionMedia *sessmedia;
1154   GstRTSPMedia *media;
1155   GstRTSPStream *stream;
1156   GstRTSPState rtspstate;
1157
1158   uri = state->uri;
1159
1160   /* the uri contains the stream number we added in the SDP config, which is
1161    * always /stream=%d so we need to strip that off
1162    * parse the stream we need to configure, look for the stream in the abspath
1163    * first and then in the query. */
1164   if (uri->abspath == NULL || !(pos = strstr (uri->abspath, "/stream="))) {
1165     if (uri->query == NULL || !(pos = strstr (uri->query, "/stream=")))
1166       goto bad_request;
1167   }
1168
1169   /* we can mofify the parsed uri in place */
1170   *pos = '\0';
1171
1172   pos += strlen ("/stream=");
1173   if (sscanf (pos, "%u", &streamid) != 1)
1174     goto bad_request;
1175
1176   /* parse the transport */
1177   res =
1178       gst_rtsp_message_get_header (state->request, GST_RTSP_HDR_TRANSPORT,
1179       &transport, 0);
1180   if (res != GST_RTSP_OK)
1181     goto no_transport;
1182
1183   gst_rtsp_transport_new (&ct);
1184
1185   /* our supported transports */
1186   supported = GST_RTSP_LOWER_TRANS_UDP |
1187       GST_RTSP_LOWER_TRANS_UDP_MCAST | GST_RTSP_LOWER_TRANS_TCP;
1188
1189   /* parse and find a usable supported transport */
1190   if (!parse_transport (transport, supported, ct))
1191     goto unsupported_transports;
1192
1193   /* we create the session after parsing stuff so that we don't make
1194    * a session for malformed requests */
1195   if (priv->session_pool == NULL)
1196     goto no_pool;
1197
1198   session = state->session;
1199
1200   if (session) {
1201     g_object_ref (session);
1202     /* get a handle to the configuration of the media in the session, this can
1203      * return NULL if this is a new url to manage in this session. */
1204     sessmedia = gst_rtsp_session_get_media (session, uri);
1205   } else {
1206     /* create a session if this fails we probably reached our session limit or
1207      * something. */
1208     if (!(session = gst_rtsp_session_pool_create (priv->session_pool)))
1209       goto service_unavailable;
1210
1211     state->session = session;
1212
1213     /* we need a new media configuration in this session */
1214     sessmedia = NULL;
1215   }
1216
1217   /* we have no media, find one and manage it */
1218   if (sessmedia == NULL) {
1219     /* get a handle to the configuration of the media in the session */
1220     if ((media = find_media (client, state))) {
1221       /* manage the media in our session now */
1222       sessmedia = gst_rtsp_session_manage_media (session, uri, media);
1223     }
1224   }
1225
1226   /* if we stil have no media, error */
1227   if (sessmedia == NULL)
1228     goto not_found;
1229
1230   state->sessmedia = sessmedia;
1231   state->media = media = gst_rtsp_session_media_get_media (sessmedia);
1232
1233   /* now get the stream */
1234   stream = gst_rtsp_media_get_stream (media, streamid);
1235   if (stream == NULL)
1236     goto not_found;
1237
1238   state->stream = stream;
1239
1240   /* set blocksize on this stream */
1241   if (!handle_blocksize (media, stream, state->request))
1242     goto invalid_blocksize;
1243
1244   /* update the client transport */
1245   if (!configure_client_transport (client, state, ct))
1246     goto unsupported_client_transport;
1247
1248   /* set in the session media transport */
1249   trans = gst_rtsp_session_media_set_transport (sessmedia, stream, ct);
1250
1251   /* configure keepalive for this transport */
1252   gst_rtsp_stream_transport_set_keepalive (trans,
1253       (GstRTSPKeepAliveFunc) do_keepalive, session, NULL);
1254
1255   /* create and serialize the server transport */
1256   st = make_server_transport (client, state, ct);
1257   trans_str = gst_rtsp_transport_as_text (st);
1258   gst_rtsp_transport_free (st);
1259
1260   /* construct the response now */
1261   code = GST_RTSP_STS_OK;
1262   gst_rtsp_message_init_response (state->response, code,
1263       gst_rtsp_status_as_text (code), state->request);
1264
1265   gst_rtsp_message_add_header (state->response, GST_RTSP_HDR_TRANSPORT,
1266       trans_str);
1267   g_free (trans_str);
1268
1269   send_response (client, session, state->response, FALSE);
1270
1271   /* update the state */
1272   rtspstate = gst_rtsp_session_media_get_rtsp_state (sessmedia);
1273   switch (rtspstate) {
1274     case GST_RTSP_STATE_PLAYING:
1275     case GST_RTSP_STATE_RECORDING:
1276     case GST_RTSP_STATE_READY:
1277       /* no state change */
1278       break;
1279     default:
1280       gst_rtsp_session_media_set_rtsp_state (sessmedia, GST_RTSP_STATE_READY);
1281       break;
1282   }
1283   g_object_unref (session);
1284
1285   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_SETUP_REQUEST],
1286       0, state);
1287
1288   return TRUE;
1289
1290   /* ERRORS */
1291 bad_request:
1292   {
1293     GST_ERROR ("client %p: bad request", client);
1294     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, state);
1295     return FALSE;
1296   }
1297 not_found:
1298   {
1299     GST_ERROR ("client %p: media not found", client);
1300     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, state);
1301     g_object_unref (session);
1302     gst_rtsp_transport_free (ct);
1303     return FALSE;
1304   }
1305 invalid_blocksize:
1306   {
1307     GST_ERROR ("client %p: invalid blocksize", client);
1308     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, state);
1309     g_object_unref (session);
1310     gst_rtsp_transport_free (ct);
1311     return FALSE;
1312   }
1313 unsupported_client_transport:
1314   {
1315     GST_ERROR ("client %p: unsupported client transport", client);
1316     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, state);
1317     g_object_unref (session);
1318     gst_rtsp_transport_free (ct);
1319     return FALSE;
1320   }
1321 no_transport:
1322   {
1323     GST_ERROR ("client %p: no transport", client);
1324     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, state);
1325     return FALSE;
1326   }
1327 unsupported_transports:
1328   {
1329     GST_ERROR ("client %p: unsupported transports", client);
1330     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, state);
1331     gst_rtsp_transport_free (ct);
1332     return FALSE;
1333   }
1334 no_pool:
1335   {
1336     GST_ERROR ("client %p: no session pool configured", client);
1337     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, state);
1338     gst_rtsp_transport_free (ct);
1339     return FALSE;
1340   }
1341 service_unavailable:
1342   {
1343     GST_ERROR ("client %p: can't create session", client);
1344     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, state);
1345     gst_rtsp_transport_free (ct);
1346     return FALSE;
1347   }
1348 }
1349
1350 static GstSDPMessage *
1351 create_sdp (GstRTSPClient * client, GstRTSPMedia * media)
1352 {
1353   GstRTSPClientPrivate *priv = client->priv;
1354   GstSDPMessage *sdp;
1355   GstSDPInfo info;
1356   const gchar *proto;
1357
1358   gst_sdp_message_new (&sdp);
1359
1360   /* some standard things first */
1361   gst_sdp_message_set_version (sdp, "0");
1362
1363   if (priv->is_ipv6)
1364     proto = "IP6";
1365   else
1366     proto = "IP4";
1367
1368   gst_sdp_message_set_origin (sdp, "-", "1188340656180883", "1", "IN", proto,
1369       priv->server_ip);
1370
1371   gst_sdp_message_set_session_name (sdp, "Session streamed with GStreamer");
1372   gst_sdp_message_set_information (sdp, "rtsp-server");
1373   gst_sdp_message_add_time (sdp, "0", "0", NULL);
1374   gst_sdp_message_add_attribute (sdp, "tool", "GStreamer");
1375   gst_sdp_message_add_attribute (sdp, "type", "broadcast");
1376   gst_sdp_message_add_attribute (sdp, "control", "*");
1377
1378   info.server_proto = proto;
1379   info.server_ip = g_strdup (priv->server_ip);
1380
1381   /* create an SDP for the media object */
1382   if (!gst_rtsp_sdp_from_media (sdp, &info, media))
1383     goto no_sdp;
1384
1385   g_free (info.server_ip);
1386
1387   return sdp;
1388
1389   /* ERRORS */
1390 no_sdp:
1391   {
1392     GST_ERROR ("client %p: could not create SDP", client);
1393     g_free (info.server_ip);
1394     gst_sdp_message_free (sdp);
1395     return NULL;
1396   }
1397 }
1398
1399 /* for the describe we must generate an SDP */
1400 static gboolean
1401 handle_describe_request (GstRTSPClient * client, GstRTSPClientState * state)
1402 {
1403   GstRTSPResult res;
1404   GstSDPMessage *sdp;
1405   guint i, str_len;
1406   gchar *str, *content_base;
1407   GstRTSPMedia *media;
1408   GstRTSPClientClass *klass;
1409
1410   klass = GST_RTSP_CLIENT_GET_CLASS (client);
1411
1412   /* check what kind of format is accepted, we don't really do anything with it
1413    * and always return SDP for now. */
1414   for (i = 0; i++;) {
1415     gchar *accept;
1416
1417     res =
1418         gst_rtsp_message_get_header (state->request, GST_RTSP_HDR_ACCEPT,
1419         &accept, i);
1420     if (res == GST_RTSP_ENOTIMPL)
1421       break;
1422
1423     if (g_ascii_strcasecmp (accept, "application/sdp") == 0)
1424       break;
1425   }
1426
1427   /* find the media object for the uri */
1428   if (!(media = find_media (client, state)))
1429     goto no_media;
1430
1431   /* create an SDP for the media object on this client */
1432   if (!(sdp = klass->create_sdp (client, media)))
1433     goto no_sdp;
1434
1435   g_object_unref (media);
1436
1437   gst_rtsp_message_init_response (state->response, GST_RTSP_STS_OK,
1438       gst_rtsp_status_as_text (GST_RTSP_STS_OK), state->request);
1439
1440   gst_rtsp_message_add_header (state->response, GST_RTSP_HDR_CONTENT_TYPE,
1441       "application/sdp");
1442
1443   /* content base for some clients that might screw up creating the setup uri */
1444   str = gst_rtsp_url_get_request_uri (state->uri);
1445   str_len = strlen (str);
1446
1447   /* check for trailing '/' and append one */
1448   if (str[str_len - 1] != '/') {
1449     content_base = g_malloc (str_len + 2);
1450     memcpy (content_base, str, str_len);
1451     content_base[str_len] = '/';
1452     content_base[str_len + 1] = '\0';
1453     g_free (str);
1454   } else {
1455     content_base = str;
1456   }
1457
1458   GST_INFO ("adding content-base: %s", content_base);
1459
1460   gst_rtsp_message_add_header (state->response, GST_RTSP_HDR_CONTENT_BASE,
1461       content_base);
1462   g_free (content_base);
1463
1464   /* add SDP to the response body */
1465   str = gst_sdp_message_as_text (sdp);
1466   gst_rtsp_message_take_body (state->response, (guint8 *) str, strlen (str));
1467   gst_sdp_message_free (sdp);
1468
1469   send_response (client, state->session, state->response, FALSE);
1470
1471   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_DESCRIBE_REQUEST],
1472       0, state);
1473
1474   return TRUE;
1475
1476   /* ERRORS */
1477 no_media:
1478   {
1479     GST_ERROR ("client %p: no media", client);
1480     /* error reply is already sent */
1481     return FALSE;
1482   }
1483 no_sdp:
1484   {
1485     GST_ERROR ("client %p: can't create SDP", client);
1486     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, state);
1487     g_object_unref (media);
1488     return FALSE;
1489   }
1490 }
1491
1492 static gboolean
1493 handle_options_request (GstRTSPClient * client, GstRTSPClientState * state)
1494 {
1495   GstRTSPMethod options;
1496   gchar *str;
1497
1498   options = GST_RTSP_DESCRIBE |
1499       GST_RTSP_OPTIONS |
1500       GST_RTSP_PAUSE |
1501       GST_RTSP_PLAY |
1502       GST_RTSP_SETUP |
1503       GST_RTSP_GET_PARAMETER | GST_RTSP_SET_PARAMETER | GST_RTSP_TEARDOWN;
1504
1505   str = gst_rtsp_options_as_text (options);
1506
1507   gst_rtsp_message_init_response (state->response, GST_RTSP_STS_OK,
1508       gst_rtsp_status_as_text (GST_RTSP_STS_OK), state->request);
1509
1510   gst_rtsp_message_add_header (state->response, GST_RTSP_HDR_PUBLIC, str);
1511   g_free (str);
1512
1513   send_response (client, state->session, state->response, FALSE);
1514
1515   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_OPTIONS_REQUEST],
1516       0, state);
1517
1518   return TRUE;
1519 }
1520
1521 /* remove duplicate and trailing '/' */
1522 static void
1523 sanitize_uri (GstRTSPUrl * uri)
1524 {
1525   gint i, len;
1526   gchar *s, *d;
1527   gboolean have_slash, prev_slash;
1528
1529   s = d = uri->abspath;
1530   len = strlen (uri->abspath);
1531
1532   prev_slash = FALSE;
1533
1534   for (i = 0; i < len; i++) {
1535     have_slash = s[i] == '/';
1536     *d = s[i];
1537     if (!have_slash || !prev_slash)
1538       d++;
1539     prev_slash = have_slash;
1540   }
1541   len = d - uri->abspath;
1542   /* don't remove the first slash if that's the only thing left */
1543   if (len > 1 && *(d - 1) == '/')
1544     d--;
1545   *d = '\0';
1546 }
1547
1548 static void
1549 client_session_finalized (GstRTSPClient * client, GstRTSPSession * session)
1550 {
1551   GstRTSPClientPrivate *priv = client->priv;
1552
1553   GST_INFO ("client %p: session %p finished", client, session);
1554
1555   /* unlink all media managed in this session */
1556   client_unlink_session (client, session);
1557
1558   /* remove the session */
1559   if (!(priv->sessions = g_list_remove (priv->sessions, session))) {
1560     GST_INFO ("client %p: all sessions finalized, close the connection",
1561         client);
1562     close_connection (client);
1563   }
1564 }
1565
1566 static void
1567 client_watch_session (GstRTSPClient * client, GstRTSPSession * session)
1568 {
1569   GstRTSPClientPrivate *priv = client->priv;
1570   GList *walk;
1571
1572   for (walk = priv->sessions; walk; walk = g_list_next (walk)) {
1573     GstRTSPSession *msession = (GstRTSPSession *) walk->data;
1574
1575     /* we already know about this session */
1576     if (msession == session)
1577       return;
1578   }
1579
1580   GST_INFO ("watching session %p", session);
1581
1582   g_object_weak_ref (G_OBJECT (session), (GWeakNotify) client_session_finalized,
1583       client);
1584   priv->sessions = g_list_prepend (priv->sessions, session);
1585
1586   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_NEW_SESSION], 0,
1587       session);
1588 }
1589
1590 static void
1591 handle_request (GstRTSPClient * client, GstRTSPMessage * request)
1592 {
1593   GstRTSPClientPrivate *priv = client->priv;
1594   GstRTSPMethod method;
1595   const gchar *uristr;
1596   GstRTSPUrl *uri = NULL;
1597   GstRTSPVersion version;
1598   GstRTSPResult res;
1599   GstRTSPSession *session = NULL;
1600   GstRTSPClientState state = { NULL };
1601   GstRTSPMessage response = { 0 };
1602   gchar *sessid;
1603
1604   state.request = request;
1605   state.response = &response;
1606
1607   if (gst_debug_category_get_threshold (rtsp_client_debug) >= GST_LEVEL_LOG) {
1608     gst_rtsp_message_dump (request);
1609   }
1610
1611   GST_INFO ("client %p: received a request", client);
1612
1613   gst_rtsp_message_parse_request (request, &method, &uristr, &version);
1614
1615   /* we can only handle 1.0 requests */
1616   if (version != GST_RTSP_VERSION_1_0)
1617     goto not_supported;
1618
1619   state.method = method;
1620
1621   /* we always try to parse the url first */
1622   if (gst_rtsp_url_parse (uristr, &uri) != GST_RTSP_OK)
1623     goto bad_request;
1624
1625   /* get the session if there is any */
1626   res = gst_rtsp_message_get_header (request, GST_RTSP_HDR_SESSION, &sessid, 0);
1627   if (res == GST_RTSP_OK) {
1628     if (priv->session_pool == NULL)
1629       goto no_pool;
1630
1631     /* we had a session in the request, find it again */
1632     if (!(session = gst_rtsp_session_pool_find (priv->session_pool, sessid)))
1633       goto session_not_found;
1634
1635     /* we add the session to the client list of watched sessions. When a session
1636      * disappears because it times out, we will be notified. If all sessions are
1637      * gone, we will close the connection */
1638     client_watch_session (client, session);
1639   }
1640
1641   /* sanitize the uri */
1642   sanitize_uri (uri);
1643   state.uri = uri;
1644   state.session = session;
1645
1646   if (priv->auth) {
1647     if (!gst_rtsp_auth_check (priv->auth, client, 0, &state))
1648       goto not_authorized;
1649   }
1650
1651   /* now see what is asked and dispatch to a dedicated handler */
1652   switch (method) {
1653     case GST_RTSP_OPTIONS:
1654       handle_options_request (client, &state);
1655       break;
1656     case GST_RTSP_DESCRIBE:
1657       handle_describe_request (client, &state);
1658       break;
1659     case GST_RTSP_SETUP:
1660       handle_setup_request (client, &state);
1661       break;
1662     case GST_RTSP_PLAY:
1663       handle_play_request (client, &state);
1664       break;
1665     case GST_RTSP_PAUSE:
1666       handle_pause_request (client, &state);
1667       break;
1668     case GST_RTSP_TEARDOWN:
1669       handle_teardown_request (client, &state);
1670       break;
1671     case GST_RTSP_SET_PARAMETER:
1672       handle_set_param_request (client, &state);
1673       break;
1674     case GST_RTSP_GET_PARAMETER:
1675       handle_get_param_request (client, &state);
1676       break;
1677     case GST_RTSP_ANNOUNCE:
1678     case GST_RTSP_RECORD:
1679     case GST_RTSP_REDIRECT:
1680       goto not_implemented;
1681     case GST_RTSP_INVALID:
1682     default:
1683       goto bad_request;
1684   }
1685
1686 done:
1687   if (session)
1688     g_object_unref (session);
1689   if (uri)
1690     gst_rtsp_url_free (uri);
1691   return;
1692
1693   /* ERRORS */
1694 not_supported:
1695   {
1696     GST_ERROR ("client %p: version %d not supported", client, version);
1697     send_generic_response (client, GST_RTSP_STS_RTSP_VERSION_NOT_SUPPORTED,
1698         &state);
1699     goto done;
1700   }
1701 bad_request:
1702   {
1703     GST_ERROR ("client %p: bad request", client);
1704     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, &state);
1705     goto done;
1706   }
1707 no_pool:
1708   {
1709     GST_ERROR ("client %p: no pool configured", client);
1710     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, &state);
1711     goto done;
1712   }
1713 session_not_found:
1714   {
1715     GST_ERROR ("client %p: session not found", client);
1716     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, &state);
1717     goto done;
1718   }
1719 not_authorized:
1720   {
1721     GST_ERROR ("client %p: not allowed", client);
1722     handle_unauthorized_request (client, priv->auth, &state);
1723     goto done;
1724   }
1725 not_implemented:
1726   {
1727     GST_ERROR ("client %p: method %d not implemented", client, method);
1728     send_generic_response (client, GST_RTSP_STS_NOT_IMPLEMENTED, &state);
1729     goto done;
1730   }
1731 }
1732
1733 static void
1734 handle_data (GstRTSPClient * client, GstRTSPMessage * message)
1735 {
1736   GstRTSPClientPrivate *priv = client->priv;
1737   GstRTSPResult res;
1738   guint8 channel;
1739   GList *walk;
1740   guint8 *data;
1741   guint size;
1742   GstBuffer *buffer;
1743   gboolean handled;
1744
1745   /* find the stream for this message */
1746   res = gst_rtsp_message_parse_data (message, &channel);
1747   if (res != GST_RTSP_OK)
1748     return;
1749
1750   gst_rtsp_message_steal_body (message, &data, &size);
1751
1752   buffer = gst_buffer_new_wrapped (data, size);
1753
1754   handled = FALSE;
1755   for (walk = priv->transports; walk; walk = g_list_next (walk)) {
1756     GstRTSPStreamTransport *trans;
1757     GstRTSPStream *stream;
1758     const GstRTSPTransport *tr;
1759
1760     trans = walk->data;
1761
1762     tr = gst_rtsp_stream_transport_get_transport (trans);
1763     stream = gst_rtsp_stream_transport_get_stream (trans);
1764
1765     /* check for TCP transport */
1766     if (tr->lower_transport == GST_RTSP_LOWER_TRANS_TCP) {
1767       /* dispatch to the stream based on the channel number */
1768       if (tr->interleaved.min == channel) {
1769         gst_rtsp_stream_recv_rtp (stream, buffer);
1770         handled = TRUE;
1771         break;
1772       } else if (tr->interleaved.max == channel) {
1773         gst_rtsp_stream_recv_rtcp (stream, buffer);
1774         handled = TRUE;
1775         break;
1776       }
1777     }
1778   }
1779   if (!handled)
1780     gst_buffer_unref (buffer);
1781 }
1782
1783 /**
1784  * gst_rtsp_client_set_session_pool:
1785  * @client: a #GstRTSPClient
1786  * @pool: a #GstRTSPSessionPool
1787  *
1788  * Set @pool as the sessionpool for @client which it will use to find
1789  * or allocate sessions. the sessionpool is usually inherited from the server
1790  * that created the client but can be overridden later.
1791  */
1792 void
1793 gst_rtsp_client_set_session_pool (GstRTSPClient * client,
1794     GstRTSPSessionPool * pool)
1795 {
1796   GstRTSPSessionPool *old;
1797   GstRTSPClientPrivate *priv;
1798
1799   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
1800
1801   priv = client->priv;
1802
1803   if (pool)
1804     g_object_ref (pool);
1805
1806   g_mutex_lock (&priv->lock);
1807   old = priv->session_pool;
1808   priv->session_pool = pool;
1809   g_mutex_unlock (&priv->lock);
1810
1811   if (old)
1812     g_object_unref (old);
1813 }
1814
1815 /**
1816  * gst_rtsp_client_get_session_pool:
1817  * @client: a #GstRTSPClient
1818  *
1819  * Get the #GstRTSPSessionPool object that @client uses to manage its sessions.
1820  *
1821  * Returns: (transfer full): a #GstRTSPSessionPool, unref after usage.
1822  */
1823 GstRTSPSessionPool *
1824 gst_rtsp_client_get_session_pool (GstRTSPClient * client)
1825 {
1826   GstRTSPClientPrivate *priv;
1827   GstRTSPSessionPool *result;
1828
1829   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
1830
1831   priv = client->priv;
1832
1833   g_mutex_lock (&priv->lock);
1834   if ((result = priv->session_pool))
1835     g_object_ref (result);
1836   g_mutex_unlock (&priv->lock);
1837
1838   return result;
1839 }
1840
1841 /**
1842  * gst_rtsp_client_set_mount_points:
1843  * @client: a #GstRTSPClient
1844  * @mounts: a #GstRTSPMountPoints
1845  *
1846  * Set @mounts as the mount points for @client which it will use to map urls
1847  * to media streams. These mount points are usually inherited from the server that
1848  * created the client but can be overriden later.
1849  */
1850 void
1851 gst_rtsp_client_set_mount_points (GstRTSPClient * client,
1852     GstRTSPMountPoints * mounts)
1853 {
1854   GstRTSPClientPrivate *priv;
1855   GstRTSPMountPoints *old;
1856
1857   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
1858
1859   priv = client->priv;
1860
1861   if (mounts)
1862     g_object_ref (mounts);
1863
1864   g_mutex_lock (&priv->lock);
1865   old = priv->mount_points;
1866   priv->mount_points = mounts;
1867   g_mutex_unlock (&priv->lock);
1868
1869   if (old)
1870     g_object_unref (old);
1871 }
1872
1873 /**
1874  * gst_rtsp_client_get_mount_points:
1875  * @client: a #GstRTSPClient
1876  *
1877  * Get the #GstRTSPMountPoints object that @client uses to manage its sessions.
1878  *
1879  * Returns: (transfer full): a #GstRTSPMountPoints, unref after usage.
1880  */
1881 GstRTSPMountPoints *
1882 gst_rtsp_client_get_mount_points (GstRTSPClient * client)
1883 {
1884   GstRTSPClientPrivate *priv;
1885   GstRTSPMountPoints *result;
1886
1887   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
1888
1889   priv = client->priv;
1890
1891   g_mutex_lock (&priv->lock);
1892   if ((result = priv->mount_points))
1893     g_object_ref (result);
1894   g_mutex_unlock (&priv->lock);
1895
1896   return result;
1897 }
1898
1899 /**
1900  * gst_rtsp_client_set_use_client_settings:
1901  * @client: a #GstRTSPClient
1902  * @use_client_settings: whether to use client settings for multicast
1903  *
1904  * Use client transport settings (destination and ttl) for multicast.
1905  * When @use_client_settings is %FALSE, the server settings will be
1906  * used.
1907  */
1908 void
1909 gst_rtsp_client_set_use_client_settings (GstRTSPClient * client,
1910     gboolean use_client_settings)
1911 {
1912   GstRTSPClientPrivate *priv;
1913
1914   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
1915
1916   priv = client->priv;
1917
1918   g_mutex_lock (&priv->lock);
1919   priv->use_client_settings = use_client_settings;
1920   g_mutex_unlock (&priv->lock);
1921 }
1922
1923 /**
1924  * gst_rtsp_client_get_use_client_settings:
1925  * @client: a #GstRTSPClient
1926  *
1927  * Check if client transport settings (destination and ttl) for multicast
1928  * will be used.
1929  */
1930 gboolean
1931 gst_rtsp_client_get_use_client_settings (GstRTSPClient * client)
1932 {
1933   GstRTSPClientPrivate *priv;
1934   gboolean res;
1935
1936   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), FALSE);
1937
1938   priv = client->priv;
1939
1940   g_mutex_lock (&priv->lock);
1941   res = priv->use_client_settings;
1942   g_mutex_unlock (&priv->lock);
1943
1944   return res;
1945 }
1946
1947 /**
1948  * gst_rtsp_client_set_auth:
1949  * @client: a #GstRTSPClient
1950  * @auth: a #GstRTSPAuth
1951  *
1952  * configure @auth to be used as the authentication manager of @client.
1953  */
1954 void
1955 gst_rtsp_client_set_auth (GstRTSPClient * client, GstRTSPAuth * auth)
1956 {
1957   GstRTSPClientPrivate *priv;
1958   GstRTSPAuth *old;
1959
1960   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
1961
1962   priv = client->priv;
1963
1964   if (auth)
1965     g_object_ref (auth);
1966
1967   g_mutex_lock (&priv->lock);
1968   old = priv->auth;
1969   priv->auth = auth;
1970   g_mutex_unlock (&priv->lock);
1971
1972   if (old)
1973     g_object_unref (old);
1974 }
1975
1976
1977 /**
1978  * gst_rtsp_client_get_auth:
1979  * @client: a #GstRTSPClient
1980  *
1981  * Get the #GstRTSPAuth used as the authentication manager of @client.
1982  *
1983  * Returns: (transfer full): the #GstRTSPAuth of @client. g_object_unref() after
1984  * usage.
1985  */
1986 GstRTSPAuth *
1987 gst_rtsp_client_get_auth (GstRTSPClient * client)
1988 {
1989   GstRTSPClientPrivate *priv;
1990   GstRTSPAuth *result;
1991
1992   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
1993
1994   priv = client->priv;
1995
1996   g_mutex_lock (&priv->lock);
1997   if ((result = priv->auth))
1998     g_object_ref (result);
1999   g_mutex_unlock (&priv->lock);
2000
2001   return result;
2002 }
2003
2004 /**
2005  * gst_rtsp_client_set_send_func:
2006  * @client: a #GstRTSPClient
2007  * @func: a #GstRTSPClientSendFunc
2008  * @user_data: user data passed to @func
2009  * @notify: called when @user_data is no longer in use
2010  *
2011  * Set @func as the callback that will be called when a new message needs to be
2012  * sent to the client. @user_data is passed to @func and @notify is called when
2013  * @user_data is no longer in use.
2014  */
2015 void
2016 gst_rtsp_client_set_send_func (GstRTSPClient * client,
2017     GstRTSPClientSendFunc func, gpointer user_data, GDestroyNotify notify)
2018 {
2019   GstRTSPClientPrivate *priv;
2020   GDestroyNotify old_notify;
2021   gpointer old_data;
2022
2023   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2024
2025   priv = client->priv;
2026
2027   g_mutex_lock (&priv->lock);
2028   priv->send_func = func;
2029   old_notify = priv->send_notify;
2030   old_data = priv->send_data;
2031   priv->send_notify = notify;
2032   priv->send_data = user_data;
2033   g_mutex_unlock (&priv->lock);
2034
2035   if (old_notify)
2036     old_notify (old_data);
2037 }
2038
2039 /**
2040  * gst_rtsp_client_handle_message:
2041  * @client: a #GstRTSPClient
2042  * @message: an #GstRTSPMessage
2043  *
2044  * Let the client handle @message.
2045  *
2046  * Returns: a #GstRTSPResult.
2047  */
2048 GstRTSPResult
2049 gst_rtsp_client_handle_message (GstRTSPClient * client,
2050     GstRTSPMessage * message)
2051 {
2052   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), GST_RTSP_EINVAL);
2053   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2054
2055   switch (message->type) {
2056     case GST_RTSP_MESSAGE_REQUEST:
2057       handle_request (client, message);
2058       break;
2059     case GST_RTSP_MESSAGE_RESPONSE:
2060       break;
2061     case GST_RTSP_MESSAGE_DATA:
2062       handle_data (client, message);
2063       break;
2064     default:
2065       break;
2066   }
2067   return GST_RTSP_OK;
2068 }
2069
2070 static GstRTSPResult
2071 do_send_message (GstRTSPClient * client, GstRTSPMessage * message,
2072     gboolean close, gpointer user_data)
2073 {
2074   GstRTSPClientPrivate *priv = client->priv;
2075
2076   /* send the response and store the seq number so we can wait until it's
2077    * written to the client to close the connection */
2078   return gst_rtsp_watch_send_message (priv->watch, message, close ?
2079       &priv->close_seq : NULL);
2080 }
2081
2082 static GstRTSPResult
2083 message_received (GstRTSPWatch * watch, GstRTSPMessage * message,
2084     gpointer user_data)
2085 {
2086   return gst_rtsp_client_handle_message (GST_RTSP_CLIENT (user_data), message);
2087 }
2088
2089 static GstRTSPResult
2090 message_sent (GstRTSPWatch * watch, guint cseq, gpointer user_data)
2091 {
2092   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2093   GstRTSPClientPrivate *priv = client->priv;
2094
2095   if (priv->close_seq && priv->close_seq == cseq) {
2096     priv->close_seq = 0;
2097     close_connection (client);
2098   }
2099
2100   return GST_RTSP_OK;
2101 }
2102
2103 static GstRTSPResult
2104 closed (GstRTSPWatch * watch, gpointer user_data)
2105 {
2106   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2107   GstRTSPClientPrivate *priv = client->priv;
2108   const gchar *tunnelid;
2109
2110   GST_INFO ("client %p: connection closed", client);
2111
2112   if ((tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection))) {
2113     g_mutex_lock (&tunnels_lock);
2114     /* remove from tunnelids */
2115     g_hash_table_remove (tunnels, tunnelid);
2116     g_mutex_unlock (&tunnels_lock);
2117   }
2118
2119   return GST_RTSP_OK;
2120 }
2121
2122 static GstRTSPResult
2123 error (GstRTSPWatch * watch, GstRTSPResult result, gpointer user_data)
2124 {
2125   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2126   gchar *str;
2127
2128   str = gst_rtsp_strresult (result);
2129   GST_INFO ("client %p: received an error %s", client, str);
2130   g_free (str);
2131
2132   return GST_RTSP_OK;
2133 }
2134
2135 static GstRTSPResult
2136 error_full (GstRTSPWatch * watch, GstRTSPResult result,
2137     GstRTSPMessage * message, guint id, gpointer user_data)
2138 {
2139   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2140   gchar *str;
2141
2142   str = gst_rtsp_strresult (result);
2143   GST_INFO
2144       ("client %p: received an error %s when handling message %p with id %d",
2145       client, str, message, id);
2146   g_free (str);
2147
2148   return GST_RTSP_OK;
2149 }
2150
2151 static gboolean
2152 remember_tunnel (GstRTSPClient * client)
2153 {
2154   GstRTSPClientPrivate *priv = client->priv;
2155   const gchar *tunnelid;
2156
2157   /* store client in the pending tunnels */
2158   tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection);
2159   if (tunnelid == NULL)
2160     goto no_tunnelid;
2161
2162   GST_INFO ("client %p: inserting tunnel session %s", client, tunnelid);
2163
2164   /* we can't have two clients connecting with the same tunnelid */
2165   g_mutex_lock (&tunnels_lock);
2166   if (g_hash_table_lookup (tunnels, tunnelid))
2167     goto tunnel_existed;
2168
2169   g_hash_table_insert (tunnels, g_strdup (tunnelid), g_object_ref (client));
2170   g_mutex_unlock (&tunnels_lock);
2171
2172   return TRUE;
2173
2174   /* ERRORS */
2175 no_tunnelid:
2176   {
2177     GST_ERROR ("client %p: no tunnelid provided", client);
2178     return FALSE;
2179   }
2180 tunnel_existed:
2181   {
2182     g_mutex_unlock (&tunnels_lock);
2183     GST_ERROR ("client %p: tunnel session %s already existed", client,
2184         tunnelid);
2185     return FALSE;
2186   }
2187 }
2188
2189 static GstRTSPStatusCode
2190 tunnel_start (GstRTSPWatch * watch, gpointer user_data)
2191 {
2192   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2193   GstRTSPClientPrivate *priv = client->priv;
2194
2195   GST_INFO ("client %p: tunnel start (connection %p)", client,
2196       priv->connection);
2197
2198   if (!remember_tunnel (client))
2199     goto tunnel_error;
2200
2201   return GST_RTSP_STS_OK;
2202
2203   /* ERRORS */
2204 tunnel_error:
2205   {
2206     GST_ERROR ("client %p: error starting tunnel", client);
2207     return GST_RTSP_STS_SERVICE_UNAVAILABLE;
2208   }
2209 }
2210
2211 static GstRTSPResult
2212 tunnel_lost (GstRTSPWatch * watch, gpointer user_data)
2213 {
2214   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2215   GstRTSPClientPrivate *priv = client->priv;
2216
2217   GST_WARNING ("client %p: tunnel lost (connection %p)", client,
2218       priv->connection);
2219
2220   /* ignore error, it'll only be a problem when the client does a POST again */
2221   remember_tunnel (client);
2222
2223   return GST_RTSP_OK;
2224 }
2225
2226 static GstRTSPResult
2227 tunnel_complete (GstRTSPWatch * watch, gpointer user_data)
2228 {
2229   const gchar *tunnelid;
2230   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2231   GstRTSPClientPrivate *priv = client->priv;
2232   GstRTSPClient *oclient;
2233   GstRTSPClientPrivate *opriv;
2234
2235   GST_INFO ("client %p: tunnel complete", client);
2236
2237   /* find previous tunnel */
2238   tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection);
2239   if (tunnelid == NULL)
2240     goto no_tunnelid;
2241
2242   g_mutex_lock (&tunnels_lock);
2243   if (!(oclient = g_hash_table_lookup (tunnels, tunnelid)))
2244     goto no_tunnel;
2245
2246   /* remove the old client from the table. ref before because removing it will
2247    * remove the ref to it. */
2248   g_object_ref (oclient);
2249   g_hash_table_remove (tunnels, tunnelid);
2250
2251   opriv = oclient->priv;
2252
2253   if (opriv->watch == NULL)
2254     goto tunnel_closed;
2255   g_mutex_unlock (&tunnels_lock);
2256
2257   GST_INFO ("client %p: found tunnel %p (old %p, new %p)", client, oclient,
2258       opriv->connection, priv->connection);
2259
2260   /* merge the tunnels into the first client */
2261   gst_rtsp_connection_do_tunnel (opriv->connection, priv->connection);
2262   gst_rtsp_watch_reset (opriv->watch);
2263   g_object_unref (oclient);
2264
2265   return GST_RTSP_OK;
2266
2267   /* ERRORS */
2268 no_tunnelid:
2269   {
2270     GST_ERROR ("client %p: no tunnelid provided", client);
2271     return GST_RTSP_ERROR;
2272   }
2273 no_tunnel:
2274   {
2275     g_mutex_unlock (&tunnels_lock);
2276     GST_ERROR ("client %p: tunnel session %s not found", client, tunnelid);
2277     return GST_RTSP_ERROR;
2278   }
2279 tunnel_closed:
2280   {
2281     g_mutex_unlock (&tunnels_lock);
2282     GST_ERROR ("client %p: tunnel session %s was closed", client, tunnelid);
2283     g_object_unref (oclient);
2284     return GST_RTSP_ERROR;
2285   }
2286 }
2287
2288 static GstRTSPWatchFuncs watch_funcs = {
2289   message_received,
2290   message_sent,
2291   closed,
2292   error,
2293   tunnel_start,
2294   tunnel_complete,
2295   error_full,
2296   tunnel_lost
2297 };
2298
2299 static void
2300 client_watch_notify (GstRTSPClient * client)
2301 {
2302   GstRTSPClientPrivate *priv = client->priv;
2303
2304   GST_INFO ("client %p: watch destroyed", client);
2305   priv->watch = NULL;
2306   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_CLOSED], 0, NULL);
2307   g_object_unref (client);
2308 }
2309
2310 static gboolean
2311 setup_client (GstRTSPClient * client, GSocket * socket,
2312     GstRTSPConnection * conn, GError ** error)
2313 {
2314   GstRTSPClientPrivate *priv = client->priv;
2315   GSocket *read_socket;
2316   GSocketAddress *address;
2317   GstRTSPUrl *url;
2318
2319   read_socket = gst_rtsp_connection_get_read_socket (conn);
2320   priv->is_ipv6 = g_socket_get_family (socket) == G_SOCKET_FAMILY_IPV6;
2321
2322   if (!(address = g_socket_get_remote_address (read_socket, error)))
2323     goto no_address;
2324
2325   g_free (priv->server_ip);
2326   /* keep the original ip that the client connected to */
2327   if (G_IS_INET_SOCKET_ADDRESS (address)) {
2328     GInetAddress *iaddr;
2329
2330     iaddr = g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (address));
2331
2332     priv->server_ip = g_inet_address_to_string (iaddr);
2333     g_object_unref (address);
2334   } else {
2335     priv->server_ip = g_strdup ("unknown");
2336   }
2337
2338   GST_INFO ("client %p connected to server ip %s, ipv6 = %d", client,
2339       priv->server_ip, priv->is_ipv6);
2340
2341   url = gst_rtsp_connection_get_url (conn);
2342   GST_INFO ("added new client %p ip %s:%d", client, url->host, url->port);
2343
2344   priv->connection = conn;
2345
2346   return TRUE;
2347
2348   /* ERRORS */
2349 no_address:
2350   {
2351     GST_ERROR ("could not get remote address %s", (*error)->message);
2352     return FALSE;
2353   }
2354 }
2355
2356 /**
2357  * gst_rtsp_client_use_socket:
2358  * @client: a #GstRTSPClient
2359  * @socket: a #GSocket
2360  * @ip: the IP address of the remote client
2361  * @port: the port used by the other end
2362  * @initial_buffer: any zero terminated initial data that was already read from
2363  *     the socket
2364  * @error: a #GError
2365  *
2366  * Take an existing network socket and use it for an RTSP connection.
2367  *
2368  * Returns: %TRUE on success.
2369  */
2370 gboolean
2371 gst_rtsp_client_use_socket (GstRTSPClient * client, GSocket * socket,
2372     const gchar * ip, gint port, const gchar * initial_buffer, GError ** error)
2373 {
2374   GstRTSPConnection *conn;
2375   GstRTSPResult res;
2376
2377   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), FALSE);
2378   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2379
2380   GST_RTSP_CHECK (gst_rtsp_connection_create_from_socket (socket, ip, port,
2381           initial_buffer, &conn), no_connection);
2382
2383   return setup_client (client, socket, conn, error);
2384
2385   /* ERRORS */
2386 no_connection:
2387   {
2388     gchar *str = gst_rtsp_strresult (res);
2389
2390     GST_ERROR ("could not create connection from socket %p: %s", socket, str);
2391     g_free (str);
2392     return FALSE;
2393   }
2394 }
2395
2396 /**
2397  * gst_rtsp_client_accept:
2398  * @client: a #GstRTSPClient
2399  * @socket: a #GSocket
2400  * @context: the context to run in
2401  * @cancellable: a #GCancellable
2402  * @error: a #GError
2403  *
2404  * Accept a new connection for @client on @socket.
2405  *
2406  * Returns: %TRUE if the client could be accepted.
2407  */
2408 gboolean
2409 gst_rtsp_client_accept (GstRTSPClient * client, GSocket * socket,
2410     GCancellable * cancellable, GError ** error)
2411 {
2412   GstRTSPConnection *conn;
2413   GstRTSPResult res;
2414
2415   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), FALSE);
2416   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2417
2418   /* a new client connected. */
2419   GST_RTSP_CHECK (gst_rtsp_connection_accept (socket, &conn, cancellable),
2420       accept_failed);
2421
2422   return setup_client (client, socket, conn, error);
2423
2424   /* ERRORS */
2425 accept_failed:
2426   {
2427     gchar *str = gst_rtsp_strresult (res);
2428
2429     GST_ERROR ("Could not accept client on server socket %p: %s", socket, str);
2430     g_free (str);
2431     return FALSE;
2432   }
2433 }
2434
2435 /**
2436  * gst_rtsp_client_attach:
2437  * @client: a #GstRTSPClient
2438  * @context: (allow-none): a #GMainContext
2439  *
2440  * Attaches @client to @context. When the mainloop for @context is run, the
2441  * client will be dispatched. When @context is NULL, the default context will be
2442  * used).
2443  *
2444  * This function should be called when the client properties and urls are fully
2445  * configured and the client is ready to start.
2446  *
2447  * Returns: the ID (greater than 0) for the source within the GMainContext.
2448  */
2449 guint
2450 gst_rtsp_client_attach (GstRTSPClient * client, GMainContext * context)
2451 {
2452   GstRTSPClientPrivate *priv;
2453   guint res;
2454
2455   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), 0);
2456   priv = client->priv;
2457   g_return_val_if_fail (priv->watch == NULL, 0);
2458
2459   /* create watch for the connection and attach */
2460   priv->watch = gst_rtsp_watch_new (priv->connection, &watch_funcs,
2461       g_object_ref (client), (GDestroyNotify) client_watch_notify);
2462   gst_rtsp_client_set_send_func (client, do_send_message, NULL, NULL);
2463
2464   GST_INFO ("attaching to context %p", context);
2465   res = gst_rtsp_watch_attach (priv->watch, context);
2466   gst_rtsp_watch_unref (priv->watch);
2467
2468   return res;
2469 }