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