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