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