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