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