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