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