rtsp-client: expose uri
[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   /* unlink the all TCP callbacks */
666   unlink_session_transports (client, session, media);
667
668   /* remove the session from the watched sessions */
669   g_object_weak_unref (G_OBJECT (session),
670       (GWeakNotify) client_session_finalized, client);
671   priv->sessions = g_list_remove (priv->sessions, session);
672
673   gst_rtsp_session_media_set_state (media, GST_STATE_NULL);
674
675   /* unmanage the media in the session, returns false if all media session
676    * are torn down. */
677   if (!gst_rtsp_session_release_media (session, media)) {
678     /* remove the session */
679     gst_rtsp_session_pool_remove (priv->session_pool, session);
680   }
681   /* construct the response now */
682   code = GST_RTSP_STS_OK;
683   gst_rtsp_message_init_response (state->response, code,
684       gst_rtsp_status_as_text (code), state->request);
685
686   send_response (client, session, state->response, TRUE);
687
688   /* we emit the signal before closing the connection */
689   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_TEARDOWN_REQUEST],
690       0, state);
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
863   if (!(session = state->session))
864     goto no_session;
865
866   /* get a handle to the configuration of the media in the session */
867   media = gst_rtsp_session_get_media (session, state->uri);
868   if (!media)
869     goto not_found;
870
871   state->sessmedia = media;
872
873   /* the session state must be playing or ready */
874   rtspstate = gst_rtsp_session_media_get_rtsp_state (media);
875   if (rtspstate != GST_RTSP_STATE_PLAYING && rtspstate != GST_RTSP_STATE_READY)
876     goto invalid_state;
877
878   /* parse the range header if we have one */
879   res =
880       gst_rtsp_message_get_header (state->request, GST_RTSP_HDR_RANGE, &str, 0);
881   if (res == GST_RTSP_OK) {
882     if (gst_rtsp_range_parse (str, &range) == GST_RTSP_OK) {
883       /* we have a range, seek to the position */
884       gst_rtsp_media_seek (gst_rtsp_session_media_get_media (media), range);
885       gst_rtsp_range_free (range);
886     }
887   }
888
889   /* grab RTPInfo from the payloaders now */
890   rtpinfo = g_string_new ("");
891
892   n_streams =
893       gst_rtsp_media_n_streams (gst_rtsp_session_media_get_media (media));
894   for (i = 0, infocount = 0; i < n_streams; i++) {
895     GstRTSPStreamTransport *trans;
896     GstRTSPStream *stream;
897     const GstRTSPTransport *tr;
898     gchar *uristr;
899     guint rtptime, seq;
900
901     /* get the transport, if there is no transport configured, skip this stream */
902     trans = gst_rtsp_session_media_get_transport (media, i);
903     if (trans == NULL) {
904       GST_INFO ("stream %d is not configured", i);
905       continue;
906     }
907     tr = gst_rtsp_stream_transport_get_transport (trans);
908
909     if (tr->lower_transport == GST_RTSP_LOWER_TRANS_TCP) {
910       /* for TCP, link the stream to the TCP connection of the client */
911       link_transport (client, session, trans);
912     }
913
914     stream = gst_rtsp_stream_transport_get_stream (trans);
915     if (gst_rtsp_stream_get_rtpinfo (stream, &rtptime, &seq)) {
916       if (infocount > 0)
917         g_string_append (rtpinfo, ", ");
918
919       uristr = gst_rtsp_url_get_request_uri (state->uri);
920       g_string_append_printf (rtpinfo, "url=%s/stream=%d;seq=%u;rtptime=%u",
921           uristr, i, seq, rtptime);
922       g_free (uristr);
923
924       infocount++;
925     } else {
926       GST_WARNING ("RTP-Info cannot be determined for stream %d", i);
927     }
928   }
929
930   /* construct the response now */
931   code = GST_RTSP_STS_OK;
932   gst_rtsp_message_init_response (state->response, code,
933       gst_rtsp_status_as_text (code), state->request);
934
935   /* add the RTP-Info header */
936   if (infocount > 0) {
937     str = g_string_free (rtpinfo, FALSE);
938     gst_rtsp_message_take_header (state->response, GST_RTSP_HDR_RTP_INFO, str);
939   } else {
940     g_string_free (rtpinfo, TRUE);
941   }
942
943   /* add the range */
944   str =
945       gst_rtsp_media_get_range_string (gst_rtsp_session_media_get_media (media),
946       TRUE);
947   gst_rtsp_message_take_header (state->response, GST_RTSP_HDR_RANGE, str);
948
949   send_response (client, session, state->response, FALSE);
950
951   /* start playing after sending the request */
952   gst_rtsp_session_media_set_state (media, GST_STATE_PLAYING);
953
954   gst_rtsp_session_media_set_rtsp_state (media, GST_RTSP_STATE_PLAYING);
955
956   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_PLAY_REQUEST],
957       0, state);
958
959   return TRUE;
960
961   /* ERRORS */
962 no_session:
963   {
964     GST_ERROR ("client %p: no session", client);
965     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, state);
966     return FALSE;
967   }
968 not_found:
969   {
970     GST_ERROR ("client %p: media not found", client);
971     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, state);
972     return FALSE;
973   }
974 invalid_state:
975   {
976     GST_ERROR ("client %p: not PLAYING or READY", client);
977     send_generic_response (client, GST_RTSP_STS_METHOD_NOT_VALID_IN_THIS_STATE,
978         state);
979     return FALSE;
980   }
981 }
982
983 static void
984 do_keepalive (GstRTSPSession * session)
985 {
986   GST_INFO ("keep session %p alive", session);
987   gst_rtsp_session_touch (session);
988 }
989
990 /* parse @transport and return a valid transport in @tr. only transports
991  * from @supported are returned. Returns FALSE if no valid transport
992  * was found. */
993 static gboolean
994 parse_transport (const char *transport, GstRTSPLowerTrans supported,
995     GstRTSPTransport * tr)
996 {
997   gint i;
998   gboolean res;
999   gchar **transports;
1000
1001   res = FALSE;
1002   gst_rtsp_transport_init (tr);
1003
1004   GST_DEBUG ("parsing transports %s", transport);
1005
1006   transports = g_strsplit (transport, ",", 0);
1007
1008   /* loop through the transports, try to parse */
1009   for (i = 0; transports[i]; i++) {
1010     res = gst_rtsp_transport_parse (transports[i], tr);
1011     if (res != GST_RTSP_OK) {
1012       /* no valid transport, search some more */
1013       GST_WARNING ("could not parse transport %s", transports[i]);
1014       goto next;
1015     }
1016
1017     /* we have a transport, see if it's RTP/AVP */
1018     if (tr->trans != GST_RTSP_TRANS_RTP || tr->profile != GST_RTSP_PROFILE_AVP) {
1019       GST_WARNING ("invalid transport %s", transports[i]);
1020       goto next;
1021     }
1022
1023     if (!(tr->lower_transport & supported)) {
1024       GST_WARNING ("unsupported transport %s", transports[i]);
1025       goto next;
1026     }
1027
1028     /* we have a valid transport */
1029     GST_INFO ("found valid transport %s", transports[i]);
1030     res = TRUE;
1031     break;
1032
1033   next:
1034     gst_rtsp_transport_init (tr);
1035   }
1036   g_strfreev (transports);
1037
1038   return res;
1039 }
1040
1041 static gboolean
1042 handle_blocksize (GstRTSPMedia * media, GstRTSPStream * stream,
1043     GstRTSPMessage * request)
1044 {
1045   gchar *blocksize_str;
1046   gboolean ret = TRUE;
1047
1048   if (gst_rtsp_message_get_header (request, GST_RTSP_HDR_BLOCKSIZE,
1049           &blocksize_str, 0) == GST_RTSP_OK) {
1050     guint64 blocksize;
1051     gchar *end;
1052
1053     blocksize = g_ascii_strtoull (blocksize_str, &end, 10);
1054     if (end == blocksize_str) {
1055       GST_ERROR ("failed to parse blocksize");
1056       ret = FALSE;
1057     } else {
1058       /* we don't want to change the mtu when this media
1059        * can be shared because it impacts other clients */
1060       if (gst_rtsp_media_is_shared (media))
1061         return TRUE;
1062
1063       if (blocksize > G_MAXUINT)
1064         blocksize = G_MAXUINT;
1065       gst_rtsp_stream_set_mtu (stream, blocksize);
1066     }
1067   }
1068   return ret;
1069 }
1070
1071 static gboolean
1072 configure_client_transport (GstRTSPClient * client, GstRTSPClientState * state,
1073     GstRTSPTransport * ct)
1074 {
1075   GstRTSPClientPrivate *priv = client->priv;
1076
1077   /* we have a valid transport now, set the destination of the client. */
1078   if (ct->lower_transport == GST_RTSP_LOWER_TRANS_UDP_MCAST) {
1079     if (ct->destination && priv->use_client_settings) {
1080       GstRTSPAddress *addr;
1081
1082       addr = gst_rtsp_stream_reserve_address (state->stream, ct->destination,
1083           ct->port.min, ct->port.max - ct->port.min + 1, ct->ttl);
1084
1085       if (addr == NULL)
1086         goto no_address;
1087
1088       gst_rtsp_address_free (addr);
1089     } else {
1090       GstRTSPAddress *addr;
1091
1092       addr = gst_rtsp_stream_get_address (state->stream);
1093       if (addr == NULL)
1094         goto no_address;
1095
1096       g_free (ct->destination);
1097       ct->destination = g_strdup (addr->address);
1098       ct->port.min = addr->port;
1099       ct->port.max = addr->port + addr->n_ports - 1;
1100       ct->ttl = addr->ttl;
1101
1102       gst_rtsp_address_free (addr);
1103     }
1104   } else {
1105     GstRTSPUrl *url;
1106
1107     url = gst_rtsp_connection_get_url (priv->connection);
1108     g_free (ct->destination);
1109     ct->destination = g_strdup (url->host);
1110
1111     if (ct->lower_transport & GST_RTSP_LOWER_TRANS_TCP) {
1112       /* check if the client selected channels for TCP */
1113       if (ct->interleaved.min == -1 || ct->interleaved.max == -1) {
1114         gst_rtsp_session_media_alloc_channels (state->sessmedia,
1115             &ct->interleaved);
1116       }
1117     }
1118   }
1119   return TRUE;
1120
1121   /* ERRORS */
1122 no_address:
1123   {
1124     GST_ERROR_OBJECT (client, "failed to acquire address for stream");
1125     return FALSE;
1126   }
1127 }
1128
1129 static GstRTSPTransport *
1130 make_server_transport (GstRTSPClient * client, GstRTSPClientState * state,
1131     GstRTSPTransport * ct)
1132 {
1133   GstRTSPTransport *st;
1134
1135   /* prepare the server transport */
1136   gst_rtsp_transport_new (&st);
1137
1138   st->trans = ct->trans;
1139   st->profile = ct->profile;
1140   st->lower_transport = ct->lower_transport;
1141
1142   switch (st->lower_transport) {
1143     case GST_RTSP_LOWER_TRANS_UDP:
1144       st->client_port = ct->client_port;
1145       gst_rtsp_stream_get_server_port (state->stream, &st->server_port);
1146       break;
1147     case GST_RTSP_LOWER_TRANS_UDP_MCAST:
1148       st->port = ct->port;
1149       st->destination = g_strdup (ct->destination);
1150       st->ttl = ct->ttl;
1151       break;
1152     case GST_RTSP_LOWER_TRANS_TCP:
1153       st->interleaved = ct->interleaved;
1154     default:
1155       break;
1156   }
1157
1158   gst_rtsp_stream_get_ssrc (state->stream, &st->ssrc);
1159
1160   return st;
1161 }
1162
1163 static gboolean
1164 handle_setup_request (GstRTSPClient * client, GstRTSPClientState * state)
1165 {
1166   GstRTSPClientPrivate *priv = client->priv;
1167   GstRTSPResult res;
1168   GstRTSPUrl *uri;
1169   gchar *transport;
1170   GstRTSPTransport *ct, *st;
1171   GstRTSPLowerTrans supported;
1172   GstRTSPStatusCode code;
1173   GstRTSPSession *session;
1174   GstRTSPStreamTransport *trans;
1175   gchar *trans_str, *pos;
1176   guint streamid;
1177   GstRTSPSessionMedia *sessmedia;
1178   GstRTSPMedia *media;
1179   GstRTSPStream *stream;
1180   GstRTSPState rtspstate;
1181
1182   uri = state->uri;
1183
1184   /* the uri contains the stream number we added in the SDP config, which is
1185    * always /stream=%d so we need to strip that off
1186    * parse the stream we need to configure, look for the stream in the abspath
1187    * first and then in the query. */
1188   if (uri->abspath == NULL || !(pos = strstr (uri->abspath, "/stream="))) {
1189     if (uri->query == NULL || !(pos = strstr (uri->query, "/stream=")))
1190       goto bad_request;
1191   }
1192
1193   /* we can mofify the parsed uri in place */
1194   *pos = '\0';
1195
1196   pos += strlen ("/stream=");
1197   if (sscanf (pos, "%u", &streamid) != 1)
1198     goto bad_request;
1199
1200   /* parse the transport */
1201   res =
1202       gst_rtsp_message_get_header (state->request, GST_RTSP_HDR_TRANSPORT,
1203       &transport, 0);
1204   if (res != GST_RTSP_OK)
1205     goto no_transport;
1206
1207   gst_rtsp_transport_new (&ct);
1208
1209   /* our supported transports */
1210   supported = GST_RTSP_LOWER_TRANS_UDP |
1211       GST_RTSP_LOWER_TRANS_UDP_MCAST | GST_RTSP_LOWER_TRANS_TCP;
1212
1213   /* parse and find a usable supported transport */
1214   if (!parse_transport (transport, supported, ct))
1215     goto unsupported_transports;
1216
1217   /* we create the session after parsing stuff so that we don't make
1218    * a session for malformed requests */
1219   if (priv->session_pool == NULL)
1220     goto no_pool;
1221
1222   session = state->session;
1223
1224   if (session) {
1225     g_object_ref (session);
1226     /* get a handle to the configuration of the media in the session, this can
1227      * return NULL if this is a new url to manage in this session. */
1228     sessmedia = gst_rtsp_session_get_media (session, uri);
1229   } else {
1230     /* create a session if this fails we probably reached our session limit or
1231      * something. */
1232     if (!(session = gst_rtsp_session_pool_create (priv->session_pool)))
1233       goto service_unavailable;
1234
1235     state->session = session;
1236
1237     /* we need a new media configuration in this session */
1238     sessmedia = NULL;
1239   }
1240
1241   /* we have no media, find one and manage it */
1242   if (sessmedia == NULL) {
1243     /* get a handle to the configuration of the media in the session */
1244     if ((media = find_media (client, state))) {
1245       /* manage the media in our session now */
1246       sessmedia = gst_rtsp_session_manage_media (session, uri, media);
1247     }
1248   }
1249
1250   /* if we stil have no media, error */
1251   if (sessmedia == NULL)
1252     goto not_found;
1253
1254   state->sessmedia = sessmedia;
1255   state->media = media = gst_rtsp_session_media_get_media (sessmedia);
1256
1257   /* now get the stream */
1258   stream = gst_rtsp_media_get_stream (media, streamid);
1259   if (stream == NULL)
1260     goto not_found;
1261
1262   state->stream = stream;
1263
1264   /* set blocksize on this stream */
1265   if (!handle_blocksize (media, stream, state->request))
1266     goto invalid_blocksize;
1267
1268   /* update the client transport */
1269   if (!configure_client_transport (client, state, ct))
1270     goto unsupported_client_transport;
1271
1272   /* set in the session media transport */
1273   trans = gst_rtsp_session_media_set_transport (sessmedia, stream, ct);
1274
1275   /* configure keepalive for this transport */
1276   gst_rtsp_stream_transport_set_keepalive (trans,
1277       (GstRTSPKeepAliveFunc) do_keepalive, session, NULL);
1278
1279   /* create and serialize the server transport */
1280   st = make_server_transport (client, state, ct);
1281   trans_str = gst_rtsp_transport_as_text (st);
1282   gst_rtsp_transport_free (st);
1283
1284   /* construct the response now */
1285   code = GST_RTSP_STS_OK;
1286   gst_rtsp_message_init_response (state->response, code,
1287       gst_rtsp_status_as_text (code), state->request);
1288
1289   gst_rtsp_message_add_header (state->response, GST_RTSP_HDR_TRANSPORT,
1290       trans_str);
1291   g_free (trans_str);
1292
1293   send_response (client, session, state->response, FALSE);
1294
1295   /* update the state */
1296   rtspstate = gst_rtsp_session_media_get_rtsp_state (sessmedia);
1297   switch (rtspstate) {
1298     case GST_RTSP_STATE_PLAYING:
1299     case GST_RTSP_STATE_RECORDING:
1300     case GST_RTSP_STATE_READY:
1301       /* no state change */
1302       break;
1303     default:
1304       gst_rtsp_session_media_set_rtsp_state (sessmedia, GST_RTSP_STATE_READY);
1305       break;
1306   }
1307   g_object_unref (session);
1308
1309   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_SETUP_REQUEST],
1310       0, state);
1311
1312   return TRUE;
1313
1314   /* ERRORS */
1315 bad_request:
1316   {
1317     GST_ERROR ("client %p: bad request", client);
1318     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, state);
1319     return FALSE;
1320   }
1321 not_found:
1322   {
1323     GST_ERROR ("client %p: media not found", client);
1324     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, state);
1325     g_object_unref (session);
1326     gst_rtsp_transport_free (ct);
1327     return FALSE;
1328   }
1329 invalid_blocksize:
1330   {
1331     GST_ERROR ("client %p: invalid blocksize", client);
1332     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, state);
1333     g_object_unref (session);
1334     gst_rtsp_transport_free (ct);
1335     return FALSE;
1336   }
1337 unsupported_client_transport:
1338   {
1339     GST_ERROR ("client %p: unsupported client transport", client);
1340     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, state);
1341     g_object_unref (session);
1342     gst_rtsp_transport_free (ct);
1343     return FALSE;
1344   }
1345 no_transport:
1346   {
1347     GST_ERROR ("client %p: no transport", client);
1348     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, state);
1349     return FALSE;
1350   }
1351 unsupported_transports:
1352   {
1353     GST_ERROR ("client %p: unsupported transports", client);
1354     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, state);
1355     gst_rtsp_transport_free (ct);
1356     return FALSE;
1357   }
1358 no_pool:
1359   {
1360     GST_ERROR ("client %p: no session pool configured", client);
1361     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, state);
1362     gst_rtsp_transport_free (ct);
1363     return FALSE;
1364   }
1365 service_unavailable:
1366   {
1367     GST_ERROR ("client %p: can't create session", client);
1368     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, state);
1369     gst_rtsp_transport_free (ct);
1370     return FALSE;
1371   }
1372 }
1373
1374 static GstSDPMessage *
1375 create_sdp (GstRTSPClient * client, GstRTSPMedia * media)
1376 {
1377   GstRTSPClientPrivate *priv = client->priv;
1378   GstSDPMessage *sdp;
1379   GstSDPInfo info;
1380   const gchar *proto;
1381
1382   gst_sdp_message_new (&sdp);
1383
1384   /* some standard things first */
1385   gst_sdp_message_set_version (sdp, "0");
1386
1387   if (priv->is_ipv6)
1388     proto = "IP6";
1389   else
1390     proto = "IP4";
1391
1392   gst_sdp_message_set_origin (sdp, "-", "1188340656180883", "1", "IN", proto,
1393       priv->server_ip);
1394
1395   gst_sdp_message_set_session_name (sdp, "Session streamed with GStreamer");
1396   gst_sdp_message_set_information (sdp, "rtsp-server");
1397   gst_sdp_message_add_time (sdp, "0", "0", NULL);
1398   gst_sdp_message_add_attribute (sdp, "tool", "GStreamer");
1399   gst_sdp_message_add_attribute (sdp, "type", "broadcast");
1400   gst_sdp_message_add_attribute (sdp, "control", "*");
1401
1402   info.server_proto = proto;
1403   info.server_ip = g_strdup (priv->server_ip);
1404
1405   /* create an SDP for the media object */
1406   if (!gst_rtsp_sdp_from_media (sdp, &info, media))
1407     goto no_sdp;
1408
1409   g_free (info.server_ip);
1410
1411   return sdp;
1412
1413   /* ERRORS */
1414 no_sdp:
1415   {
1416     GST_ERROR ("client %p: could not create SDP", client);
1417     g_free (info.server_ip);
1418     gst_sdp_message_free (sdp);
1419     return NULL;
1420   }
1421 }
1422
1423 /* for the describe we must generate an SDP */
1424 static gboolean
1425 handle_describe_request (GstRTSPClient * client, GstRTSPClientState * state)
1426 {
1427   GstRTSPResult res;
1428   GstSDPMessage *sdp;
1429   guint i, str_len;
1430   gchar *str, *content_base;
1431   GstRTSPMedia *media;
1432   GstRTSPClientClass *klass;
1433
1434   klass = GST_RTSP_CLIENT_GET_CLASS (client);
1435
1436   /* check what kind of format is accepted, we don't really do anything with it
1437    * and always return SDP for now. */
1438   for (i = 0; i++;) {
1439     gchar *accept;
1440
1441     res =
1442         gst_rtsp_message_get_header (state->request, GST_RTSP_HDR_ACCEPT,
1443         &accept, i);
1444     if (res == GST_RTSP_ENOTIMPL)
1445       break;
1446
1447     if (g_ascii_strcasecmp (accept, "application/sdp") == 0)
1448       break;
1449   }
1450
1451   /* find the media object for the uri */
1452   if (!(media = find_media (client, state)))
1453     goto no_media;
1454
1455   /* create an SDP for the media object on this client */
1456   if (!(sdp = klass->create_sdp (client, media)))
1457     goto no_sdp;
1458
1459   g_object_unref (media);
1460
1461   gst_rtsp_message_init_response (state->response, GST_RTSP_STS_OK,
1462       gst_rtsp_status_as_text (GST_RTSP_STS_OK), state->request);
1463
1464   gst_rtsp_message_add_header (state->response, GST_RTSP_HDR_CONTENT_TYPE,
1465       "application/sdp");
1466
1467   /* content base for some clients that might screw up creating the setup uri */
1468   str = gst_rtsp_url_get_request_uri (state->uri);
1469   str_len = strlen (str);
1470
1471   /* check for trailing '/' and append one */
1472   if (str[str_len - 1] != '/') {
1473     content_base = g_malloc (str_len + 2);
1474     memcpy (content_base, str, str_len);
1475     content_base[str_len] = '/';
1476     content_base[str_len + 1] = '\0';
1477     g_free (str);
1478   } else {
1479     content_base = str;
1480   }
1481
1482   GST_INFO ("adding content-base: %s", content_base);
1483
1484   gst_rtsp_message_add_header (state->response, GST_RTSP_HDR_CONTENT_BASE,
1485       content_base);
1486   g_free (content_base);
1487
1488   /* add SDP to the response body */
1489   str = gst_sdp_message_as_text (sdp);
1490   gst_rtsp_message_take_body (state->response, (guint8 *) str, strlen (str));
1491   gst_sdp_message_free (sdp);
1492
1493   send_response (client, state->session, state->response, FALSE);
1494
1495   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_DESCRIBE_REQUEST],
1496       0, state);
1497
1498   return TRUE;
1499
1500   /* ERRORS */
1501 no_media:
1502   {
1503     GST_ERROR ("client %p: no media", client);
1504     /* error reply is already sent */
1505     return FALSE;
1506   }
1507 no_sdp:
1508   {
1509     GST_ERROR ("client %p: can't create SDP", client);
1510     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, state);
1511     g_object_unref (media);
1512     return FALSE;
1513   }
1514 }
1515
1516 static gboolean
1517 handle_options_request (GstRTSPClient * client, GstRTSPClientState * state)
1518 {
1519   GstRTSPMethod options;
1520   gchar *str;
1521
1522   options = GST_RTSP_DESCRIBE |
1523       GST_RTSP_OPTIONS |
1524       GST_RTSP_PAUSE |
1525       GST_RTSP_PLAY |
1526       GST_RTSP_SETUP |
1527       GST_RTSP_GET_PARAMETER | GST_RTSP_SET_PARAMETER | GST_RTSP_TEARDOWN;
1528
1529   str = gst_rtsp_options_as_text (options);
1530
1531   gst_rtsp_message_init_response (state->response, GST_RTSP_STS_OK,
1532       gst_rtsp_status_as_text (GST_RTSP_STS_OK), state->request);
1533
1534   gst_rtsp_message_add_header (state->response, GST_RTSP_HDR_PUBLIC, str);
1535   g_free (str);
1536
1537   send_response (client, state->session, state->response, FALSE);
1538
1539   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_OPTIONS_REQUEST],
1540       0, state);
1541
1542   return TRUE;
1543 }
1544
1545 /* remove duplicate and trailing '/' */
1546 static void
1547 sanitize_uri (GstRTSPUrl * uri)
1548 {
1549   gint i, len;
1550   gchar *s, *d;
1551   gboolean have_slash, prev_slash;
1552
1553   s = d = uri->abspath;
1554   len = strlen (uri->abspath);
1555
1556   prev_slash = FALSE;
1557
1558   for (i = 0; i < len; i++) {
1559     have_slash = s[i] == '/';
1560     *d = s[i];
1561     if (!have_slash || !prev_slash)
1562       d++;
1563     prev_slash = have_slash;
1564   }
1565   len = d - uri->abspath;
1566   /* don't remove the first slash if that's the only thing left */
1567   if (len > 1 && *(d - 1) == '/')
1568     d--;
1569   *d = '\0';
1570 }
1571
1572 static void
1573 client_session_finalized (GstRTSPClient * client, GstRTSPSession * session)
1574 {
1575   GstRTSPClientPrivate *priv = client->priv;
1576
1577   GST_INFO ("client %p: session %p finished", client, session);
1578
1579   /* unlink all media managed in this session */
1580   client_unlink_session (client, session);
1581
1582   /* remove the session */
1583   if (!(priv->sessions = g_list_remove (priv->sessions, session))) {
1584     GST_INFO ("client %p: all sessions finalized, close the connection",
1585         client);
1586     close_connection (client);
1587   }
1588 }
1589
1590 static void
1591 client_watch_session (GstRTSPClient * client, GstRTSPSession * session)
1592 {
1593   GstRTSPClientPrivate *priv = client->priv;
1594   GList *walk;
1595
1596   for (walk = priv->sessions; walk; walk = g_list_next (walk)) {
1597     GstRTSPSession *msession = (GstRTSPSession *) walk->data;
1598
1599     /* we already know about this session */
1600     if (msession == session)
1601       return;
1602   }
1603
1604   GST_INFO ("watching session %p", session);
1605
1606   g_object_weak_ref (G_OBJECT (session), (GWeakNotify) client_session_finalized,
1607       client);
1608   priv->sessions = g_list_prepend (priv->sessions, session);
1609
1610   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_NEW_SESSION], 0,
1611       session);
1612 }
1613
1614 static void
1615 handle_request (GstRTSPClient * client, GstRTSPMessage * request)
1616 {
1617   GstRTSPClientPrivate *priv = client->priv;
1618   GstRTSPMethod method;
1619   const gchar *uristr;
1620   GstRTSPUrl *uri = NULL;
1621   GstRTSPVersion version;
1622   GstRTSPResult res;
1623   GstRTSPSession *session = NULL;
1624   GstRTSPClientState state = { NULL };
1625   GstRTSPMessage response = { 0 };
1626   gchar *sessid;
1627
1628   state.request = request;
1629   state.response = &response;
1630
1631   if (gst_debug_category_get_threshold (rtsp_client_debug) >= GST_LEVEL_LOG) {
1632     gst_rtsp_message_dump (request);
1633   }
1634
1635   GST_INFO ("client %p: received a request", client);
1636
1637   gst_rtsp_message_parse_request (request, &method, &uristr, &version);
1638
1639   /* we can only handle 1.0 requests */
1640   if (version != GST_RTSP_VERSION_1_0)
1641     goto not_supported;
1642
1643   state.method = method;
1644
1645   /* we always try to parse the url first */
1646   if (gst_rtsp_url_parse (uristr, &uri) != GST_RTSP_OK)
1647     goto bad_request;
1648
1649   /* get the session if there is any */
1650   res = gst_rtsp_message_get_header (request, GST_RTSP_HDR_SESSION, &sessid, 0);
1651   if (res == GST_RTSP_OK) {
1652     if (priv->session_pool == NULL)
1653       goto no_pool;
1654
1655     /* we had a session in the request, find it again */
1656     if (!(session = gst_rtsp_session_pool_find (priv->session_pool, sessid)))
1657       goto session_not_found;
1658
1659     /* we add the session to the client list of watched sessions. When a session
1660      * disappears because it times out, we will be notified. If all sessions are
1661      * gone, we will close the connection */
1662     client_watch_session (client, session);
1663   }
1664
1665   /* sanitize the uri */
1666   sanitize_uri (uri);
1667   state.uri = uri;
1668   state.session = session;
1669
1670   if (priv->auth) {
1671     if (!gst_rtsp_auth_check (priv->auth, client, 0, &state))
1672       goto not_authorized;
1673   }
1674
1675   /* now see what is asked and dispatch to a dedicated handler */
1676   switch (method) {
1677     case GST_RTSP_OPTIONS:
1678       handle_options_request (client, &state);
1679       break;
1680     case GST_RTSP_DESCRIBE:
1681       handle_describe_request (client, &state);
1682       break;
1683     case GST_RTSP_SETUP:
1684       handle_setup_request (client, &state);
1685       break;
1686     case GST_RTSP_PLAY:
1687       handle_play_request (client, &state);
1688       break;
1689     case GST_RTSP_PAUSE:
1690       handle_pause_request (client, &state);
1691       break;
1692     case GST_RTSP_TEARDOWN:
1693       handle_teardown_request (client, &state);
1694       break;
1695     case GST_RTSP_SET_PARAMETER:
1696       handle_set_param_request (client, &state);
1697       break;
1698     case GST_RTSP_GET_PARAMETER:
1699       handle_get_param_request (client, &state);
1700       break;
1701     case GST_RTSP_ANNOUNCE:
1702     case GST_RTSP_RECORD:
1703     case GST_RTSP_REDIRECT:
1704       goto not_implemented;
1705     case GST_RTSP_INVALID:
1706     default:
1707       goto bad_request;
1708   }
1709
1710 done:
1711   if (session)
1712     g_object_unref (session);
1713   if (uri)
1714     gst_rtsp_url_free (uri);
1715   return;
1716
1717   /* ERRORS */
1718 not_supported:
1719   {
1720     GST_ERROR ("client %p: version %d not supported", client, version);
1721     send_generic_response (client, GST_RTSP_STS_RTSP_VERSION_NOT_SUPPORTED,
1722         &state);
1723     goto done;
1724   }
1725 bad_request:
1726   {
1727     GST_ERROR ("client %p: bad request", client);
1728     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, &state);
1729     goto done;
1730   }
1731 no_pool:
1732   {
1733     GST_ERROR ("client %p: no pool configured", client);
1734     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, &state);
1735     goto done;
1736   }
1737 session_not_found:
1738   {
1739     GST_ERROR ("client %p: session not found", client);
1740     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, &state);
1741     goto done;
1742   }
1743 not_authorized:
1744   {
1745     GST_ERROR ("client %p: not allowed", client);
1746     handle_unauthorized_request (client, priv->auth, &state);
1747     goto done;
1748   }
1749 not_implemented:
1750   {
1751     GST_ERROR ("client %p: method %d not implemented", client, method);
1752     send_generic_response (client, GST_RTSP_STS_NOT_IMPLEMENTED, &state);
1753     goto done;
1754   }
1755 }
1756
1757 static void
1758 handle_data (GstRTSPClient * client, GstRTSPMessage * message)
1759 {
1760   GstRTSPClientPrivate *priv = client->priv;
1761   GstRTSPResult res;
1762   guint8 channel;
1763   GList *walk;
1764   guint8 *data;
1765   guint size;
1766   GstBuffer *buffer;
1767   gboolean handled;
1768
1769   /* find the stream for this message */
1770   res = gst_rtsp_message_parse_data (message, &channel);
1771   if (res != GST_RTSP_OK)
1772     return;
1773
1774   gst_rtsp_message_steal_body (message, &data, &size);
1775
1776   buffer = gst_buffer_new_wrapped (data, size);
1777
1778   handled = FALSE;
1779   for (walk = priv->transports; walk; walk = g_list_next (walk)) {
1780     GstRTSPStreamTransport *trans;
1781     GstRTSPStream *stream;
1782     const GstRTSPTransport *tr;
1783
1784     trans = walk->data;
1785
1786     tr = gst_rtsp_stream_transport_get_transport (trans);
1787     stream = gst_rtsp_stream_transport_get_stream (trans);
1788
1789     /* check for TCP transport */
1790     if (tr->lower_transport == GST_RTSP_LOWER_TRANS_TCP) {
1791       /* dispatch to the stream based on the channel number */
1792       if (tr->interleaved.min == channel) {
1793         gst_rtsp_stream_recv_rtp (stream, buffer);
1794         handled = TRUE;
1795         break;
1796       } else if (tr->interleaved.max == channel) {
1797         gst_rtsp_stream_recv_rtcp (stream, buffer);
1798         handled = TRUE;
1799         break;
1800       }
1801     }
1802   }
1803   if (!handled)
1804     gst_buffer_unref (buffer);
1805 }
1806
1807 /**
1808  * gst_rtsp_client_set_session_pool:
1809  * @client: a #GstRTSPClient
1810  * @pool: a #GstRTSPSessionPool
1811  *
1812  * Set @pool as the sessionpool for @client which it will use to find
1813  * or allocate sessions. the sessionpool is usually inherited from the server
1814  * that created the client but can be overridden later.
1815  */
1816 void
1817 gst_rtsp_client_set_session_pool (GstRTSPClient * client,
1818     GstRTSPSessionPool * pool)
1819 {
1820   GstRTSPSessionPool *old;
1821   GstRTSPClientPrivate *priv;
1822
1823   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
1824
1825   priv = client->priv;
1826
1827   if (pool)
1828     g_object_ref (pool);
1829
1830   g_mutex_lock (&priv->lock);
1831   old = priv->session_pool;
1832   priv->session_pool = pool;
1833   g_mutex_unlock (&priv->lock);
1834
1835   if (old)
1836     g_object_unref (old);
1837 }
1838
1839 /**
1840  * gst_rtsp_client_get_session_pool:
1841  * @client: a #GstRTSPClient
1842  *
1843  * Get the #GstRTSPSessionPool object that @client uses to manage its sessions.
1844  *
1845  * Returns: (transfer full): a #GstRTSPSessionPool, unref after usage.
1846  */
1847 GstRTSPSessionPool *
1848 gst_rtsp_client_get_session_pool (GstRTSPClient * client)
1849 {
1850   GstRTSPClientPrivate *priv;
1851   GstRTSPSessionPool *result;
1852
1853   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
1854
1855   priv = client->priv;
1856
1857   g_mutex_lock (&priv->lock);
1858   if ((result = priv->session_pool))
1859     g_object_ref (result);
1860   g_mutex_unlock (&priv->lock);
1861
1862   return result;
1863 }
1864
1865 /**
1866  * gst_rtsp_client_set_mount_points:
1867  * @client: a #GstRTSPClient
1868  * @mounts: a #GstRTSPMountPoints
1869  *
1870  * Set @mounts as the mount points for @client which it will use to map urls
1871  * to media streams. These mount points are usually inherited from the server that
1872  * created the client but can be overriden later.
1873  */
1874 void
1875 gst_rtsp_client_set_mount_points (GstRTSPClient * client,
1876     GstRTSPMountPoints * mounts)
1877 {
1878   GstRTSPClientPrivate *priv;
1879   GstRTSPMountPoints *old;
1880
1881   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
1882
1883   priv = client->priv;
1884
1885   if (mounts)
1886     g_object_ref (mounts);
1887
1888   g_mutex_lock (&priv->lock);
1889   old = priv->mount_points;
1890   priv->mount_points = mounts;
1891   g_mutex_unlock (&priv->lock);
1892
1893   if (old)
1894     g_object_unref (old);
1895 }
1896
1897 /**
1898  * gst_rtsp_client_get_mount_points:
1899  * @client: a #GstRTSPClient
1900  *
1901  * Get the #GstRTSPMountPoints object that @client uses to manage its sessions.
1902  *
1903  * Returns: (transfer full): a #GstRTSPMountPoints, unref after usage.
1904  */
1905 GstRTSPMountPoints *
1906 gst_rtsp_client_get_mount_points (GstRTSPClient * client)
1907 {
1908   GstRTSPClientPrivate *priv;
1909   GstRTSPMountPoints *result;
1910
1911   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
1912
1913   priv = client->priv;
1914
1915   g_mutex_lock (&priv->lock);
1916   if ((result = priv->mount_points))
1917     g_object_ref (result);
1918   g_mutex_unlock (&priv->lock);
1919
1920   return result;
1921 }
1922
1923 /**
1924  * gst_rtsp_client_set_use_client_settings:
1925  * @client: a #GstRTSPClient
1926  * @use_client_settings: whether to use client settings for multicast
1927  *
1928  * Use client transport settings (destination and ttl) for multicast.
1929  * When @use_client_settings is %FALSE, the server settings will be
1930  * used.
1931  */
1932 void
1933 gst_rtsp_client_set_use_client_settings (GstRTSPClient * client,
1934     gboolean use_client_settings)
1935 {
1936   GstRTSPClientPrivate *priv;
1937
1938   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
1939
1940   priv = client->priv;
1941
1942   g_mutex_lock (&priv->lock);
1943   priv->use_client_settings = use_client_settings;
1944   g_mutex_unlock (&priv->lock);
1945 }
1946
1947 /**
1948  * gst_rtsp_client_get_use_client_settings:
1949  * @client: a #GstRTSPClient
1950  *
1951  * Check if client transport settings (destination and ttl) for multicast
1952  * will be used.
1953  */
1954 gboolean
1955 gst_rtsp_client_get_use_client_settings (GstRTSPClient * client)
1956 {
1957   GstRTSPClientPrivate *priv;
1958   gboolean res;
1959
1960   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), FALSE);
1961
1962   priv = client->priv;
1963
1964   g_mutex_lock (&priv->lock);
1965   res = priv->use_client_settings;
1966   g_mutex_unlock (&priv->lock);
1967
1968   return res;
1969 }
1970
1971 /**
1972  * gst_rtsp_client_set_auth:
1973  * @client: a #GstRTSPClient
1974  * @auth: a #GstRTSPAuth
1975  *
1976  * configure @auth to be used as the authentication manager of @client.
1977  */
1978 void
1979 gst_rtsp_client_set_auth (GstRTSPClient * client, GstRTSPAuth * auth)
1980 {
1981   GstRTSPClientPrivate *priv;
1982   GstRTSPAuth *old;
1983
1984   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
1985
1986   priv = client->priv;
1987
1988   if (auth)
1989     g_object_ref (auth);
1990
1991   g_mutex_lock (&priv->lock);
1992   old = priv->auth;
1993   priv->auth = auth;
1994   g_mutex_unlock (&priv->lock);
1995
1996   if (old)
1997     g_object_unref (old);
1998 }
1999
2000
2001 /**
2002  * gst_rtsp_client_get_auth:
2003  * @client: a #GstRTSPClient
2004  *
2005  * Get the #GstRTSPAuth used as the authentication manager of @client.
2006  *
2007  * Returns: (transfer full): the #GstRTSPAuth of @client. g_object_unref() after
2008  * usage.
2009  */
2010 GstRTSPAuth *
2011 gst_rtsp_client_get_auth (GstRTSPClient * client)
2012 {
2013   GstRTSPClientPrivate *priv;
2014   GstRTSPAuth *result;
2015
2016   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2017
2018   priv = client->priv;
2019
2020   g_mutex_lock (&priv->lock);
2021   if ((result = priv->auth))
2022     g_object_ref (result);
2023   g_mutex_unlock (&priv->lock);
2024
2025   return result;
2026 }
2027
2028 /**
2029  * gst_rtsp_client_get_uri:
2030  * @client: a #GstRTSPClient
2031  *
2032  * Get the #GstRTSPUrl of @client.
2033  *
2034  * Returns: (transfer full): the #GstRTSPUrl of @client. Free with
2035  * gst_rtsp_url_free () after usage.
2036  */
2037 GstRTSPUrl *
2038 gst_rtsp_client_get_uri (GstRTSPClient * client)
2039 {
2040   GstRTSPClientPrivate *priv;
2041   GstRTSPUrl *result = NULL;
2042
2043   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2044
2045   priv = client->priv;
2046
2047   g_mutex_lock (&priv->lock);
2048   if (priv->uri != NULL)
2049     result = gst_rtsp_url_copy (priv->uri);
2050   g_mutex_unlock (&priv->lock);
2051
2052   return result;
2053 }
2054
2055 /**
2056  * gst_rtsp_client_set_send_func:
2057  * @client: a #GstRTSPClient
2058  * @func: a #GstRTSPClientSendFunc
2059  * @user_data: user data passed to @func
2060  * @notify: called when @user_data is no longer in use
2061  *
2062  * Set @func as the callback that will be called when a new message needs to be
2063  * sent to the client. @user_data is passed to @func and @notify is called when
2064  * @user_data is no longer in use.
2065  */
2066 void
2067 gst_rtsp_client_set_send_func (GstRTSPClient * client,
2068     GstRTSPClientSendFunc func, gpointer user_data, GDestroyNotify notify)
2069 {
2070   GstRTSPClientPrivate *priv;
2071   GDestroyNotify old_notify;
2072   gpointer old_data;
2073
2074   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2075
2076   priv = client->priv;
2077
2078   g_mutex_lock (&priv->send_lock);
2079   priv->send_func = func;
2080   old_notify = priv->send_notify;
2081   old_data = priv->send_data;
2082   priv->send_notify = notify;
2083   priv->send_data = user_data;
2084   g_mutex_unlock (&priv->send_lock);
2085
2086   if (old_notify)
2087     old_notify (old_data);
2088 }
2089
2090 /**
2091  * gst_rtsp_client_handle_message:
2092  * @client: a #GstRTSPClient
2093  * @message: an #GstRTSPMessage
2094  *
2095  * Let the client handle @message.
2096  *
2097  * Returns: a #GstRTSPResult.
2098  */
2099 GstRTSPResult
2100 gst_rtsp_client_handle_message (GstRTSPClient * client,
2101     GstRTSPMessage * message)
2102 {
2103   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), GST_RTSP_EINVAL);
2104   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2105
2106   switch (message->type) {
2107     case GST_RTSP_MESSAGE_REQUEST:
2108       handle_request (client, message);
2109       break;
2110     case GST_RTSP_MESSAGE_RESPONSE:
2111       break;
2112     case GST_RTSP_MESSAGE_DATA:
2113       handle_data (client, message);
2114       break;
2115     default:
2116       break;
2117   }
2118   return GST_RTSP_OK;
2119 }
2120
2121 static GstRTSPResult
2122 do_send_message (GstRTSPClient * client, GstRTSPMessage * message,
2123     gboolean close, gpointer user_data)
2124 {
2125   GstRTSPClientPrivate *priv = client->priv;
2126
2127   /* send the response and store the seq number so we can wait until it's
2128    * written to the client to close the connection */
2129   return gst_rtsp_watch_send_message (priv->watch, message, close ?
2130       &priv->close_seq : NULL);
2131 }
2132
2133 static GstRTSPResult
2134 message_received (GstRTSPWatch * watch, GstRTSPMessage * message,
2135     gpointer user_data)
2136 {
2137   return gst_rtsp_client_handle_message (GST_RTSP_CLIENT (user_data), message);
2138 }
2139
2140 static GstRTSPResult
2141 message_sent (GstRTSPWatch * watch, guint cseq, gpointer user_data)
2142 {
2143   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2144   GstRTSPClientPrivate *priv = client->priv;
2145
2146   if (priv->close_seq && priv->close_seq == cseq) {
2147     priv->close_seq = 0;
2148     close_connection (client);
2149   }
2150
2151   return GST_RTSP_OK;
2152 }
2153
2154 static GstRTSPResult
2155 closed (GstRTSPWatch * watch, gpointer user_data)
2156 {
2157   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2158   GstRTSPClientPrivate *priv = client->priv;
2159   const gchar *tunnelid;
2160
2161   GST_INFO ("client %p: connection closed", client);
2162
2163   if ((tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection))) {
2164     g_mutex_lock (&tunnels_lock);
2165     /* remove from tunnelids */
2166     g_hash_table_remove (tunnels, tunnelid);
2167     g_mutex_unlock (&tunnels_lock);
2168   }
2169
2170   gst_rtsp_client_set_send_func (client, NULL, NULL, NULL);
2171
2172   return GST_RTSP_OK;
2173 }
2174
2175 static GstRTSPResult
2176 error (GstRTSPWatch * watch, GstRTSPResult result, gpointer user_data)
2177 {
2178   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2179   gchar *str;
2180
2181   str = gst_rtsp_strresult (result);
2182   GST_INFO ("client %p: received an error %s", client, str);
2183   g_free (str);
2184
2185   return GST_RTSP_OK;
2186 }
2187
2188 static GstRTSPResult
2189 error_full (GstRTSPWatch * watch, GstRTSPResult result,
2190     GstRTSPMessage * message, guint id, gpointer user_data)
2191 {
2192   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2193   gchar *str;
2194
2195   str = gst_rtsp_strresult (result);
2196   GST_INFO
2197       ("client %p: received an error %s when handling message %p with id %d",
2198       client, str, message, id);
2199   g_free (str);
2200
2201   return GST_RTSP_OK;
2202 }
2203
2204 static gboolean
2205 remember_tunnel (GstRTSPClient * client)
2206 {
2207   GstRTSPClientPrivate *priv = client->priv;
2208   const gchar *tunnelid;
2209
2210   /* store client in the pending tunnels */
2211   tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection);
2212   if (tunnelid == NULL)
2213     goto no_tunnelid;
2214
2215   GST_INFO ("client %p: inserting tunnel session %s", client, tunnelid);
2216
2217   /* we can't have two clients connecting with the same tunnelid */
2218   g_mutex_lock (&tunnels_lock);
2219   if (g_hash_table_lookup (tunnels, tunnelid))
2220     goto tunnel_existed;
2221
2222   g_hash_table_insert (tunnels, g_strdup (tunnelid), g_object_ref (client));
2223   g_mutex_unlock (&tunnels_lock);
2224
2225   return TRUE;
2226
2227   /* ERRORS */
2228 no_tunnelid:
2229   {
2230     GST_ERROR ("client %p: no tunnelid provided", client);
2231     return FALSE;
2232   }
2233 tunnel_existed:
2234   {
2235     g_mutex_unlock (&tunnels_lock);
2236     GST_ERROR ("client %p: tunnel session %s already existed", client,
2237         tunnelid);
2238     return FALSE;
2239   }
2240 }
2241
2242 static GstRTSPStatusCode
2243 tunnel_start (GstRTSPWatch * watch, gpointer user_data)
2244 {
2245   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2246   GstRTSPClientPrivate *priv = client->priv;
2247
2248   GST_INFO ("client %p: tunnel start (connection %p)", client,
2249       priv->connection);
2250
2251   if (!remember_tunnel (client))
2252     goto tunnel_error;
2253
2254   return GST_RTSP_STS_OK;
2255
2256   /* ERRORS */
2257 tunnel_error:
2258   {
2259     GST_ERROR ("client %p: error starting tunnel", client);
2260     return GST_RTSP_STS_SERVICE_UNAVAILABLE;
2261   }
2262 }
2263
2264 static GstRTSPResult
2265 tunnel_lost (GstRTSPWatch * watch, gpointer user_data)
2266 {
2267   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2268   GstRTSPClientPrivate *priv = client->priv;
2269
2270   GST_WARNING ("client %p: tunnel lost (connection %p)", client,
2271       priv->connection);
2272
2273   /* ignore error, it'll only be a problem when the client does a POST again */
2274   remember_tunnel (client);
2275
2276   return GST_RTSP_OK;
2277 }
2278
2279 static GstRTSPResult
2280 tunnel_complete (GstRTSPWatch * watch, gpointer user_data)
2281 {
2282   const gchar *tunnelid;
2283   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2284   GstRTSPClientPrivate *priv = client->priv;
2285   GstRTSPClient *oclient;
2286   GstRTSPClientPrivate *opriv;
2287
2288   GST_INFO ("client %p: tunnel complete", client);
2289
2290   /* find previous tunnel */
2291   tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection);
2292   if (tunnelid == NULL)
2293     goto no_tunnelid;
2294
2295   g_mutex_lock (&tunnels_lock);
2296   if (!(oclient = g_hash_table_lookup (tunnels, tunnelid)))
2297     goto no_tunnel;
2298
2299   /* remove the old client from the table. ref before because removing it will
2300    * remove the ref to it. */
2301   g_object_ref (oclient);
2302   g_hash_table_remove (tunnels, tunnelid);
2303
2304   opriv = oclient->priv;
2305
2306   if (opriv->watch == NULL)
2307     goto tunnel_closed;
2308   g_mutex_unlock (&tunnels_lock);
2309
2310   GST_INFO ("client %p: found tunnel %p (old %p, new %p)", client, oclient,
2311       opriv->connection, priv->connection);
2312
2313   /* merge the tunnels into the first client */
2314   gst_rtsp_connection_do_tunnel (opriv->connection, priv->connection);
2315   gst_rtsp_watch_reset (opriv->watch);
2316   g_object_unref (oclient);
2317
2318   return GST_RTSP_OK;
2319
2320   /* ERRORS */
2321 no_tunnelid:
2322   {
2323     GST_ERROR ("client %p: no tunnelid provided", client);
2324     return GST_RTSP_ERROR;
2325   }
2326 no_tunnel:
2327   {
2328     g_mutex_unlock (&tunnels_lock);
2329     GST_ERROR ("client %p: tunnel session %s not found", client, tunnelid);
2330     return GST_RTSP_ERROR;
2331   }
2332 tunnel_closed:
2333   {
2334     g_mutex_unlock (&tunnels_lock);
2335     GST_ERROR ("client %p: tunnel session %s was closed", client, tunnelid);
2336     g_object_unref (oclient);
2337     return GST_RTSP_ERROR;
2338   }
2339 }
2340
2341 static GstRTSPWatchFuncs watch_funcs = {
2342   message_received,
2343   message_sent,
2344   closed,
2345   error,
2346   tunnel_start,
2347   tunnel_complete,
2348   error_full,
2349   tunnel_lost
2350 };
2351
2352 static void
2353 client_watch_notify (GstRTSPClient * client)
2354 {
2355   GstRTSPClientPrivate *priv = client->priv;
2356
2357   GST_INFO ("client %p: watch destroyed", client);
2358   priv->watch = NULL;
2359   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_CLOSED], 0, NULL);
2360   g_object_unref (client);
2361 }
2362
2363 static gboolean
2364 setup_client (GstRTSPClient * client, GSocket * socket,
2365     GstRTSPConnection * conn, GError ** error)
2366 {
2367   GstRTSPClientPrivate *priv = client->priv;
2368   GSocket *read_socket;
2369   GSocketAddress *address;
2370   GstRTSPUrl *url;
2371
2372   read_socket = gst_rtsp_connection_get_read_socket (conn);
2373   priv->is_ipv6 = g_socket_get_family (socket) == G_SOCKET_FAMILY_IPV6;
2374
2375   if (!(address = g_socket_get_remote_address (read_socket, error)))
2376     goto no_address;
2377
2378   g_free (priv->server_ip);
2379   /* keep the original ip that the client connected to */
2380   if (G_IS_INET_SOCKET_ADDRESS (address)) {
2381     GInetAddress *iaddr;
2382
2383     iaddr = g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (address));
2384
2385     priv->server_ip = g_inet_address_to_string (iaddr);
2386     g_object_unref (address);
2387   } else {
2388     priv->server_ip = g_strdup ("unknown");
2389   }
2390
2391   GST_INFO ("client %p connected to server ip %s, ipv6 = %d", client,
2392       priv->server_ip, priv->is_ipv6);
2393
2394   url = gst_rtsp_connection_get_url (conn);
2395   GST_INFO ("added new client %p ip %s:%d", client, url->host, url->port);
2396
2397   priv->connection = conn;
2398
2399   return TRUE;
2400
2401   /* ERRORS */
2402 no_address:
2403   {
2404     GST_ERROR ("could not get remote address %s", (*error)->message);
2405     return FALSE;
2406   }
2407 }
2408
2409 /**
2410  * gst_rtsp_client_use_socket:
2411  * @client: a #GstRTSPClient
2412  * @socket: a #GSocket
2413  * @ip: the IP address of the remote client
2414  * @port: the port used by the other end
2415  * @initial_buffer: any zero terminated initial data that was already read from
2416  *     the socket
2417  * @error: a #GError
2418  *
2419  * Take an existing network socket and use it for an RTSP connection.
2420  *
2421  * Returns: %TRUE on success.
2422  */
2423 gboolean
2424 gst_rtsp_client_use_socket (GstRTSPClient * client, GSocket * socket,
2425     const gchar * ip, gint port, const gchar * initial_buffer, GError ** error)
2426 {
2427   GstRTSPConnection *conn;
2428   GstRTSPResult res;
2429
2430   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), FALSE);
2431   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2432
2433   GST_RTSP_CHECK (gst_rtsp_connection_create_from_socket (socket, ip, port,
2434           initial_buffer, &conn), no_connection);
2435
2436   return setup_client (client, socket, conn, error);
2437
2438   /* ERRORS */
2439 no_connection:
2440   {
2441     gchar *str = gst_rtsp_strresult (res);
2442
2443     GST_ERROR ("could not create connection from socket %p: %s", socket, str);
2444     g_free (str);
2445     return FALSE;
2446   }
2447 }
2448
2449 /**
2450  * gst_rtsp_client_accept:
2451  * @client: a #GstRTSPClient
2452  * @socket: a #GSocket
2453  * @context: the context to run in
2454  * @cancellable: a #GCancellable
2455  * @error: a #GError
2456  *
2457  * Accept a new connection for @client on @socket.
2458  *
2459  * Returns: %TRUE if the client could be accepted.
2460  */
2461 gboolean
2462 gst_rtsp_client_accept (GstRTSPClient * client, GSocket * socket,
2463     GCancellable * cancellable, GError ** error)
2464 {
2465   GstRTSPConnection *conn;
2466   GstRTSPResult res;
2467
2468   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), FALSE);
2469   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2470
2471   /* a new client connected. */
2472   GST_RTSP_CHECK (gst_rtsp_connection_accept (socket, &conn, cancellable),
2473       accept_failed);
2474
2475   return setup_client (client, socket, conn, error);
2476
2477   /* ERRORS */
2478 accept_failed:
2479   {
2480     gchar *str = gst_rtsp_strresult (res);
2481
2482     GST_ERROR ("Could not accept client on server socket %p: %s", socket, str);
2483     g_free (str);
2484     return FALSE;
2485   }
2486 }
2487
2488 /**
2489  * gst_rtsp_client_attach:
2490  * @client: a #GstRTSPClient
2491  * @context: (allow-none): a #GMainContext
2492  *
2493  * Attaches @client to @context. When the mainloop for @context is run, the
2494  * client will be dispatched. When @context is NULL, the default context will be
2495  * used).
2496  *
2497  * This function should be called when the client properties and urls are fully
2498  * configured and the client is ready to start.
2499  *
2500  * Returns: the ID (greater than 0) for the source within the GMainContext.
2501  */
2502 guint
2503 gst_rtsp_client_attach (GstRTSPClient * client, GMainContext * context)
2504 {
2505   GstRTSPClientPrivate *priv;
2506   guint res;
2507
2508   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), 0);
2509   priv = client->priv;
2510   g_return_val_if_fail (priv->watch == NULL, 0);
2511
2512   /* create watch for the connection and attach */
2513   priv->watch = gst_rtsp_watch_new (priv->connection, &watch_funcs,
2514       g_object_ref (client), (GDestroyNotify) client_watch_notify);
2515   gst_rtsp_client_set_send_func (client, do_send_message, priv->watch,
2516       (GDestroyNotify) gst_rtsp_watch_unref);
2517
2518   /* FIXME make this configurable. We don't want to do this yet because it will
2519    * be superceeded by a cache object later */
2520   gst_rtsp_watch_set_send_backlog (priv->watch, 0, 100);
2521
2522   GST_INFO ("attaching to context %p", context);
2523   res = gst_rtsp_watch_attach (priv->watch, context);
2524
2525   return res;
2526 }