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