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