stream: add more support for IPv6
[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       GSocketFamily family;
1188
1189       family = priv->is_ipv6 ? G_SOCKET_FAMILY_IPV6 : G_SOCKET_FAMILY_IPV4;
1190
1191       addr = gst_rtsp_stream_get_multicast_address (state->stream, family);
1192       if (addr == NULL)
1193         goto no_address;
1194
1195       g_free (ct->destination);
1196       ct->destination = g_strdup (addr->address);
1197       ct->port.min = addr->port;
1198       ct->port.max = addr->port + addr->n_ports - 1;
1199       ct->ttl = addr->ttl;
1200
1201       gst_rtsp_address_free (addr);
1202     }
1203   } else {
1204     GstRTSPUrl *url;
1205
1206     url = gst_rtsp_connection_get_url (priv->connection);
1207     g_free (ct->destination);
1208     ct->destination = g_strdup (url->host);
1209
1210     if (ct->lower_transport & GST_RTSP_LOWER_TRANS_TCP) {
1211       /* check if the client selected channels for TCP */
1212       if (ct->interleaved.min == -1 || ct->interleaved.max == -1) {
1213         gst_rtsp_session_media_alloc_channels (state->sessmedia,
1214             &ct->interleaved);
1215       }
1216     }
1217   }
1218   return TRUE;
1219
1220   /* ERRORS */
1221 no_address:
1222   {
1223     GST_ERROR_OBJECT (client, "failed to acquire address for stream");
1224     return FALSE;
1225   }
1226 }
1227
1228 static GstRTSPTransport *
1229 make_server_transport (GstRTSPClient * client, GstRTSPClientState * state,
1230     GstRTSPTransport * ct)
1231 {
1232   GstRTSPTransport *st;
1233   GInetAddress *addr;
1234   GSocketFamily family;
1235
1236   /* prepare the server transport */
1237   gst_rtsp_transport_new (&st);
1238
1239   st->trans = ct->trans;
1240   st->profile = ct->profile;
1241   st->lower_transport = ct->lower_transport;
1242
1243   addr = g_inet_address_new_from_string (ct->destination);
1244
1245   if (!addr) {
1246     GST_ERROR ("failed to get inet addr from client destination");
1247     family = G_SOCKET_FAMILY_IPV4;
1248   } else {
1249     family = g_inet_address_get_family (addr);
1250     g_object_unref (addr);
1251     addr = NULL;
1252   }
1253
1254   switch (st->lower_transport) {
1255     case GST_RTSP_LOWER_TRANS_UDP:
1256       st->client_port = ct->client_port;
1257       gst_rtsp_stream_get_server_port (state->stream, &st->server_port, family);
1258       break;
1259     case GST_RTSP_LOWER_TRANS_UDP_MCAST:
1260       st->port = ct->port;
1261       st->destination = g_strdup (ct->destination);
1262       st->ttl = ct->ttl;
1263       break;
1264     case GST_RTSP_LOWER_TRANS_TCP:
1265       st->interleaved = ct->interleaved;
1266     default:
1267       break;
1268   }
1269
1270   gst_rtsp_stream_get_ssrc (state->stream, &st->ssrc);
1271
1272   return st;
1273 }
1274
1275 static gboolean
1276 handle_setup_request (GstRTSPClient * client, GstRTSPClientState * state)
1277 {
1278   GstRTSPClientPrivate *priv = client->priv;
1279   GstRTSPResult res;
1280   GstRTSPUrl *uri;
1281   gchar *transport;
1282   GstRTSPTransport *ct, *st;
1283   GstRTSPLowerTrans supported;
1284   GstRTSPStatusCode code;
1285   GstRTSPSession *session;
1286   GstRTSPStreamTransport *trans;
1287   gchar *trans_str, *pos;
1288   guint streamid;
1289   GstRTSPSessionMedia *sessmedia;
1290   GstRTSPMedia *media;
1291   GstRTSPStream *stream;
1292   GstRTSPState rtspstate;
1293   GstRTSPClientClass *klass;
1294
1295   if (!state->uri)
1296     goto no_uri;
1297
1298   uri = state->uri;
1299
1300   /* the uri contains the stream number we added in the SDP config, which is
1301    * always /stream=%d so we need to strip that off
1302    * parse the stream we need to configure, look for the stream in the abspath
1303    * first and then in the query. */
1304   if (uri->abspath == NULL || !(pos = strstr (uri->abspath, "/stream="))) {
1305     if (uri->query == NULL || !(pos = strstr (uri->query, "/stream=")))
1306       goto bad_request;
1307   }
1308
1309   /* we can mofify the parsed uri in place */
1310   *pos = '\0';
1311
1312   pos += strlen ("/stream=");
1313   if (sscanf (pos, "%u", &streamid) != 1)
1314     goto bad_request;
1315
1316   /* parse the transport */
1317   res =
1318       gst_rtsp_message_get_header (state->request, GST_RTSP_HDR_TRANSPORT,
1319       &transport, 0);
1320   if (res != GST_RTSP_OK)
1321     goto no_transport;
1322
1323   gst_rtsp_transport_new (&ct);
1324
1325   /* our supported transports */
1326   supported = GST_RTSP_LOWER_TRANS_UDP |
1327       GST_RTSP_LOWER_TRANS_UDP_MCAST | GST_RTSP_LOWER_TRANS_TCP;
1328
1329   /* parse and find a usable supported transport */
1330   if (!parse_transport (transport, supported, ct))
1331     goto unsupported_transports;
1332
1333   /* we create the session after parsing stuff so that we don't make
1334    * a session for malformed requests */
1335   if (priv->session_pool == NULL)
1336     goto no_pool;
1337
1338   session = state->session;
1339
1340   if (session) {
1341     g_object_ref (session);
1342     /* get a handle to the configuration of the media in the session, this can
1343      * return NULL if this is a new url to manage in this session. */
1344     sessmedia = gst_rtsp_session_get_media (session, uri);
1345   } else {
1346     /* create a session if this fails we probably reached our session limit or
1347      * something. */
1348     if (!(session = gst_rtsp_session_pool_create (priv->session_pool)))
1349       goto service_unavailable;
1350
1351     /* make sure this client is closed when the session is closed */
1352     client_watch_session (client, session);
1353
1354     /* signal new session */
1355     g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_NEW_SESSION], 0,
1356         session);
1357
1358     state->session = session;
1359
1360     /* we need a new media configuration in this session */
1361     sessmedia = NULL;
1362   }
1363
1364   /* we have no media, find one and manage it */
1365   if (sessmedia == NULL) {
1366     /* get a handle to the configuration of the media in the session */
1367     if ((media = find_media (client, state))) {
1368       /* manage the media in our session now */
1369       sessmedia = gst_rtsp_session_manage_media (session, uri, media);
1370     }
1371   }
1372
1373   /* if we stil have no media, error */
1374   if (sessmedia == NULL)
1375     goto not_found;
1376
1377   state->sessmedia = sessmedia;
1378   state->media = media = gst_rtsp_session_media_get_media (sessmedia);
1379
1380   /* now get the stream */
1381   stream = gst_rtsp_media_get_stream (media, streamid);
1382   if (stream == NULL)
1383     goto not_found;
1384
1385   state->stream = stream;
1386
1387   /* set blocksize on this stream */
1388   if (!handle_blocksize (media, stream, state->request))
1389     goto invalid_blocksize;
1390
1391   /* update the client transport */
1392   klass = GST_RTSP_CLIENT_GET_CLASS (client);
1393   if (!klass->configure_client_transport (client, state, ct))
1394     goto unsupported_client_transport;
1395
1396   /* set in the session media transport */
1397   trans = gst_rtsp_session_media_set_transport (sessmedia, stream, ct);
1398
1399   /* configure keepalive for this transport */
1400   gst_rtsp_stream_transport_set_keepalive (trans,
1401       (GstRTSPKeepAliveFunc) do_keepalive, session, NULL);
1402
1403   /* create and serialize the server transport */
1404   st = make_server_transport (client, state, ct);
1405   trans_str = gst_rtsp_transport_as_text (st);
1406   gst_rtsp_transport_free (st);
1407
1408   /* construct the response now */
1409   code = GST_RTSP_STS_OK;
1410   gst_rtsp_message_init_response (state->response, code,
1411       gst_rtsp_status_as_text (code), state->request);
1412
1413   gst_rtsp_message_add_header (state->response, GST_RTSP_HDR_TRANSPORT,
1414       trans_str);
1415   g_free (trans_str);
1416
1417   send_message (client, session, state->response, FALSE);
1418
1419   /* update the state */
1420   rtspstate = gst_rtsp_session_media_get_rtsp_state (sessmedia);
1421   switch (rtspstate) {
1422     case GST_RTSP_STATE_PLAYING:
1423     case GST_RTSP_STATE_RECORDING:
1424     case GST_RTSP_STATE_READY:
1425       /* no state change */
1426       break;
1427     default:
1428       gst_rtsp_session_media_set_rtsp_state (sessmedia, GST_RTSP_STATE_READY);
1429       break;
1430   }
1431   g_object_unref (session);
1432
1433   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_SETUP_REQUEST],
1434       0, state);
1435
1436   return TRUE;
1437
1438   /* ERRORS */
1439 no_uri:
1440   {
1441     GST_ERROR ("client %p: no uri", client);
1442     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, state);
1443     return FALSE;
1444   }
1445 bad_request:
1446   {
1447     GST_ERROR ("client %p: bad request", client);
1448     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, state);
1449     return FALSE;
1450   }
1451 not_found:
1452   {
1453     GST_ERROR ("client %p: media not found", client);
1454     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, state);
1455     g_object_unref (session);
1456     gst_rtsp_transport_free (ct);
1457     return FALSE;
1458   }
1459 invalid_blocksize:
1460   {
1461     GST_ERROR ("client %p: invalid blocksize", client);
1462     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, state);
1463     g_object_unref (session);
1464     gst_rtsp_transport_free (ct);
1465     return FALSE;
1466   }
1467 unsupported_client_transport:
1468   {
1469     GST_ERROR ("client %p: unsupported client transport", client);
1470     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, state);
1471     g_object_unref (session);
1472     gst_rtsp_transport_free (ct);
1473     return FALSE;
1474   }
1475 no_transport:
1476   {
1477     GST_ERROR ("client %p: no transport", client);
1478     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, state);
1479     return FALSE;
1480   }
1481 unsupported_transports:
1482   {
1483     GST_ERROR ("client %p: unsupported transports", client);
1484     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, state);
1485     gst_rtsp_transport_free (ct);
1486     return FALSE;
1487   }
1488 no_pool:
1489   {
1490     GST_ERROR ("client %p: no session pool configured", client);
1491     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, state);
1492     gst_rtsp_transport_free (ct);
1493     return FALSE;
1494   }
1495 service_unavailable:
1496   {
1497     GST_ERROR ("client %p: can't create session", client);
1498     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, state);
1499     gst_rtsp_transport_free (ct);
1500     return FALSE;
1501   }
1502 }
1503
1504 static GstSDPMessage *
1505 create_sdp (GstRTSPClient * client, GstRTSPMedia * media)
1506 {
1507   GstRTSPClientPrivate *priv = client->priv;
1508   GstSDPMessage *sdp;
1509   GstSDPInfo info;
1510   const gchar *proto;
1511
1512   gst_sdp_message_new (&sdp);
1513
1514   /* some standard things first */
1515   gst_sdp_message_set_version (sdp, "0");
1516
1517   if (priv->is_ipv6)
1518     proto = "IP6";
1519   else
1520     proto = "IP4";
1521
1522   gst_sdp_message_set_origin (sdp, "-", "1188340656180883", "1", "IN", proto,
1523       priv->server_ip);
1524
1525   gst_sdp_message_set_session_name (sdp, "Session streamed with GStreamer");
1526   gst_sdp_message_set_information (sdp, "rtsp-server");
1527   gst_sdp_message_add_time (sdp, "0", "0", NULL);
1528   gst_sdp_message_add_attribute (sdp, "tool", "GStreamer");
1529   gst_sdp_message_add_attribute (sdp, "type", "broadcast");
1530   gst_sdp_message_add_attribute (sdp, "control", "*");
1531
1532   info.is_ipv6 = priv->is_ipv6;
1533   info.server_ip = priv->server_ip;
1534
1535   /* create an SDP for the media object */
1536   if (!gst_rtsp_sdp_from_media (sdp, &info, media))
1537     goto no_sdp;
1538
1539   return sdp;
1540
1541   /* ERRORS */
1542 no_sdp:
1543   {
1544     GST_ERROR ("client %p: could not create SDP", client);
1545     gst_sdp_message_free (sdp);
1546     return NULL;
1547   }
1548 }
1549
1550 /* for the describe we must generate an SDP */
1551 static gboolean
1552 handle_describe_request (GstRTSPClient * client, GstRTSPClientState * state)
1553 {
1554   GstRTSPResult res;
1555   GstSDPMessage *sdp;
1556   guint i, str_len;
1557   gchar *str, *content_base;
1558   GstRTSPMedia *media;
1559   GstRTSPClientClass *klass;
1560
1561   klass = GST_RTSP_CLIENT_GET_CLASS (client);
1562
1563   if (!state->uri)
1564     goto no_uri;
1565
1566   /* check what kind of format is accepted, we don't really do anything with it
1567    * and always return SDP for now. */
1568   for (i = 0; i++;) {
1569     gchar *accept;
1570
1571     res =
1572         gst_rtsp_message_get_header (state->request, GST_RTSP_HDR_ACCEPT,
1573         &accept, i);
1574     if (res == GST_RTSP_ENOTIMPL)
1575       break;
1576
1577     if (g_ascii_strcasecmp (accept, "application/sdp") == 0)
1578       break;
1579   }
1580
1581   /* find the media object for the uri */
1582   if (!(media = find_media (client, state)))
1583     goto no_media;
1584
1585   /* create an SDP for the media object on this client */
1586   if (!(sdp = klass->create_sdp (client, media)))
1587     goto no_sdp;
1588
1589   g_object_unref (media);
1590
1591   gst_rtsp_message_init_response (state->response, GST_RTSP_STS_OK,
1592       gst_rtsp_status_as_text (GST_RTSP_STS_OK), state->request);
1593
1594   gst_rtsp_message_add_header (state->response, GST_RTSP_HDR_CONTENT_TYPE,
1595       "application/sdp");
1596
1597   /* content base for some clients that might screw up creating the setup uri */
1598   str = gst_rtsp_url_get_request_uri (state->uri);
1599   str_len = strlen (str);
1600
1601   /* check for trailing '/' and append one */
1602   if (str[str_len - 1] != '/') {
1603     content_base = g_malloc (str_len + 2);
1604     memcpy (content_base, str, str_len);
1605     content_base[str_len] = '/';
1606     content_base[str_len + 1] = '\0';
1607     g_free (str);
1608   } else {
1609     content_base = str;
1610   }
1611
1612   GST_INFO ("adding content-base: %s", content_base);
1613
1614   gst_rtsp_message_add_header (state->response, GST_RTSP_HDR_CONTENT_BASE,
1615       content_base);
1616   g_free (content_base);
1617
1618   /* add SDP to the response body */
1619   str = gst_sdp_message_as_text (sdp);
1620   gst_rtsp_message_take_body (state->response, (guint8 *) str, strlen (str));
1621   gst_sdp_message_free (sdp);
1622
1623   send_message (client, state->session, state->response, FALSE);
1624
1625   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_DESCRIBE_REQUEST],
1626       0, state);
1627
1628   return TRUE;
1629
1630   /* ERRORS */
1631 no_uri:
1632   {
1633     GST_ERROR ("client %p: no uri", client);
1634     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, state);
1635     return FALSE;
1636   }
1637 no_media:
1638   {
1639     GST_ERROR ("client %p: no media", client);
1640     /* error reply is already sent */
1641     return FALSE;
1642   }
1643 no_sdp:
1644   {
1645     GST_ERROR ("client %p: can't create SDP", client);
1646     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, state);
1647     g_object_unref (media);
1648     return FALSE;
1649   }
1650 }
1651
1652 static gboolean
1653 handle_options_request (GstRTSPClient * client, GstRTSPClientState * state)
1654 {
1655   GstRTSPMethod options;
1656   gchar *str;
1657
1658   options = GST_RTSP_DESCRIBE |
1659       GST_RTSP_OPTIONS |
1660       GST_RTSP_PAUSE |
1661       GST_RTSP_PLAY |
1662       GST_RTSP_SETUP |
1663       GST_RTSP_GET_PARAMETER | GST_RTSP_SET_PARAMETER | GST_RTSP_TEARDOWN;
1664
1665   str = gst_rtsp_options_as_text (options);
1666
1667   gst_rtsp_message_init_response (state->response, GST_RTSP_STS_OK,
1668       gst_rtsp_status_as_text (GST_RTSP_STS_OK), state->request);
1669
1670   gst_rtsp_message_add_header (state->response, GST_RTSP_HDR_PUBLIC, str);
1671   g_free (str);
1672
1673   send_message (client, state->session, state->response, FALSE);
1674
1675   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_OPTIONS_REQUEST],
1676       0, state);
1677
1678   return TRUE;
1679 }
1680
1681 /* remove duplicate and trailing '/' */
1682 static void
1683 sanitize_uri (GstRTSPUrl * uri)
1684 {
1685   gint i, len;
1686   gchar *s, *d;
1687   gboolean have_slash, prev_slash;
1688
1689   s = d = uri->abspath;
1690   len = strlen (uri->abspath);
1691
1692   prev_slash = FALSE;
1693
1694   for (i = 0; i < len; i++) {
1695     have_slash = s[i] == '/';
1696     *d = s[i];
1697     if (!have_slash || !prev_slash)
1698       d++;
1699     prev_slash = have_slash;
1700   }
1701   len = d - uri->abspath;
1702   /* don't remove the first slash if that's the only thing left */
1703   if (len > 1 && *(d - 1) == '/')
1704     d--;
1705   *d = '\0';
1706 }
1707
1708 static void
1709 client_session_finalized (GstRTSPClient * client, GstRTSPSession * session)
1710 {
1711   GstRTSPClientPrivate *priv = client->priv;
1712
1713   GST_INFO ("client %p: session %p finished", client, session);
1714
1715   /* unlink all media managed in this session */
1716   client_unlink_session (client, session);
1717
1718   /* remove the session */
1719   if (!(priv->sessions = g_list_remove (priv->sessions, session))) {
1720     GST_INFO ("client %p: all sessions finalized, close the connection",
1721         client);
1722     close_connection (client);
1723   }
1724 }
1725
1726 static void
1727 handle_request (GstRTSPClient * client, GstRTSPMessage * request)
1728 {
1729   GstRTSPClientPrivate *priv = client->priv;
1730   GstRTSPMethod method;
1731   const gchar *uristr;
1732   GstRTSPUrl *uri = NULL;
1733   GstRTSPVersion version;
1734   GstRTSPResult res;
1735   GstRTSPSession *session = NULL;
1736   GstRTSPClientState state = { NULL };
1737   GstRTSPMessage response = { 0 };
1738   gchar *sessid;
1739
1740   state.request = request;
1741   state.response = &response;
1742
1743   if (gst_debug_category_get_threshold (rtsp_client_debug) >= GST_LEVEL_LOG) {
1744     gst_rtsp_message_dump (request);
1745   }
1746
1747   GST_INFO ("client %p: received a request", client);
1748
1749   gst_rtsp_message_parse_request (request, &method, &uristr, &version);
1750
1751   /* we can only handle 1.0 requests */
1752   if (version != GST_RTSP_VERSION_1_0)
1753     goto not_supported;
1754
1755   state.method = method;
1756
1757   /* we always try to parse the url first */
1758   if (strcmp (uristr, "*") == 0) {
1759     /* special case where we have * as uri, keep uri = NULL */
1760   } else if (gst_rtsp_url_parse (uristr, &uri) != GST_RTSP_OK)
1761     goto bad_request;
1762
1763   /* get the session if there is any */
1764   res = gst_rtsp_message_get_header (request, GST_RTSP_HDR_SESSION, &sessid, 0);
1765   if (res == GST_RTSP_OK) {
1766     if (priv->session_pool == NULL)
1767       goto no_pool;
1768
1769     /* we had a session in the request, find it again */
1770     if (!(session = gst_rtsp_session_pool_find (priv->session_pool, sessid)))
1771       goto session_not_found;
1772
1773     /* we add the session to the client list of watched sessions. When a session
1774      * disappears because it times out, we will be notified. If all sessions are
1775      * gone, we will close the connection */
1776     client_watch_session (client, session);
1777   }
1778
1779   /* sanitize the uri */
1780   if (uri)
1781     sanitize_uri (uri);
1782   state.uri = uri;
1783   state.session = session;
1784
1785   if (priv->auth) {
1786     if (!gst_rtsp_auth_check (priv->auth, client, 0, &state))
1787       goto not_authorized;
1788   }
1789
1790   /* now see what is asked and dispatch to a dedicated handler */
1791   switch (method) {
1792     case GST_RTSP_OPTIONS:
1793       handle_options_request (client, &state);
1794       break;
1795     case GST_RTSP_DESCRIBE:
1796       handle_describe_request (client, &state);
1797       break;
1798     case GST_RTSP_SETUP:
1799       handle_setup_request (client, &state);
1800       break;
1801     case GST_RTSP_PLAY:
1802       handle_play_request (client, &state);
1803       break;
1804     case GST_RTSP_PAUSE:
1805       handle_pause_request (client, &state);
1806       break;
1807     case GST_RTSP_TEARDOWN:
1808       handle_teardown_request (client, &state);
1809       break;
1810     case GST_RTSP_SET_PARAMETER:
1811       handle_set_param_request (client, &state);
1812       break;
1813     case GST_RTSP_GET_PARAMETER:
1814       handle_get_param_request (client, &state);
1815       break;
1816     case GST_RTSP_ANNOUNCE:
1817     case GST_RTSP_RECORD:
1818     case GST_RTSP_REDIRECT:
1819       goto not_implemented;
1820     case GST_RTSP_INVALID:
1821     default:
1822       goto bad_request;
1823   }
1824
1825 done:
1826   if (session)
1827     g_object_unref (session);
1828   if (uri)
1829     gst_rtsp_url_free (uri);
1830   return;
1831
1832   /* ERRORS */
1833 not_supported:
1834   {
1835     GST_ERROR ("client %p: version %d not supported", client, version);
1836     send_generic_response (client, GST_RTSP_STS_RTSP_VERSION_NOT_SUPPORTED,
1837         &state);
1838     goto done;
1839   }
1840 bad_request:
1841   {
1842     GST_ERROR ("client %p: bad request", client);
1843     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, &state);
1844     goto done;
1845   }
1846 no_pool:
1847   {
1848     GST_ERROR ("client %p: no pool configured", client);
1849     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, &state);
1850     goto done;
1851   }
1852 session_not_found:
1853   {
1854     GST_ERROR ("client %p: session not found", client);
1855     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, &state);
1856     goto done;
1857   }
1858 not_authorized:
1859   {
1860     GST_ERROR ("client %p: not allowed", client);
1861     handle_unauthorized_request (client, priv->auth, &state);
1862     goto done;
1863   }
1864 not_implemented:
1865   {
1866     GST_ERROR ("client %p: method %d not implemented", client, method);
1867     send_generic_response (client, GST_RTSP_STS_NOT_IMPLEMENTED, &state);
1868     goto done;
1869   }
1870 }
1871
1872 static void
1873 handle_data (GstRTSPClient * client, GstRTSPMessage * message)
1874 {
1875   GstRTSPClientPrivate *priv = client->priv;
1876   GstRTSPResult res;
1877   guint8 channel;
1878   GList *walk;
1879   guint8 *data;
1880   guint size;
1881   GstBuffer *buffer;
1882   gboolean handled;
1883
1884   /* find the stream for this message */
1885   res = gst_rtsp_message_parse_data (message, &channel);
1886   if (res != GST_RTSP_OK)
1887     return;
1888
1889   gst_rtsp_message_steal_body (message, &data, &size);
1890
1891   buffer = gst_buffer_new_wrapped (data, size);
1892
1893   handled = FALSE;
1894   for (walk = priv->transports; walk; walk = g_list_next (walk)) {
1895     GstRTSPStreamTransport *trans;
1896     GstRTSPStream *stream;
1897     const GstRTSPTransport *tr;
1898
1899     trans = walk->data;
1900
1901     tr = gst_rtsp_stream_transport_get_transport (trans);
1902     stream = gst_rtsp_stream_transport_get_stream (trans);
1903
1904     /* check for TCP transport */
1905     if (tr->lower_transport == GST_RTSP_LOWER_TRANS_TCP) {
1906       /* dispatch to the stream based on the channel number */
1907       if (tr->interleaved.min == channel) {
1908         gst_rtsp_stream_recv_rtp (stream, buffer);
1909         handled = TRUE;
1910         break;
1911       } else if (tr->interleaved.max == channel) {
1912         gst_rtsp_stream_recv_rtcp (stream, buffer);
1913         handled = TRUE;
1914         break;
1915       }
1916     }
1917   }
1918   if (!handled)
1919     gst_buffer_unref (buffer);
1920 }
1921
1922 /**
1923  * gst_rtsp_client_set_session_pool:
1924  * @client: a #GstRTSPClient
1925  * @pool: a #GstRTSPSessionPool
1926  *
1927  * Set @pool as the sessionpool for @client which it will use to find
1928  * or allocate sessions. the sessionpool is usually inherited from the server
1929  * that created the client but can be overridden later.
1930  */
1931 void
1932 gst_rtsp_client_set_session_pool (GstRTSPClient * client,
1933     GstRTSPSessionPool * pool)
1934 {
1935   GstRTSPSessionPool *old;
1936   GstRTSPClientPrivate *priv;
1937
1938   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
1939
1940   priv = client->priv;
1941
1942   if (pool)
1943     g_object_ref (pool);
1944
1945   g_mutex_lock (&priv->lock);
1946   old = priv->session_pool;
1947   priv->session_pool = pool;
1948   g_mutex_unlock (&priv->lock);
1949
1950   if (old)
1951     g_object_unref (old);
1952 }
1953
1954 /**
1955  * gst_rtsp_client_get_session_pool:
1956  * @client: a #GstRTSPClient
1957  *
1958  * Get the #GstRTSPSessionPool object that @client uses to manage its sessions.
1959  *
1960  * Returns: (transfer full): a #GstRTSPSessionPool, unref after usage.
1961  */
1962 GstRTSPSessionPool *
1963 gst_rtsp_client_get_session_pool (GstRTSPClient * client)
1964 {
1965   GstRTSPClientPrivate *priv;
1966   GstRTSPSessionPool *result;
1967
1968   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
1969
1970   priv = client->priv;
1971
1972   g_mutex_lock (&priv->lock);
1973   if ((result = priv->session_pool))
1974     g_object_ref (result);
1975   g_mutex_unlock (&priv->lock);
1976
1977   return result;
1978 }
1979
1980 /**
1981  * gst_rtsp_client_set_mount_points:
1982  * @client: a #GstRTSPClient
1983  * @mounts: a #GstRTSPMountPoints
1984  *
1985  * Set @mounts as the mount points for @client which it will use to map urls
1986  * to media streams. These mount points are usually inherited from the server that
1987  * created the client but can be overriden later.
1988  */
1989 void
1990 gst_rtsp_client_set_mount_points (GstRTSPClient * client,
1991     GstRTSPMountPoints * mounts)
1992 {
1993   GstRTSPClientPrivate *priv;
1994   GstRTSPMountPoints *old;
1995
1996   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
1997
1998   priv = client->priv;
1999
2000   if (mounts)
2001     g_object_ref (mounts);
2002
2003   g_mutex_lock (&priv->lock);
2004   old = priv->mount_points;
2005   priv->mount_points = mounts;
2006   g_mutex_unlock (&priv->lock);
2007
2008   if (old)
2009     g_object_unref (old);
2010 }
2011
2012 /**
2013  * gst_rtsp_client_get_mount_points:
2014  * @client: a #GstRTSPClient
2015  *
2016  * Get the #GstRTSPMountPoints object that @client uses to manage its sessions.
2017  *
2018  * Returns: (transfer full): a #GstRTSPMountPoints, unref after usage.
2019  */
2020 GstRTSPMountPoints *
2021 gst_rtsp_client_get_mount_points (GstRTSPClient * client)
2022 {
2023   GstRTSPClientPrivate *priv;
2024   GstRTSPMountPoints *result;
2025
2026   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2027
2028   priv = client->priv;
2029
2030   g_mutex_lock (&priv->lock);
2031   if ((result = priv->mount_points))
2032     g_object_ref (result);
2033   g_mutex_unlock (&priv->lock);
2034
2035   return result;
2036 }
2037
2038 /**
2039  * gst_rtsp_client_set_use_client_settings:
2040  * @client: a #GstRTSPClient
2041  * @use_client_settings: whether to use client settings for multicast
2042  *
2043  * Use client transport settings (destination and ttl) for multicast.
2044  * When @use_client_settings is %FALSE, the server settings will be
2045  * used.
2046  */
2047 void
2048 gst_rtsp_client_set_use_client_settings (GstRTSPClient * client,
2049     gboolean use_client_settings)
2050 {
2051   GstRTSPClientPrivate *priv;
2052
2053   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2054
2055   priv = client->priv;
2056
2057   g_mutex_lock (&priv->lock);
2058   priv->use_client_settings = use_client_settings;
2059   g_mutex_unlock (&priv->lock);
2060 }
2061
2062 /**
2063  * gst_rtsp_client_get_use_client_settings:
2064  * @client: a #GstRTSPClient
2065  *
2066  * Check if client transport settings (destination and ttl) for multicast
2067  * will be used.
2068  */
2069 gboolean
2070 gst_rtsp_client_get_use_client_settings (GstRTSPClient * client)
2071 {
2072   GstRTSPClientPrivate *priv;
2073   gboolean res;
2074
2075   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), FALSE);
2076
2077   priv = client->priv;
2078
2079   g_mutex_lock (&priv->lock);
2080   res = priv->use_client_settings;
2081   g_mutex_unlock (&priv->lock);
2082
2083   return res;
2084 }
2085
2086 /**
2087  * gst_rtsp_client_set_auth:
2088  * @client: a #GstRTSPClient
2089  * @auth: a #GstRTSPAuth
2090  *
2091  * configure @auth to be used as the authentication manager of @client.
2092  */
2093 void
2094 gst_rtsp_client_set_auth (GstRTSPClient * client, GstRTSPAuth * auth)
2095 {
2096   GstRTSPClientPrivate *priv;
2097   GstRTSPAuth *old;
2098
2099   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2100
2101   priv = client->priv;
2102
2103   if (auth)
2104     g_object_ref (auth);
2105
2106   g_mutex_lock (&priv->lock);
2107   old = priv->auth;
2108   priv->auth = auth;
2109   g_mutex_unlock (&priv->lock);
2110
2111   if (old)
2112     g_object_unref (old);
2113 }
2114
2115
2116 /**
2117  * gst_rtsp_client_get_auth:
2118  * @client: a #GstRTSPClient
2119  *
2120  * Get the #GstRTSPAuth used as the authentication manager of @client.
2121  *
2122  * Returns: (transfer full): the #GstRTSPAuth of @client. g_object_unref() after
2123  * usage.
2124  */
2125 GstRTSPAuth *
2126 gst_rtsp_client_get_auth (GstRTSPClient * client)
2127 {
2128   GstRTSPClientPrivate *priv;
2129   GstRTSPAuth *result;
2130
2131   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2132
2133   priv = client->priv;
2134
2135   g_mutex_lock (&priv->lock);
2136   if ((result = priv->auth))
2137     g_object_ref (result);
2138   g_mutex_unlock (&priv->lock);
2139
2140   return result;
2141 }
2142
2143 /**
2144  * gst_rtsp_client_set_connection:
2145  * @client: a #GstRTSPClient
2146  * @conn: (transfer full): a #GstRTSPConnection
2147  *
2148  * Set the #GstRTSPConnection of @client. This function takes ownership of
2149  * @conn.
2150  *
2151  * Returns: %TRUE on success.
2152  */
2153 gboolean
2154 gst_rtsp_client_set_connection (GstRTSPClient * client,
2155     GstRTSPConnection * conn)
2156 {
2157   GstRTSPClientPrivate *priv;
2158   GSocket *read_socket;
2159   GSocketAddress *address;
2160   GstRTSPUrl *url;
2161   GError *error = NULL;
2162
2163   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), FALSE);
2164   g_return_val_if_fail (conn != NULL, FALSE);
2165
2166   priv = client->priv;
2167
2168   read_socket = gst_rtsp_connection_get_read_socket (conn);
2169
2170   if (!(address = g_socket_get_local_address (read_socket, &error)))
2171     goto no_address;
2172
2173   g_free (priv->server_ip);
2174   /* keep the original ip that the client connected to */
2175   if (G_IS_INET_SOCKET_ADDRESS (address)) {
2176     GInetAddress *iaddr;
2177
2178     iaddr = g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (address));
2179
2180     /* socket might be ipv6 but adress still ipv4 */
2181     priv->is_ipv6 = g_inet_address_get_family (iaddr) == G_SOCKET_FAMILY_IPV6;
2182     priv->server_ip = g_inet_address_to_string (iaddr);
2183     g_object_unref (address);
2184   } else {
2185     priv->is_ipv6 = g_socket_get_family (read_socket) == G_SOCKET_FAMILY_IPV6;
2186     priv->server_ip = g_strdup ("unknown");
2187   }
2188
2189   GST_INFO ("client %p connected to server ip %s, ipv6 = %d", client,
2190       priv->server_ip, priv->is_ipv6);
2191
2192   url = gst_rtsp_connection_get_url (conn);
2193   GST_INFO ("added new client %p ip %s:%d", client, url->host, url->port);
2194
2195   priv->connection = conn;
2196
2197   return TRUE;
2198
2199   /* ERRORS */
2200 no_address:
2201   {
2202     GST_ERROR ("could not get local address %s", error->message);
2203     g_error_free (error);
2204     return FALSE;
2205   }
2206 }
2207
2208 /**
2209  * gst_rtsp_client_get_connection:
2210  * @client: a #GstRTSPClient
2211  *
2212  * Get the #GstRTSPConnection of @client.
2213  *
2214  * Returns: (transfer none): the #GstRTSPConnection of @client.
2215  * The connection object returned remains valid until the client is freed.
2216  */
2217 GstRTSPConnection *
2218 gst_rtsp_client_get_connection (GstRTSPClient * client)
2219 {
2220   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2221
2222   return client->priv->connection;
2223 }
2224
2225 /**
2226  * gst_rtsp_client_set_send_func:
2227  * @client: a #GstRTSPClient
2228  * @func: a #GstRTSPClientSendFunc
2229  * @user_data: user data passed to @func
2230  * @notify: called when @user_data is no longer in use
2231  *
2232  * Set @func as the callback that will be called when a new message needs to be
2233  * sent to the client. @user_data is passed to @func and @notify is called when
2234  * @user_data is no longer in use.
2235  */
2236 void
2237 gst_rtsp_client_set_send_func (GstRTSPClient * client,
2238     GstRTSPClientSendFunc func, gpointer user_data, GDestroyNotify notify)
2239 {
2240   GstRTSPClientPrivate *priv;
2241   GDestroyNotify old_notify;
2242   gpointer old_data;
2243
2244   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2245
2246   priv = client->priv;
2247
2248   g_mutex_lock (&priv->send_lock);
2249   priv->send_func = func;
2250   old_notify = priv->send_notify;
2251   old_data = priv->send_data;
2252   priv->send_notify = notify;
2253   priv->send_data = user_data;
2254   g_mutex_unlock (&priv->send_lock);
2255
2256   if (old_notify)
2257     old_notify (old_data);
2258 }
2259
2260 /**
2261  * gst_rtsp_client_handle_message:
2262  * @client: a #GstRTSPClient
2263  * @message: an #GstRTSPMessage
2264  *
2265  * Let the client handle @message.
2266  *
2267  * Returns: a #GstRTSPResult.
2268  */
2269 GstRTSPResult
2270 gst_rtsp_client_handle_message (GstRTSPClient * client,
2271     GstRTSPMessage * message)
2272 {
2273   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), GST_RTSP_EINVAL);
2274   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2275
2276   switch (message->type) {
2277     case GST_RTSP_MESSAGE_REQUEST:
2278       handle_request (client, message);
2279       break;
2280     case GST_RTSP_MESSAGE_RESPONSE:
2281       break;
2282     case GST_RTSP_MESSAGE_DATA:
2283       handle_data (client, message);
2284       break;
2285     default:
2286       break;
2287   }
2288   return GST_RTSP_OK;
2289 }
2290
2291 /**
2292  * gst_rtsp_client_send_request:
2293  * @client: a #GstRTSPClient
2294  * @session: a #GstRTSPSession to send the request to or %NULL
2295  * @request: The request #GstRTSPMessage to send
2296  *
2297  * Send a request message to the client.
2298  */
2299 GstRTSPResult
2300 gst_rtsp_client_send_request (GstRTSPClient * client, GstRTSPSession * session,
2301     GstRTSPMessage * request)
2302 {
2303   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), GST_RTSP_EINVAL);
2304   g_return_val_if_fail (request != NULL, GST_RTSP_EINVAL);
2305   g_return_val_if_fail (request->type == GST_RTSP_MESSAGE_REQUEST,
2306       GST_RTSP_EINVAL);
2307
2308   send_message (client, session, request, FALSE);
2309
2310   return GST_RTSP_OK;
2311 }
2312
2313 static GstRTSPResult
2314 do_send_message (GstRTSPClient * client, GstRTSPMessage * message,
2315     gboolean close, gpointer user_data)
2316 {
2317   GstRTSPClientPrivate *priv = client->priv;
2318
2319   /* send the response and store the seq number so we can wait until it's
2320    * written to the client to close the connection */
2321   return gst_rtsp_watch_send_message (priv->watch, message, close ?
2322       &priv->close_seq : NULL);
2323 }
2324
2325 static GstRTSPResult
2326 message_received (GstRTSPWatch * watch, GstRTSPMessage * message,
2327     gpointer user_data)
2328 {
2329   return gst_rtsp_client_handle_message (GST_RTSP_CLIENT (user_data), message);
2330 }
2331
2332 static GstRTSPResult
2333 message_sent (GstRTSPWatch * watch, guint cseq, gpointer user_data)
2334 {
2335   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2336   GstRTSPClientPrivate *priv = client->priv;
2337
2338   if (priv->close_seq && priv->close_seq == cseq) {
2339     priv->close_seq = 0;
2340     close_connection (client);
2341   }
2342
2343   return GST_RTSP_OK;
2344 }
2345
2346 static GstRTSPResult
2347 closed (GstRTSPWatch * watch, gpointer user_data)
2348 {
2349   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2350   GstRTSPClientPrivate *priv = client->priv;
2351   const gchar *tunnelid;
2352
2353   GST_INFO ("client %p: connection closed", client);
2354
2355   if ((tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection))) {
2356     g_mutex_lock (&tunnels_lock);
2357     /* remove from tunnelids */
2358     g_hash_table_remove (tunnels, tunnelid);
2359     g_mutex_unlock (&tunnels_lock);
2360   }
2361
2362   gst_rtsp_client_set_send_func (client, NULL, NULL, NULL);
2363
2364   return GST_RTSP_OK;
2365 }
2366
2367 static GstRTSPResult
2368 error (GstRTSPWatch * watch, GstRTSPResult result, gpointer user_data)
2369 {
2370   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2371   gchar *str;
2372
2373   str = gst_rtsp_strresult (result);
2374   GST_INFO ("client %p: received an error %s", client, str);
2375   g_free (str);
2376
2377   return GST_RTSP_OK;
2378 }
2379
2380 static GstRTSPResult
2381 error_full (GstRTSPWatch * watch, GstRTSPResult result,
2382     GstRTSPMessage * message, guint id, gpointer user_data)
2383 {
2384   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2385   gchar *str;
2386
2387   str = gst_rtsp_strresult (result);
2388   GST_INFO
2389       ("client %p: error when handling message %p with id %d: %s",
2390       client, message, id, str);
2391   g_free (str);
2392
2393   return GST_RTSP_OK;
2394 }
2395
2396 static gboolean
2397 remember_tunnel (GstRTSPClient * client)
2398 {
2399   GstRTSPClientPrivate *priv = client->priv;
2400   const gchar *tunnelid;
2401
2402   /* store client in the pending tunnels */
2403   tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection);
2404   if (tunnelid == NULL)
2405     goto no_tunnelid;
2406
2407   GST_INFO ("client %p: inserting tunnel session %s", client, tunnelid);
2408
2409   /* we can't have two clients connecting with the same tunnelid */
2410   g_mutex_lock (&tunnels_lock);
2411   if (g_hash_table_lookup (tunnels, tunnelid))
2412     goto tunnel_existed;
2413
2414   g_hash_table_insert (tunnels, g_strdup (tunnelid), g_object_ref (client));
2415   g_mutex_unlock (&tunnels_lock);
2416
2417   return TRUE;
2418
2419   /* ERRORS */
2420 no_tunnelid:
2421   {
2422     GST_ERROR ("client %p: no tunnelid provided", client);
2423     return FALSE;
2424   }
2425 tunnel_existed:
2426   {
2427     g_mutex_unlock (&tunnels_lock);
2428     GST_ERROR ("client %p: tunnel session %s already existed", client,
2429         tunnelid);
2430     return FALSE;
2431   }
2432 }
2433
2434 static GstRTSPStatusCode
2435 tunnel_start (GstRTSPWatch * watch, gpointer user_data)
2436 {
2437   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2438   GstRTSPClientPrivate *priv = client->priv;
2439
2440   GST_INFO ("client %p: tunnel start (connection %p)", client,
2441       priv->connection);
2442
2443   if (!remember_tunnel (client))
2444     goto tunnel_error;
2445
2446   return GST_RTSP_STS_OK;
2447
2448   /* ERRORS */
2449 tunnel_error:
2450   {
2451     GST_ERROR ("client %p: error starting tunnel", client);
2452     return GST_RTSP_STS_SERVICE_UNAVAILABLE;
2453   }
2454 }
2455
2456 static GstRTSPResult
2457 tunnel_lost (GstRTSPWatch * watch, gpointer user_data)
2458 {
2459   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2460   GstRTSPClientPrivate *priv = client->priv;
2461
2462   GST_WARNING ("client %p: tunnel lost (connection %p)", client,
2463       priv->connection);
2464
2465   /* ignore error, it'll only be a problem when the client does a POST again */
2466   remember_tunnel (client);
2467
2468   return GST_RTSP_OK;
2469 }
2470
2471 static GstRTSPResult
2472 tunnel_complete (GstRTSPWatch * watch, gpointer user_data)
2473 {
2474   const gchar *tunnelid;
2475   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2476   GstRTSPClientPrivate *priv = client->priv;
2477   GstRTSPClient *oclient;
2478   GstRTSPClientPrivate *opriv;
2479
2480   GST_INFO ("client %p: tunnel complete", client);
2481
2482   /* find previous tunnel */
2483   tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection);
2484   if (tunnelid == NULL)
2485     goto no_tunnelid;
2486
2487   g_mutex_lock (&tunnels_lock);
2488   if (!(oclient = g_hash_table_lookup (tunnels, tunnelid)))
2489     goto no_tunnel;
2490
2491   /* remove the old client from the table. ref before because removing it will
2492    * remove the ref to it. */
2493   g_object_ref (oclient);
2494   g_hash_table_remove (tunnels, tunnelid);
2495
2496   opriv = oclient->priv;
2497
2498   if (opriv->watch == NULL)
2499     goto tunnel_closed;
2500   g_mutex_unlock (&tunnels_lock);
2501
2502   GST_INFO ("client %p: found tunnel %p (old %p, new %p)", client, oclient,
2503       opriv->connection, priv->connection);
2504
2505   /* merge the tunnels into the first client */
2506   gst_rtsp_connection_do_tunnel (opriv->connection, priv->connection);
2507   gst_rtsp_watch_reset (opriv->watch);
2508   g_object_unref (oclient);
2509
2510   return GST_RTSP_OK;
2511
2512   /* ERRORS */
2513 no_tunnelid:
2514   {
2515     GST_ERROR ("client %p: no tunnelid provided", client);
2516     return GST_RTSP_ERROR;
2517   }
2518 no_tunnel:
2519   {
2520     g_mutex_unlock (&tunnels_lock);
2521     GST_ERROR ("client %p: tunnel session %s not found", client, tunnelid);
2522     return GST_RTSP_ERROR;
2523   }
2524 tunnel_closed:
2525   {
2526     g_mutex_unlock (&tunnels_lock);
2527     GST_ERROR ("client %p: tunnel session %s was closed", client, tunnelid);
2528     g_object_unref (oclient);
2529     return GST_RTSP_ERROR;
2530   }
2531 }
2532
2533 static GstRTSPWatchFuncs watch_funcs = {
2534   message_received,
2535   message_sent,
2536   closed,
2537   error,
2538   tunnel_start,
2539   tunnel_complete,
2540   error_full,
2541   tunnel_lost
2542 };
2543
2544 static void
2545 client_watch_notify (GstRTSPClient * client)
2546 {
2547   GstRTSPClientPrivate *priv = client->priv;
2548
2549   GST_INFO ("client %p: watch destroyed", client);
2550   priv->watch = NULL;
2551   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_CLOSED], 0, NULL);
2552   g_object_unref (client);
2553 }
2554
2555 /**
2556  * gst_rtsp_client_attach:
2557  * @client: a #GstRTSPClient
2558  * @context: (allow-none): a #GMainContext
2559  *
2560  * Attaches @client to @context. When the mainloop for @context is run, the
2561  * client will be dispatched. When @context is NULL, the default context will be
2562  * used).
2563  *
2564  * This function should be called when the client properties and urls are fully
2565  * configured and the client is ready to start.
2566  *
2567  * Returns: the ID (greater than 0) for the source within the GMainContext.
2568  */
2569 guint
2570 gst_rtsp_client_attach (GstRTSPClient * client, GMainContext * context)
2571 {
2572   GstRTSPClientPrivate *priv;
2573   guint res;
2574
2575   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), 0);
2576   priv = client->priv;
2577   g_return_val_if_fail (priv->watch == NULL, 0);
2578
2579   /* create watch for the connection and attach */
2580   priv->watch = gst_rtsp_watch_new (priv->connection, &watch_funcs,
2581       g_object_ref (client), (GDestroyNotify) client_watch_notify);
2582   gst_rtsp_client_set_send_func (client, do_send_message, priv->watch,
2583       (GDestroyNotify) gst_rtsp_watch_unref);
2584
2585   /* FIXME make this configurable. We don't want to do this yet because it will
2586    * be superceeded by a cache object later */
2587   gst_rtsp_watch_set_send_backlog (priv->watch, 0, 100);
2588
2589   GST_INFO ("attaching to context %p", context);
2590   res = gst_rtsp_watch_attach (priv->watch, context);
2591
2592   return res;
2593 }
2594
2595 /**
2596  * gst_rtsp_client_session_filter:
2597  * @client: a #GstRTSPclient
2598  * @func: (scope call): a callback
2599  * @user_data: user data passed to @func
2600  *
2601  * Call @func for each session managed by @client. The result value of @func
2602  * determines what happens to the session. @func will be called with @client
2603  * locked so no further actions on @client can be performed from @func.
2604  *
2605  * If @func returns #GST_RTSP_FILTER_REMOVE, the session will be removed from
2606  * @client.
2607  *
2608  * If @func returns #GST_RTSP_FILTER_KEEP, the session will remain in @client.
2609  *
2610  * If @func returns #GST_RTSP_FILTER_REF, the session will remain in @client but
2611  * will also be added with an additional ref to the result #GList of this
2612  * function..
2613  *
2614  * Returns: (element-type GstRTSPSession) (transfer full): a #GList with all
2615  * sessions for which @func returned #GST_RTSP_FILTER_REF. After usage, each
2616  * element in the #GList should be unreffed before the list is freed.
2617  */
2618 GList *
2619 gst_rtsp_client_session_filter (GstRTSPClient * client,
2620     GstRTSPClientSessionFilterFunc func, gpointer user_data)
2621 {
2622   GstRTSPClientPrivate *priv;
2623   GList *result, *walk, *next;
2624
2625   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2626   g_return_val_if_fail (func != NULL, NULL);
2627
2628   priv = client->priv;
2629
2630   result = NULL;
2631
2632   g_mutex_lock (&priv->lock);
2633   for (walk = priv->sessions; walk; walk = next) {
2634     GstRTSPSession *sess = walk->data;
2635
2636     next = g_list_next (walk);
2637
2638     switch (func (client, sess, user_data)) {
2639       case GST_RTSP_FILTER_REMOVE:
2640         /* stop watching the session and pretent it went away */
2641         client_cleanup_session (client, sess);
2642         break;
2643       case GST_RTSP_FILTER_REF:
2644         result = g_list_prepend (result, g_object_ref (sess));
2645         break;
2646       case GST_RTSP_FILTER_KEEP:
2647       default:
2648         break;
2649     }
2650   }
2651   g_mutex_unlock (&priv->lock);
2652
2653   return result;
2654 }