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