client: add state push/pop
[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  * SECTION:rtsp-client
21  * @short_description: A client connection state
22  * @see_also: #GstRTSPServer, #GstRTSPThreadPool
23  *
24  * The client object handles the connection with a client for as long as a TCP
25  * connection is open.
26  *
27  * A #GstRTSPClient is created by #GstRTSPServer when a new connection is
28  * accepted and it inherits the #GstRTSPMountPoints, #GstRTSPSessionPool,
29  * #GstRTSPAuth and #GstRTSPThreadPool from the server.
30  *
31  * The client connection should be configured with the #GstRTSPConnection using
32  * gst_rtsp_client_set_connection() before it can be attached to a #GMainContext
33  * using gst_rtsp_client_attach(). From then on the client will handle requests
34  * on the connection.
35  *
36  * Use gst_rtsp_client_session_filter() to iterate or modify all the
37  * #GstRTSPSession objects managed by the client object.
38  *
39  * Last reviewed on 2013-07-11 (1.0.0)
40  */
41
42 #include <stdio.h>
43 #include <string.h>
44
45 #include "rtsp-client.h"
46 #include "rtsp-sdp.h"
47 #include "rtsp-params.h"
48
49 #define GST_RTSP_CLIENT_GET_PRIVATE(obj)  \
50    (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_RTSP_CLIENT, GstRTSPClientPrivate))
51
52 /* locking order:
53  * send_lock, lock, tunnels_lock
54  */
55
56 struct _GstRTSPClientPrivate
57 {
58   GMutex lock;                  /* protects everything else */
59   GMutex send_lock;
60   GstRTSPConnection *connection;
61   GstRTSPWatch *watch;
62   guint close_seq;
63   gchar *server_ip;
64   gboolean is_ipv6;
65   gboolean use_client_settings;
66
67   GstRTSPClientSendFunc send_func;      /* protected by send_lock */
68   gpointer send_data;           /* protected by send_lock */
69   GDestroyNotify send_notify;   /* protected by send_lock */
70
71   GstRTSPSessionPool *session_pool;
72   GstRTSPMountPoints *mount_points;
73   GstRTSPAuth *auth;
74   GstRTSPThreadPool *thread_pool;
75
76   /* used to cache the media in the last requested DESCRIBE so that
77    * we can pick it up in the next SETUP immediately */
78   gchar *path;
79   GstRTSPMedia *media;
80
81   GList *transports;
82   GList *sessions;
83 };
84
85 static GMutex tunnels_lock;
86 static GHashTable *tunnels;     /* protected by tunnels_lock */
87
88 #define DEFAULT_SESSION_POOL            NULL
89 #define DEFAULT_MOUNT_POINTS            NULL
90 #define DEFAULT_USE_CLIENT_SETTINGS     FALSE
91
92 enum
93 {
94   PROP_0,
95   PROP_SESSION_POOL,
96   PROP_MOUNT_POINTS,
97   PROP_USE_CLIENT_SETTINGS,
98   PROP_LAST
99 };
100
101 enum
102 {
103   SIGNAL_CLOSED,
104   SIGNAL_NEW_SESSION,
105   SIGNAL_OPTIONS_REQUEST,
106   SIGNAL_DESCRIBE_REQUEST,
107   SIGNAL_SETUP_REQUEST,
108   SIGNAL_PLAY_REQUEST,
109   SIGNAL_PAUSE_REQUEST,
110   SIGNAL_TEARDOWN_REQUEST,
111   SIGNAL_SET_PARAMETER_REQUEST,
112   SIGNAL_GET_PARAMETER_REQUEST,
113   SIGNAL_LAST
114 };
115
116 GST_DEBUG_CATEGORY_STATIC (rtsp_client_debug);
117 #define GST_CAT_DEFAULT rtsp_client_debug
118
119 static guint gst_rtsp_client_signals[SIGNAL_LAST] = { 0 };
120
121 static void gst_rtsp_client_get_property (GObject * object, guint propid,
122     GValue * value, GParamSpec * pspec);
123 static void gst_rtsp_client_set_property (GObject * object, guint propid,
124     const GValue * value, GParamSpec * pspec);
125 static void gst_rtsp_client_finalize (GObject * obj);
126
127 static GstSDPMessage *create_sdp (GstRTSPClient * client, GstRTSPMedia * media);
128 static void client_session_finalized (GstRTSPClient * client,
129     GstRTSPSession * session);
130 static void unlink_session_transports (GstRTSPClient * client,
131     GstRTSPSession * session, GstRTSPSessionMedia * sessmedia);
132 static gboolean default_configure_client_transport (GstRTSPClient * client,
133     GstRTSPClientState * state, GstRTSPTransport * ct);
134 static GstRTSPResult default_params_set (GstRTSPClient * client,
135     GstRTSPClientState * state);
136 static GstRTSPResult default_params_get (GstRTSPClient * client,
137     GstRTSPClientState * state);
138
139 G_DEFINE_TYPE (GstRTSPClient, gst_rtsp_client, G_TYPE_OBJECT);
140
141 static void
142 gst_rtsp_client_class_init (GstRTSPClientClass * klass)
143 {
144   GObjectClass *gobject_class;
145
146   g_type_class_add_private (klass, sizeof (GstRTSPClientPrivate));
147
148   gobject_class = G_OBJECT_CLASS (klass);
149
150   gobject_class->get_property = gst_rtsp_client_get_property;
151   gobject_class->set_property = gst_rtsp_client_set_property;
152   gobject_class->finalize = gst_rtsp_client_finalize;
153
154   klass->create_sdp = create_sdp;
155   klass->configure_client_transport = default_configure_client_transport;
156   klass->params_set = default_params_set;
157   klass->params_get = default_params_get;
158
159   g_object_class_install_property (gobject_class, PROP_SESSION_POOL,
160       g_param_spec_object ("session-pool", "Session Pool",
161           "The session pool to use for client session",
162           GST_TYPE_RTSP_SESSION_POOL,
163           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
164
165   g_object_class_install_property (gobject_class, PROP_MOUNT_POINTS,
166       g_param_spec_object ("mount-points", "Mount Points",
167           "The mount points to use for client session",
168           GST_TYPE_RTSP_MOUNT_POINTS,
169           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
170
171   g_object_class_install_property (gobject_class, PROP_USE_CLIENT_SETTINGS,
172       g_param_spec_boolean ("use-client-settings", "Use Client Settings",
173           "Use client settings for ttl and destination in multicast",
174           DEFAULT_USE_CLIENT_SETTINGS,
175           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
176
177   gst_rtsp_client_signals[SIGNAL_CLOSED] =
178       g_signal_new ("closed", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
179       G_STRUCT_OFFSET (GstRTSPClientClass, closed), NULL, NULL,
180       g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0, G_TYPE_NONE);
181
182   gst_rtsp_client_signals[SIGNAL_NEW_SESSION] =
183       g_signal_new ("new-session", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
184       G_STRUCT_OFFSET (GstRTSPClientClass, new_session), NULL, NULL,
185       g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1, GST_TYPE_RTSP_SESSION);
186
187   gst_rtsp_client_signals[SIGNAL_OPTIONS_REQUEST] =
188       g_signal_new ("options-request", G_TYPE_FROM_CLASS (klass),
189       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, options_request),
190       NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1,
191       G_TYPE_POINTER);
192
193   gst_rtsp_client_signals[SIGNAL_DESCRIBE_REQUEST] =
194       g_signal_new ("describe-request", G_TYPE_FROM_CLASS (klass),
195       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, describe_request),
196       NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1,
197       G_TYPE_POINTER);
198
199   gst_rtsp_client_signals[SIGNAL_SETUP_REQUEST] =
200       g_signal_new ("setup-request", G_TYPE_FROM_CLASS (klass),
201       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, setup_request),
202       NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1,
203       G_TYPE_POINTER);
204
205   gst_rtsp_client_signals[SIGNAL_PLAY_REQUEST] =
206       g_signal_new ("play-request", G_TYPE_FROM_CLASS (klass),
207       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, play_request),
208       NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1,
209       G_TYPE_POINTER);
210
211   gst_rtsp_client_signals[SIGNAL_PAUSE_REQUEST] =
212       g_signal_new ("pause-request", G_TYPE_FROM_CLASS (klass),
213       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, pause_request),
214       NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1,
215       G_TYPE_POINTER);
216
217   gst_rtsp_client_signals[SIGNAL_TEARDOWN_REQUEST] =
218       g_signal_new ("teardown-request", G_TYPE_FROM_CLASS (klass),
219       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, teardown_request),
220       NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1,
221       G_TYPE_POINTER);
222
223   gst_rtsp_client_signals[SIGNAL_SET_PARAMETER_REQUEST] =
224       g_signal_new ("set-parameter-request", G_TYPE_FROM_CLASS (klass),
225       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass,
226           set_parameter_request), NULL, NULL, g_cclosure_marshal_VOID__POINTER,
227       G_TYPE_NONE, 1, G_TYPE_POINTER);
228
229   gst_rtsp_client_signals[SIGNAL_GET_PARAMETER_REQUEST] =
230       g_signal_new ("get-parameter-request", G_TYPE_FROM_CLASS (klass),
231       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass,
232           get_parameter_request), NULL, NULL, g_cclosure_marshal_VOID__POINTER,
233       G_TYPE_NONE, 1, G_TYPE_POINTER);
234
235   tunnels =
236       g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_object_unref);
237   g_mutex_init (&tunnels_lock);
238
239   GST_DEBUG_CATEGORY_INIT (rtsp_client_debug, "rtspclient", 0, "GstRTSPClient");
240 }
241
242 static void
243 gst_rtsp_client_init (GstRTSPClient * client)
244 {
245   GstRTSPClientPrivate *priv = GST_RTSP_CLIENT_GET_PRIVATE (client);
246
247   client->priv = priv;
248
249   g_mutex_init (&priv->lock);
250   g_mutex_init (&priv->send_lock);
251   priv->use_client_settings = DEFAULT_USE_CLIENT_SETTINGS;
252   priv->close_seq = 0;
253 }
254
255 static GstRTSPFilterResult
256 filter_session (GstRTSPSession * sess, GstRTSPSessionMedia * sessmedia,
257     gpointer user_data)
258 {
259   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
260
261   gst_rtsp_session_media_set_state (sessmedia, GST_STATE_NULL);
262   unlink_session_transports (client, sess, sessmedia);
263
264   /* unmanage the media in the session */
265   return GST_RTSP_FILTER_REMOVE;
266 }
267
268 static void
269 client_unlink_session (GstRTSPClient * client, GstRTSPSession * session)
270 {
271   /* unlink all media managed in this session */
272   gst_rtsp_session_filter (session, filter_session, client);
273 }
274
275 static void
276 client_watch_session (GstRTSPClient * client, GstRTSPSession * session)
277 {
278   GstRTSPClientPrivate *priv = client->priv;
279   GList *walk;
280
281   for (walk = priv->sessions; walk; walk = g_list_next (walk)) {
282     GstRTSPSession *msession = (GstRTSPSession *) walk->data;
283
284     /* we already know about this session */
285     if (msession == session)
286       return;
287   }
288
289   GST_INFO ("watching session %p", session);
290
291   g_object_weak_ref (G_OBJECT (session), (GWeakNotify) client_session_finalized,
292       client);
293   priv->sessions = g_list_prepend (priv->sessions, session);
294 }
295
296 static void
297 client_unwatch_session (GstRTSPClient * client, GstRTSPSession * session)
298 {
299   GstRTSPClientPrivate *priv = client->priv;
300
301   GST_INFO ("unwatching session %p", session);
302
303   g_object_weak_unref (G_OBJECT (session),
304       (GWeakNotify) client_session_finalized, client);
305   priv->sessions = g_list_remove (priv->sessions, session);
306 }
307
308 static void
309 client_cleanup_session (GstRTSPClient * client, GstRTSPSession * session)
310 {
311   g_object_weak_unref (G_OBJECT (session),
312       (GWeakNotify) client_session_finalized, client);
313   client_unlink_session (client, session);
314 }
315
316 static void
317 client_cleanup_sessions (GstRTSPClient * client)
318 {
319   GstRTSPClientPrivate *priv = client->priv;
320   GList *sessions;
321
322   /* remove weak-ref from sessions */
323   for (sessions = priv->sessions; sessions; sessions = g_list_next (sessions)) {
324     client_cleanup_session (client, (GstRTSPSession *) sessions->data);
325   }
326   g_list_free (priv->sessions);
327   priv->sessions = NULL;
328 }
329
330 /* A client is finalized when the connection is broken */
331 static void
332 gst_rtsp_client_finalize (GObject * obj)
333 {
334   GstRTSPClient *client = GST_RTSP_CLIENT (obj);
335   GstRTSPClientPrivate *priv = client->priv;
336
337   GST_INFO ("finalize client %p", client);
338
339   gst_rtsp_client_set_send_func (client, NULL, NULL, NULL);
340
341   if (priv->watch)
342     g_source_destroy ((GSource *) priv->watch);
343
344   client_cleanup_sessions (client);
345
346   if (priv->connection)
347     gst_rtsp_connection_free (priv->connection);
348   if (priv->session_pool)
349     g_object_unref (priv->session_pool);
350   if (priv->mount_points)
351     g_object_unref (priv->mount_points);
352   if (priv->auth)
353     g_object_unref (priv->auth);
354
355   if (priv->path)
356     g_free (priv->path);
357   if (priv->media) {
358     gst_rtsp_media_unprepare (priv->media);
359     g_object_unref (priv->media);
360   }
361
362   g_free (priv->server_ip);
363   g_mutex_clear (&priv->lock);
364   g_mutex_clear (&priv->send_lock);
365
366   G_OBJECT_CLASS (gst_rtsp_client_parent_class)->finalize (obj);
367 }
368
369 static void
370 gst_rtsp_client_get_property (GObject * object, guint propid,
371     GValue * value, GParamSpec * pspec)
372 {
373   GstRTSPClient *client = GST_RTSP_CLIENT (object);
374
375   switch (propid) {
376     case PROP_SESSION_POOL:
377       g_value_take_object (value, gst_rtsp_client_get_session_pool (client));
378       break;
379     case PROP_MOUNT_POINTS:
380       g_value_take_object (value, gst_rtsp_client_get_mount_points (client));
381       break;
382     case PROP_USE_CLIENT_SETTINGS:
383       g_value_set_boolean (value,
384           gst_rtsp_client_get_use_client_settings (client));
385       break;
386     default:
387       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, propid, pspec);
388   }
389 }
390
391 static void
392 gst_rtsp_client_set_property (GObject * object, guint propid,
393     const GValue * value, GParamSpec * pspec)
394 {
395   GstRTSPClient *client = GST_RTSP_CLIENT (object);
396
397   switch (propid) {
398     case PROP_SESSION_POOL:
399       gst_rtsp_client_set_session_pool (client, g_value_get_object (value));
400       break;
401     case PROP_MOUNT_POINTS:
402       gst_rtsp_client_set_mount_points (client, g_value_get_object (value));
403       break;
404     case PROP_USE_CLIENT_SETTINGS:
405       gst_rtsp_client_set_use_client_settings (client,
406           g_value_get_boolean (value));
407       break;
408     default:
409       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, propid, pspec);
410   }
411 }
412
413 /**
414  * gst_rtsp_client_new:
415  *
416  * Create a new #GstRTSPClient instance.
417  *
418  * Returns: a new #GstRTSPClient
419  */
420 GstRTSPClient *
421 gst_rtsp_client_new (void)
422 {
423   GstRTSPClient *result;
424
425   result = g_object_new (GST_TYPE_RTSP_CLIENT, NULL);
426
427   return result;
428 }
429
430 static void
431 send_message (GstRTSPClient * client, GstRTSPSession * session,
432     GstRTSPMessage * message, gboolean close)
433 {
434   GstRTSPClientPrivate *priv = client->priv;
435
436   gst_rtsp_message_add_header (message, GST_RTSP_HDR_SERVER,
437       "GStreamer RTSP server");
438
439   /* remove any previous header */
440   gst_rtsp_message_remove_header (message, GST_RTSP_HDR_SESSION, -1);
441
442   /* add the new session header for new session ids */
443   if (session) {
444     gst_rtsp_message_take_header (message, GST_RTSP_HDR_SESSION,
445         gst_rtsp_session_get_header (session));
446   }
447
448   if (gst_debug_category_get_threshold (rtsp_client_debug) >= GST_LEVEL_LOG) {
449     gst_rtsp_message_dump (message);
450   }
451
452   if (close)
453     gst_rtsp_message_add_header (message, GST_RTSP_HDR_CONNECTION, "close");
454
455   g_mutex_lock (&priv->send_lock);
456   if (priv->send_func)
457     priv->send_func (client, message, close, priv->send_data);
458   g_mutex_unlock (&priv->send_lock);
459
460   gst_rtsp_message_unset (message);
461 }
462
463 static void
464 send_generic_response (GstRTSPClient * client, GstRTSPStatusCode code,
465     GstRTSPClientState * state)
466 {
467   gst_rtsp_message_init_response (state->response, code,
468       gst_rtsp_status_as_text (code), state->request);
469
470   send_message (client, NULL, state->response, FALSE);
471 }
472
473 static void
474 handle_unauthorized_request (GstRTSPClient * client, GstRTSPAuth * auth,
475     GstRTSPClientState * state)
476 {
477   gst_rtsp_message_init_response (state->response, GST_RTSP_STS_UNAUTHORIZED,
478       gst_rtsp_status_as_text (GST_RTSP_STS_UNAUTHORIZED), state->request);
479
480   if (auth) {
481     /* and let the authentication manager setup the auth tokens */
482     gst_rtsp_auth_setup (auth, state);
483   }
484
485   send_message (client, state->session, state->response, FALSE);
486 }
487
488
489 static gboolean
490 paths_are_equal (const gchar * path1, const gchar * path2, gint len2)
491 {
492   if (path1 == NULL || path2 == NULL)
493     return FALSE;
494
495   if (strlen (path1) != len2)
496     return FALSE;
497
498   if (strncmp (path1, path2, len2))
499     return FALSE;
500
501   return TRUE;
502 }
503
504 /* this function is called to initially find the media for the DESCRIBE request
505  * but is cached for when the same client (without breaking the connection) is
506  * doing a setup for the exact same url. */
507 static GstRTSPMedia *
508 find_media (GstRTSPClient * client, GstRTSPClientState * state, gint * matched)
509 {
510   GstRTSPClientPrivate *priv = client->priv;
511   GstRTSPMediaFactory *factory;
512   GstRTSPMedia *media;
513   gchar *path;
514   gint path_len;
515
516   if (!priv->mount_points)
517     goto no_mount_points;
518
519   path = state->uri->abspath;
520
521   /* find the longest matching factory for the uri first */
522   if (!(factory = gst_rtsp_mount_points_match (priv->mount_points,
523               path, matched)))
524     goto no_factory;
525
526   state->factory = factory;
527
528   if (!gst_rtsp_auth_check (GST_RTSP_AUTH_CHECK_MEDIA_FACTORY_ACCESS))
529     goto no_factory_access;
530
531   if (!gst_rtsp_auth_check (GST_RTSP_AUTH_CHECK_MEDIA_FACTORY_CONSTRUCT))
532     goto not_authorized;
533
534   if (matched)
535     path_len = *matched;
536   else
537     path_len = strlen (path);
538
539   if (!paths_are_equal (priv->path, path, path_len)) {
540     GstRTSPThread *thread;
541
542     /* remove any previously cached values before we try to construct a new
543      * media for uri */
544     if (priv->path)
545       g_free (priv->path);
546     priv->path = NULL;
547     if (priv->media) {
548       gst_rtsp_media_unprepare (priv->media);
549       g_object_unref (priv->media);
550     }
551     priv->media = NULL;
552
553     /* prepare the media and add it to the pipeline */
554     if (!(media = gst_rtsp_media_factory_construct (factory, state->uri)))
555       goto no_media;
556
557     state->media = media;
558
559     thread = gst_rtsp_thread_pool_get_thread (priv->thread_pool,
560         GST_RTSP_THREAD_TYPE_MEDIA, state);
561     if (thread == NULL)
562       goto no_thread;
563
564     /* prepare the media */
565     if (!(gst_rtsp_media_prepare (media, thread)))
566       goto no_prepare;
567
568     /* now keep track of the uri and the media */
569     priv->path = g_strndup (path, path_len);
570     priv->media = media;
571   } else {
572     /* we have seen this path before, used cached media */
573     media = priv->media;
574     state->media = media;
575     GST_INFO ("reusing cached media %p for path %s", media, priv->path);
576   }
577
578   g_object_unref (factory);
579   state->factory = NULL;
580
581   if (media)
582     g_object_ref (media);
583
584   return media;
585
586   /* ERRORS */
587 no_mount_points:
588   {
589     GST_ERROR ("client %p: no mount points configured", client);
590     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, state);
591     return NULL;
592   }
593 no_factory:
594   {
595     GST_ERROR ("client %p: no factory for uri %s", client, path);
596     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, state);
597     return NULL;
598   }
599 no_factory_access:
600   {
601     GST_ERROR ("client %p: not authorized to see factory uri %s", client, path);
602     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, state);
603     return NULL;
604   }
605 not_authorized:
606   {
607     GST_ERROR ("client %p: not authorized for factory uri %s", client, path);
608     handle_unauthorized_request (client, priv->auth, state);
609     return NULL;
610   }
611 no_media:
612   {
613     GST_ERROR ("client %p: can't create media", client);
614     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, state);
615     g_object_unref (factory);
616     state->factory = NULL;
617     return NULL;
618   }
619 no_thread:
620   {
621     GST_ERROR ("client %p: can't create thread", client);
622     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, state);
623     g_object_unref (media);
624     state->media = NULL;
625     g_object_unref (factory);
626     state->factory = NULL;
627     return NULL;
628   }
629 no_prepare:
630   {
631     GST_ERROR ("client %p: can't prepare media", client);
632     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, state);
633     g_object_unref (media);
634     state->media = NULL;
635     g_object_unref (factory);
636     state->factory = NULL;
637     return NULL;
638   }
639 }
640
641 static gboolean
642 do_send_data (GstBuffer * buffer, guint8 channel, GstRTSPClient * client)
643 {
644   GstRTSPClientPrivate *priv = client->priv;
645   GstRTSPMessage message = { 0 };
646   GstMapInfo map_info;
647   guint8 *data;
648   guint usize;
649
650   gst_rtsp_message_init_data (&message, channel);
651
652   /* FIXME, need some sort of iovec RTSPMessage here */
653   if (!gst_buffer_map (buffer, &map_info, GST_MAP_READ))
654     return FALSE;
655
656   gst_rtsp_message_take_body (&message, map_info.data, map_info.size);
657
658   g_mutex_lock (&priv->send_lock);
659   if (priv->send_func)
660     priv->send_func (client, &message, FALSE, priv->send_data);
661   g_mutex_unlock (&priv->send_lock);
662
663   gst_rtsp_message_steal_body (&message, &data, &usize);
664   gst_buffer_unmap (buffer, &map_info);
665
666   gst_rtsp_message_unset (&message);
667
668   return TRUE;
669 }
670
671 static void
672 link_transport (GstRTSPClient * client, GstRTSPSession * session,
673     GstRTSPStreamTransport * trans)
674 {
675   GstRTSPClientPrivate *priv = client->priv;
676
677   GST_DEBUG ("client %p: linking transport %p", client, trans);
678
679   gst_rtsp_stream_transport_set_callbacks (trans,
680       (GstRTSPSendFunc) do_send_data,
681       (GstRTSPSendFunc) do_send_data, client, NULL);
682
683   priv->transports = g_list_prepend (priv->transports, trans);
684
685   /* make sure our session can't expire */
686   gst_rtsp_session_prevent_expire (session);
687 }
688
689 static void
690 unlink_transport (GstRTSPClient * client, GstRTSPSession * session,
691     GstRTSPStreamTransport * trans)
692 {
693   GstRTSPClientPrivate *priv = client->priv;
694
695   GST_DEBUG ("client %p: unlinking transport %p", client, trans);
696
697   gst_rtsp_stream_transport_set_callbacks (trans, NULL, NULL, NULL, NULL);
698
699   priv->transports = g_list_remove (priv->transports, trans);
700
701   /* our session can now expire */
702   gst_rtsp_session_allow_expire (session);
703 }
704
705 static void
706 unlink_session_transports (GstRTSPClient * client, GstRTSPSession * session,
707     GstRTSPSessionMedia * sessmedia)
708 {
709   guint n_streams, i;
710
711   n_streams =
712       gst_rtsp_media_n_streams (gst_rtsp_session_media_get_media (sessmedia));
713   for (i = 0; i < n_streams; i++) {
714     GstRTSPStreamTransport *trans;
715     const GstRTSPTransport *tr;
716
717     /* get the transport, if there is no transport configured, skip this stream */
718     trans = gst_rtsp_session_media_get_transport (sessmedia, i);
719     if (trans == NULL)
720       continue;
721
722     tr = gst_rtsp_stream_transport_get_transport (trans);
723
724     if (tr->lower_transport == GST_RTSP_LOWER_TRANS_TCP) {
725       /* for TCP, unlink the stream from the TCP connection of the client */
726       unlink_transport (client, session, trans);
727     }
728   }
729 }
730
731 static void
732 close_connection (GstRTSPClient * client)
733 {
734   GstRTSPClientPrivate *priv = client->priv;
735   const gchar *tunnelid;
736
737   GST_DEBUG ("client %p: closing connection", client);
738
739   if ((tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection))) {
740     g_mutex_lock (&tunnels_lock);
741     /* remove from tunnelids */
742     g_hash_table_remove (tunnels, tunnelid);
743     g_mutex_unlock (&tunnels_lock);
744   }
745
746   gst_rtsp_connection_close (priv->connection);
747 }
748
749 static gboolean
750 handle_teardown_request (GstRTSPClient * client, GstRTSPClientState * state)
751 {
752   GstRTSPClientPrivate *priv = client->priv;
753   GstRTSPSession *session;
754   GstRTSPSessionMedia *sessmedia;
755   GstRTSPStatusCode code;
756   const gchar *path;
757   gint matched;
758
759   if (!state->session)
760     goto no_session;
761
762   session = state->session;
763
764   if (!state->uri)
765     goto no_uri;
766
767   path = state->uri->abspath;
768
769   /* get a handle to the configuration of the media in the session */
770   sessmedia = gst_rtsp_session_get_media (session, path, &matched);
771   if (!sessmedia)
772     goto not_found;
773
774   /* only aggregate control for now.. */
775   if (path[matched] != '\0')
776     goto no_aggregate;
777
778   state->sessmedia = sessmedia;
779
780   /* we emit the signal before closing the connection */
781   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_TEARDOWN_REQUEST],
782       0, state);
783
784   /* unlink the all TCP callbacks */
785   unlink_session_transports (client, session, sessmedia);
786
787   /* remove the session from the watched sessions */
788   client_unwatch_session (client, session);
789
790   gst_rtsp_session_media_set_state (sessmedia, GST_STATE_NULL);
791
792   /* unmanage the media in the session, returns false if all media session
793    * are torn down. */
794   if (!gst_rtsp_session_release_media (session, sessmedia)) {
795     /* remove the session */
796     gst_rtsp_session_pool_remove (priv->session_pool, session);
797   }
798   /* construct the response now */
799   code = GST_RTSP_STS_OK;
800   gst_rtsp_message_init_response (state->response, code,
801       gst_rtsp_status_as_text (code), state->request);
802
803   send_message (client, session, state->response, TRUE);
804
805   return TRUE;
806
807   /* ERRORS */
808 no_session:
809   {
810     GST_ERROR ("client %p: no session", client);
811     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, state);
812     return FALSE;
813   }
814 no_uri:
815   {
816     GST_ERROR ("client %p: no uri supplied", client);
817     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, state);
818     return FALSE;
819   }
820 not_found:
821   {
822     GST_ERROR ("client %p: no media for uri", client);
823     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, state);
824     return FALSE;
825   }
826 no_aggregate:
827   {
828     GST_ERROR ("client %p: no aggregate path %s", client, path);
829     send_generic_response (client,
830         GST_RTSP_STS_ONLY_AGGREGATE_OPERATION_ALLOWED, state);
831     return FALSE;
832   }
833 }
834
835 static GstRTSPResult
836 default_params_set (GstRTSPClient * client, GstRTSPClientState * state)
837 {
838   GstRTSPResult res;
839
840   res = gst_rtsp_params_set (client, state);
841
842   return res;
843 }
844
845 static GstRTSPResult
846 default_params_get (GstRTSPClient * client, GstRTSPClientState * state)
847 {
848   GstRTSPResult res;
849
850   res = gst_rtsp_params_get (client, state);
851
852   return res;
853 }
854
855 static gboolean
856 handle_get_param_request (GstRTSPClient * client, GstRTSPClientState * state)
857 {
858   GstRTSPResult res;
859   guint8 *data;
860   guint size;
861
862   res = gst_rtsp_message_get_body (state->request, &data, &size);
863   if (res != GST_RTSP_OK)
864     goto bad_request;
865
866   if (size == 0) {
867     /* no body, keep-alive request */
868     send_generic_response (client, GST_RTSP_STS_OK, state);
869   } else {
870     /* there is a body, handle the params */
871     res = GST_RTSP_CLIENT_GET_CLASS (client)->params_get (client, state);
872     if (res != GST_RTSP_OK)
873       goto bad_request;
874
875     send_message (client, state->session, state->response, FALSE);
876   }
877
878   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_GET_PARAMETER_REQUEST],
879       0, state);
880
881   return TRUE;
882
883   /* ERRORS */
884 bad_request:
885   {
886     GST_ERROR ("client %p: bad request", client);
887     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, state);
888     return FALSE;
889   }
890 }
891
892 static gboolean
893 handle_set_param_request (GstRTSPClient * client, GstRTSPClientState * state)
894 {
895   GstRTSPResult res;
896   guint8 *data;
897   guint size;
898
899   res = gst_rtsp_message_get_body (state->request, &data, &size);
900   if (res != GST_RTSP_OK)
901     goto bad_request;
902
903   if (size == 0) {
904     /* no body, keep-alive request */
905     send_generic_response (client, GST_RTSP_STS_OK, state);
906   } else {
907     /* there is a body, handle the params */
908     res = GST_RTSP_CLIENT_GET_CLASS (client)->params_set (client, state);
909     if (res != GST_RTSP_OK)
910       goto bad_request;
911
912     send_message (client, state->session, state->response, FALSE);
913   }
914
915   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_SET_PARAMETER_REQUEST],
916       0, state);
917
918   return TRUE;
919
920   /* ERRORS */
921 bad_request:
922   {
923     GST_ERROR ("client %p: bad request", client);
924     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, state);
925     return FALSE;
926   }
927 }
928
929 static gboolean
930 handle_pause_request (GstRTSPClient * client, GstRTSPClientState * state)
931 {
932   GstRTSPSession *session;
933   GstRTSPSessionMedia *sessmedia;
934   GstRTSPStatusCode code;
935   GstRTSPState rtspstate;
936   const gchar *path;
937   gint matched;
938
939   if (!(session = state->session))
940     goto no_session;
941
942   if (!state->uri)
943     goto no_uri;
944
945   path = state->uri->abspath;
946
947   /* get a handle to the configuration of the media in the session */
948   sessmedia = gst_rtsp_session_get_media (session, path, &matched);
949   if (!sessmedia)
950     goto not_found;
951
952   if (path[matched] != '\0')
953     goto no_aggregate;
954
955   state->sessmedia = sessmedia;
956
957   rtspstate = gst_rtsp_session_media_get_rtsp_state (sessmedia);
958   /* the session state must be playing or recording */
959   if (rtspstate != GST_RTSP_STATE_PLAYING &&
960       rtspstate != GST_RTSP_STATE_RECORDING)
961     goto invalid_state;
962
963   /* unlink the all TCP callbacks */
964   unlink_session_transports (client, session, sessmedia);
965
966   /* then pause sending */
967   gst_rtsp_session_media_set_state (sessmedia, GST_STATE_PAUSED);
968
969   /* construct the response now */
970   code = GST_RTSP_STS_OK;
971   gst_rtsp_message_init_response (state->response, code,
972       gst_rtsp_status_as_text (code), state->request);
973
974   send_message (client, session, state->response, FALSE);
975
976   /* the state is now READY */
977   gst_rtsp_session_media_set_rtsp_state (sessmedia, GST_RTSP_STATE_READY);
978
979   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_PAUSE_REQUEST],
980       0, state);
981
982   return TRUE;
983
984   /* ERRORS */
985 no_session:
986   {
987     GST_ERROR ("client %p: no seesion", client);
988     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, state);
989     return FALSE;
990   }
991 no_uri:
992   {
993     GST_ERROR ("client %p: no uri supplied", client);
994     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, state);
995     return FALSE;
996   }
997 not_found:
998   {
999     GST_ERROR ("client %p: no media for uri", client);
1000     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, state);
1001     return FALSE;
1002   }
1003 no_aggregate:
1004   {
1005     GST_ERROR ("client %p: no aggregate path %s", client, path);
1006     send_generic_response (client,
1007         GST_RTSP_STS_ONLY_AGGREGATE_OPERATION_ALLOWED, state);
1008     return FALSE;
1009   }
1010 invalid_state:
1011   {
1012     GST_ERROR ("client %p: not PLAYING or RECORDING", client);
1013     send_generic_response (client, GST_RTSP_STS_METHOD_NOT_VALID_IN_THIS_STATE,
1014         state);
1015     return FALSE;
1016   }
1017 }
1018
1019 static gboolean
1020 handle_play_request (GstRTSPClient * client, GstRTSPClientState * state)
1021 {
1022   GstRTSPSession *session;
1023   GstRTSPSessionMedia *sessmedia;
1024   GstRTSPMedia *media;
1025   GstRTSPStatusCode code;
1026   GString *rtpinfo;
1027   guint n_streams, i, infocount;
1028   gchar *str;
1029   GstRTSPTimeRange *range;
1030   GstRTSPResult res;
1031   GstRTSPState rtspstate;
1032   GstRTSPRangeUnit unit = GST_RTSP_RANGE_NPT;
1033   const gchar *path;
1034   gint matched;
1035
1036   if (!(session = state->session))
1037     goto no_session;
1038
1039   if (!state->uri)
1040     goto no_uri;
1041
1042   path = state->uri->abspath;
1043
1044   /* get a handle to the configuration of the media in the session */
1045   sessmedia = gst_rtsp_session_get_media (session, path, &matched);
1046   if (!sessmedia)
1047     goto not_found;
1048
1049   if (path[matched] != '\0')
1050     goto no_aggregate;
1051
1052   state->sessmedia = sessmedia;
1053   state->media = media = gst_rtsp_session_media_get_media (sessmedia);
1054
1055   /* the session state must be playing or ready */
1056   rtspstate = gst_rtsp_session_media_get_rtsp_state (sessmedia);
1057   if (rtspstate != GST_RTSP_STATE_PLAYING && rtspstate != GST_RTSP_STATE_READY)
1058     goto invalid_state;
1059
1060   /* parse the range header if we have one */
1061   res =
1062       gst_rtsp_message_get_header (state->request, GST_RTSP_HDR_RANGE, &str, 0);
1063   if (res == GST_RTSP_OK) {
1064     if (gst_rtsp_range_parse (str, &range) == GST_RTSP_OK) {
1065       /* we have a range, seek to the position */
1066       unit = range->unit;
1067       gst_rtsp_media_seek (media, range);
1068       gst_rtsp_range_free (range);
1069     }
1070   }
1071
1072   /* grab RTPInfo from the payloaders now */
1073   rtpinfo = g_string_new ("");
1074
1075   n_streams = gst_rtsp_media_n_streams (media);
1076   for (i = 0, infocount = 0; i < n_streams; i++) {
1077     GstRTSPStreamTransport *trans;
1078     GstRTSPStream *stream;
1079     const GstRTSPTransport *tr;
1080     gchar *uristr;
1081     guint rtptime, seq;
1082
1083     /* get the transport, if there is no transport configured, skip this stream */
1084     trans = gst_rtsp_session_media_get_transport (sessmedia, i);
1085     if (trans == NULL) {
1086       GST_INFO ("stream %d is not configured", i);
1087       continue;
1088     }
1089     tr = gst_rtsp_stream_transport_get_transport (trans);
1090
1091     if (tr->lower_transport == GST_RTSP_LOWER_TRANS_TCP) {
1092       /* for TCP, link the stream to the TCP connection of the client */
1093       link_transport (client, session, trans);
1094     }
1095
1096     stream = gst_rtsp_stream_transport_get_stream (trans);
1097     if (gst_rtsp_stream_get_rtpinfo (stream, &rtptime, &seq)) {
1098       if (infocount > 0)
1099         g_string_append (rtpinfo, ", ");
1100
1101       uristr = gst_rtsp_url_get_request_uri (state->uri);
1102       g_string_append_printf (rtpinfo, "url=%s/stream=%d;seq=%u;rtptime=%u",
1103           uristr, i, seq, rtptime);
1104       g_free (uristr);
1105
1106       infocount++;
1107     } else {
1108       GST_WARNING ("RTP-Info cannot be determined for stream %d", i);
1109     }
1110   }
1111
1112   /* construct the response now */
1113   code = GST_RTSP_STS_OK;
1114   gst_rtsp_message_init_response (state->response, code,
1115       gst_rtsp_status_as_text (code), state->request);
1116
1117   /* add the RTP-Info header */
1118   if (infocount > 0) {
1119     str = g_string_free (rtpinfo, FALSE);
1120     gst_rtsp_message_take_header (state->response, GST_RTSP_HDR_RTP_INFO, str);
1121   } else {
1122     g_string_free (rtpinfo, TRUE);
1123   }
1124
1125   /* add the range */
1126   str = gst_rtsp_media_get_range_string (media, TRUE, unit);
1127   gst_rtsp_message_take_header (state->response, GST_RTSP_HDR_RANGE, str);
1128
1129   send_message (client, session, state->response, FALSE);
1130
1131   /* start playing after sending the request */
1132   gst_rtsp_session_media_set_state (sessmedia, GST_STATE_PLAYING);
1133
1134   gst_rtsp_session_media_set_rtsp_state (sessmedia, GST_RTSP_STATE_PLAYING);
1135
1136   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_PLAY_REQUEST],
1137       0, state);
1138
1139   return TRUE;
1140
1141   /* ERRORS */
1142 no_session:
1143   {
1144     GST_ERROR ("client %p: no session", client);
1145     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, state);
1146     return FALSE;
1147   }
1148 no_uri:
1149   {
1150     GST_ERROR ("client %p: no uri supplied", client);
1151     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, state);
1152     return FALSE;
1153   }
1154 not_found:
1155   {
1156     GST_ERROR ("client %p: media not found", client);
1157     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, state);
1158     return FALSE;
1159   }
1160 no_aggregate:
1161   {
1162     GST_ERROR ("client %p: no aggregate path %s", client, path);
1163     send_generic_response (client,
1164         GST_RTSP_STS_ONLY_AGGREGATE_OPERATION_ALLOWED, state);
1165     return FALSE;
1166   }
1167 invalid_state:
1168   {
1169     GST_ERROR ("client %p: not PLAYING or READY", client);
1170     send_generic_response (client, GST_RTSP_STS_METHOD_NOT_VALID_IN_THIS_STATE,
1171         state);
1172     return FALSE;
1173   }
1174 }
1175
1176 static void
1177 do_keepalive (GstRTSPSession * session)
1178 {
1179   GST_INFO ("keep session %p alive", session);
1180   gst_rtsp_session_touch (session);
1181 }
1182
1183 /* parse @transport and return a valid transport in @tr. only transports
1184  * from @supported are returned. Returns FALSE if no valid transport
1185  * was found. */
1186 static gboolean
1187 parse_transport (const char *transport, GstRTSPLowerTrans supported,
1188     GstRTSPTransport * tr)
1189 {
1190   gint i;
1191   gboolean res;
1192   gchar **transports;
1193
1194   res = FALSE;
1195   gst_rtsp_transport_init (tr);
1196
1197   GST_DEBUG ("parsing transports %s", transport);
1198
1199   transports = g_strsplit (transport, ",", 0);
1200
1201   /* loop through the transports, try to parse */
1202   for (i = 0; transports[i]; i++) {
1203     res = gst_rtsp_transport_parse (transports[i], tr);
1204     if (res != GST_RTSP_OK) {
1205       /* no valid transport, search some more */
1206       GST_WARNING ("could not parse transport %s", transports[i]);
1207       goto next;
1208     }
1209
1210     /* we have a transport, see if it's RTP/AVP */
1211     if (tr->trans != GST_RTSP_TRANS_RTP || tr->profile != GST_RTSP_PROFILE_AVP) {
1212       GST_WARNING ("invalid transport %s", transports[i]);
1213       goto next;
1214     }
1215
1216     if (!(tr->lower_transport & supported)) {
1217       GST_WARNING ("unsupported transport %s", transports[i]);
1218       goto next;
1219     }
1220
1221     /* we have a valid transport */
1222     GST_INFO ("found valid transport %s", transports[i]);
1223     res = TRUE;
1224     break;
1225
1226   next:
1227     gst_rtsp_transport_init (tr);
1228   }
1229   g_strfreev (transports);
1230
1231   return res;
1232 }
1233
1234 static gboolean
1235 handle_blocksize (GstRTSPMedia * media, GstRTSPStream * stream,
1236     GstRTSPMessage * request)
1237 {
1238   gchar *blocksize_str;
1239   gboolean ret = TRUE;
1240
1241   if (gst_rtsp_message_get_header (request, GST_RTSP_HDR_BLOCKSIZE,
1242           &blocksize_str, 0) == GST_RTSP_OK) {
1243     guint64 blocksize;
1244     gchar *end;
1245
1246     blocksize = g_ascii_strtoull (blocksize_str, &end, 10);
1247     if (end == blocksize_str) {
1248       GST_ERROR ("failed to parse blocksize");
1249       ret = FALSE;
1250     } else {
1251       /* we don't want to change the mtu when this media
1252        * can be shared because it impacts other clients */
1253       if (gst_rtsp_media_is_shared (media))
1254         return TRUE;
1255
1256       if (blocksize > G_MAXUINT)
1257         blocksize = G_MAXUINT;
1258       gst_rtsp_stream_set_mtu (stream, blocksize);
1259     }
1260   }
1261   return ret;
1262 }
1263
1264 static gboolean
1265 default_configure_client_transport (GstRTSPClient * client,
1266     GstRTSPClientState * state, GstRTSPTransport * ct)
1267 {
1268   GstRTSPClientPrivate *priv = client->priv;
1269
1270   /* we have a valid transport now, set the destination of the client. */
1271   if (ct->lower_transport == GST_RTSP_LOWER_TRANS_UDP_MCAST) {
1272     if (ct->destination && priv->use_client_settings) {
1273       GstRTSPAddress *addr;
1274
1275       addr = gst_rtsp_stream_reserve_address (state->stream, ct->destination,
1276           ct->port.min, ct->port.max - ct->port.min + 1, ct->ttl);
1277
1278       if (addr == NULL)
1279         goto no_address;
1280
1281       gst_rtsp_address_free (addr);
1282     } else {
1283       GstRTSPAddress *addr;
1284       GSocketFamily family;
1285
1286       family = priv->is_ipv6 ? G_SOCKET_FAMILY_IPV6 : G_SOCKET_FAMILY_IPV4;
1287
1288       addr = gst_rtsp_stream_get_multicast_address (state->stream, family);
1289       if (addr == NULL)
1290         goto no_address;
1291
1292       g_free (ct->destination);
1293       ct->destination = g_strdup (addr->address);
1294       ct->port.min = addr->port;
1295       ct->port.max = addr->port + addr->n_ports - 1;
1296       ct->ttl = addr->ttl;
1297
1298       gst_rtsp_address_free (addr);
1299     }
1300   } else {
1301     GstRTSPUrl *url;
1302
1303     url = gst_rtsp_connection_get_url (priv->connection);
1304     g_free (ct->destination);
1305     ct->destination = g_strdup (url->host);
1306
1307     if (ct->lower_transport & GST_RTSP_LOWER_TRANS_TCP) {
1308       /* check if the client selected channels for TCP */
1309       if (ct->interleaved.min == -1 || ct->interleaved.max == -1) {
1310         gst_rtsp_session_media_alloc_channels (state->sessmedia,
1311             &ct->interleaved);
1312       }
1313     }
1314   }
1315   return TRUE;
1316
1317   /* ERRORS */
1318 no_address:
1319   {
1320     GST_ERROR_OBJECT (client, "failed to acquire address for stream");
1321     return FALSE;
1322   }
1323 }
1324
1325 static GstRTSPTransport *
1326 make_server_transport (GstRTSPClient * client, GstRTSPClientState * state,
1327     GstRTSPTransport * ct)
1328 {
1329   GstRTSPTransport *st;
1330   GInetAddress *addr;
1331   GSocketFamily family;
1332
1333   /* prepare the server transport */
1334   gst_rtsp_transport_new (&st);
1335
1336   st->trans = ct->trans;
1337   st->profile = ct->profile;
1338   st->lower_transport = ct->lower_transport;
1339
1340   addr = g_inet_address_new_from_string (ct->destination);
1341
1342   if (!addr) {
1343     GST_ERROR ("failed to get inet addr from client destination");
1344     family = G_SOCKET_FAMILY_IPV4;
1345   } else {
1346     family = g_inet_address_get_family (addr);
1347     g_object_unref (addr);
1348     addr = NULL;
1349   }
1350
1351   switch (st->lower_transport) {
1352     case GST_RTSP_LOWER_TRANS_UDP:
1353       st->client_port = ct->client_port;
1354       gst_rtsp_stream_get_server_port (state->stream, &st->server_port, family);
1355       break;
1356     case GST_RTSP_LOWER_TRANS_UDP_MCAST:
1357       st->port = ct->port;
1358       st->destination = g_strdup (ct->destination);
1359       st->ttl = ct->ttl;
1360       break;
1361     case GST_RTSP_LOWER_TRANS_TCP:
1362       st->interleaved = ct->interleaved;
1363     default:
1364       break;
1365   }
1366
1367   gst_rtsp_stream_get_ssrc (state->stream, &st->ssrc);
1368
1369   return st;
1370 }
1371
1372 static gboolean
1373 handle_setup_request (GstRTSPClient * client, GstRTSPClientState * state)
1374 {
1375   GstRTSPClientPrivate *priv = client->priv;
1376   GstRTSPResult res;
1377   GstRTSPUrl *uri;
1378   gchar *transport;
1379   GstRTSPTransport *ct, *st;
1380   GstRTSPLowerTrans supported;
1381   GstRTSPStatusCode code;
1382   GstRTSPSession *session;
1383   GstRTSPStreamTransport *trans;
1384   gchar *trans_str;
1385   GstRTSPSessionMedia *sessmedia;
1386   GstRTSPMedia *media;
1387   GstRTSPStream *stream;
1388   GstRTSPState rtspstate;
1389   GstRTSPClientClass *klass;
1390   gchar *path, *control;
1391   gint matched;
1392
1393   if (!state->uri)
1394     goto no_uri;
1395
1396   uri = state->uri;
1397   path = uri->abspath;
1398
1399   /* parse the transport */
1400   res =
1401       gst_rtsp_message_get_header (state->request, GST_RTSP_HDR_TRANSPORT,
1402       &transport, 0);
1403   if (res != GST_RTSP_OK)
1404     goto no_transport;
1405
1406   /* we create the session after parsing stuff so that we don't make
1407    * a session for malformed requests */
1408   if (priv->session_pool == NULL)
1409     goto no_pool;
1410
1411   session = state->session;
1412
1413   if (session) {
1414     g_object_ref (session);
1415     /* get a handle to the configuration of the media in the session, this can
1416      * return NULL if this is a new url to manage in this session. */
1417     sessmedia = gst_rtsp_session_get_media (session, path, &matched);
1418   } else {
1419     /* we need a new media configuration in this session */
1420     sessmedia = NULL;
1421   }
1422
1423   /* we have no session media, find one and manage it */
1424   if (sessmedia == NULL) {
1425     /* get a handle to the configuration of the media in the session */
1426     media = find_media (client, state, &matched);
1427   } else {
1428     if ((media = gst_rtsp_session_media_get_media (sessmedia)))
1429       g_object_ref (media);
1430   }
1431   /* no media, not found then */
1432   if (media == NULL)
1433     goto media_not_found;
1434
1435   /* path is what matched. We can modify the parsed uri in place */
1436   path[matched] = '\0';
1437   /* control is remainder */
1438   control = &path[matched + 1];
1439
1440   /* find the stream now using the control part */
1441   stream = gst_rtsp_media_find_stream (media, control);
1442   if (stream == NULL)
1443     goto stream_not_found;
1444
1445   /* now we have a uri identifying a valid media and stream */
1446   state->stream = stream;
1447   state->media = media;
1448
1449   if (session == NULL) {
1450     /* create a session if this fails we probably reached our session limit or
1451      * something. */
1452     if (!(session = gst_rtsp_session_pool_create (priv->session_pool)))
1453       goto service_unavailable;
1454
1455     /* make sure this client is closed when the session is closed */
1456     client_watch_session (client, session);
1457
1458     /* signal new session */
1459     g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_NEW_SESSION], 0,
1460         session);
1461
1462     state->session = session;
1463   }
1464
1465   if (sessmedia == NULL) {
1466     /* manage the media in our session now, if not done already  */
1467     sessmedia = gst_rtsp_session_manage_media (session, path, media);
1468     /* if we stil have no media, error */
1469     if (sessmedia == NULL)
1470       goto sessmedia_unavailable;
1471   } else {
1472     g_object_unref (media);
1473   }
1474
1475   state->sessmedia = sessmedia;
1476
1477   /* set blocksize on this stream */
1478   if (!handle_blocksize (media, stream, state->request))
1479     goto invalid_blocksize;
1480
1481   gst_rtsp_transport_new (&ct);
1482
1483   /* our supported transports */
1484   supported = GST_RTSP_LOWER_TRANS_UDP |
1485       GST_RTSP_LOWER_TRANS_UDP_MCAST | GST_RTSP_LOWER_TRANS_TCP;
1486
1487   /* parse and find a usable supported transport */
1488   if (!parse_transport (transport, supported, ct))
1489     goto unsupported_transports;
1490
1491   /* update the client transport */
1492   klass = GST_RTSP_CLIENT_GET_CLASS (client);
1493   if (!klass->configure_client_transport (client, state, ct))
1494     goto unsupported_client_transport;
1495
1496   /* set in the session media transport */
1497   trans = gst_rtsp_session_media_set_transport (sessmedia, stream, ct);
1498
1499   /* configure keepalive for this transport */
1500   gst_rtsp_stream_transport_set_keepalive (trans,
1501       (GstRTSPKeepAliveFunc) do_keepalive, session, NULL);
1502
1503   /* create and serialize the server transport */
1504   st = make_server_transport (client, state, ct);
1505   trans_str = gst_rtsp_transport_as_text (st);
1506   gst_rtsp_transport_free (st);
1507
1508   /* construct the response now */
1509   code = GST_RTSP_STS_OK;
1510   gst_rtsp_message_init_response (state->response, code,
1511       gst_rtsp_status_as_text (code), state->request);
1512
1513   gst_rtsp_message_add_header (state->response, GST_RTSP_HDR_TRANSPORT,
1514       trans_str);
1515   g_free (trans_str);
1516
1517   send_message (client, session, state->response, FALSE);
1518
1519   /* update the state */
1520   rtspstate = gst_rtsp_session_media_get_rtsp_state (sessmedia);
1521   switch (rtspstate) {
1522     case GST_RTSP_STATE_PLAYING:
1523     case GST_RTSP_STATE_RECORDING:
1524     case GST_RTSP_STATE_READY:
1525       /* no state change */
1526       break;
1527     default:
1528       gst_rtsp_session_media_set_rtsp_state (sessmedia, GST_RTSP_STATE_READY);
1529       break;
1530   }
1531   g_object_unref (session);
1532
1533   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_SETUP_REQUEST],
1534       0, state);
1535
1536   return TRUE;
1537
1538   /* ERRORS */
1539 no_uri:
1540   {
1541     GST_ERROR ("client %p: no uri", client);
1542     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, state);
1543     return FALSE;
1544   }
1545 no_transport:
1546   {
1547     GST_ERROR ("client %p: no transport", client);
1548     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, state);
1549     return FALSE;
1550   }
1551 no_pool:
1552   {
1553     GST_ERROR ("client %p: no session pool configured", client);
1554     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, state);
1555     return FALSE;
1556   }
1557 media_not_found:
1558   {
1559     GST_ERROR ("client %p: media '%s' not found", client, path);
1560     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, state);
1561     return FALSE;
1562   }
1563 stream_not_found:
1564   {
1565     GST_ERROR ("client %p: stream '%s' not found", client, control);
1566     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, state);
1567     g_object_unref (media);
1568     return FALSE;
1569   }
1570 service_unavailable:
1571   {
1572     GST_ERROR ("client %p: can't create session", client);
1573     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, state);
1574     g_object_unref (media);
1575     return FALSE;
1576   }
1577 sessmedia_unavailable:
1578   {
1579     GST_ERROR ("client %p: can't create session media", client);
1580     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, state);
1581     g_object_unref (media);
1582     g_object_unref (session);
1583     return FALSE;
1584   }
1585 invalid_blocksize:
1586   {
1587     GST_ERROR ("client %p: invalid blocksize", client);
1588     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, state);
1589     g_object_unref (session);
1590     return FALSE;
1591   }
1592 unsupported_transports:
1593   {
1594     GST_ERROR ("client %p: unsupported transports", client);
1595     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, state);
1596     gst_rtsp_transport_free (ct);
1597     g_object_unref (session);
1598     return FALSE;
1599   }
1600 unsupported_client_transport:
1601   {
1602     GST_ERROR ("client %p: unsupported client transport", client);
1603     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, state);
1604     gst_rtsp_transport_free (ct);
1605     g_object_unref (session);
1606     return FALSE;
1607   }
1608 }
1609
1610 static GstSDPMessage *
1611 create_sdp (GstRTSPClient * client, GstRTSPMedia * media)
1612 {
1613   GstRTSPClientPrivate *priv = client->priv;
1614   GstSDPMessage *sdp;
1615   GstSDPInfo info;
1616   const gchar *proto;
1617
1618   gst_sdp_message_new (&sdp);
1619
1620   /* some standard things first */
1621   gst_sdp_message_set_version (sdp, "0");
1622
1623   if (priv->is_ipv6)
1624     proto = "IP6";
1625   else
1626     proto = "IP4";
1627
1628   gst_sdp_message_set_origin (sdp, "-", "1188340656180883", "1", "IN", proto,
1629       priv->server_ip);
1630
1631   gst_sdp_message_set_session_name (sdp, "Session streamed with GStreamer");
1632   gst_sdp_message_set_information (sdp, "rtsp-server");
1633   gst_sdp_message_add_time (sdp, "0", "0", NULL);
1634   gst_sdp_message_add_attribute (sdp, "tool", "GStreamer");
1635   gst_sdp_message_add_attribute (sdp, "type", "broadcast");
1636   gst_sdp_message_add_attribute (sdp, "control", "*");
1637
1638   info.is_ipv6 = priv->is_ipv6;
1639   info.server_ip = priv->server_ip;
1640
1641   /* create an SDP for the media object */
1642   if (!gst_rtsp_sdp_from_media (sdp, &info, media))
1643     goto no_sdp;
1644
1645   return sdp;
1646
1647   /* ERRORS */
1648 no_sdp:
1649   {
1650     GST_ERROR ("client %p: could not create SDP", client);
1651     gst_sdp_message_free (sdp);
1652     return NULL;
1653   }
1654 }
1655
1656 /* for the describe we must generate an SDP */
1657 static gboolean
1658 handle_describe_request (GstRTSPClient * client, GstRTSPClientState * state)
1659 {
1660   GstRTSPResult res;
1661   GstSDPMessage *sdp;
1662   guint i, str_len;
1663   gchar *str, *content_base;
1664   GstRTSPMedia *media;
1665   GstRTSPClientClass *klass;
1666
1667   klass = GST_RTSP_CLIENT_GET_CLASS (client);
1668
1669   if (!state->uri)
1670     goto no_uri;
1671
1672   /* check what kind of format is accepted, we don't really do anything with it
1673    * and always return SDP for now. */
1674   for (i = 0; i++;) {
1675     gchar *accept;
1676
1677     res =
1678         gst_rtsp_message_get_header (state->request, GST_RTSP_HDR_ACCEPT,
1679         &accept, i);
1680     if (res == GST_RTSP_ENOTIMPL)
1681       break;
1682
1683     if (g_ascii_strcasecmp (accept, "application/sdp") == 0)
1684       break;
1685   }
1686
1687   /* find the media object for the uri */
1688   if (!(media = find_media (client, state, NULL)))
1689     goto no_media;
1690
1691   /* create an SDP for the media object on this client */
1692   if (!(sdp = klass->create_sdp (client, media)))
1693     goto no_sdp;
1694
1695   g_object_unref (media);
1696
1697   gst_rtsp_message_init_response (state->response, GST_RTSP_STS_OK,
1698       gst_rtsp_status_as_text (GST_RTSP_STS_OK), state->request);
1699
1700   gst_rtsp_message_add_header (state->response, GST_RTSP_HDR_CONTENT_TYPE,
1701       "application/sdp");
1702
1703   /* content base for some clients that might screw up creating the setup uri */
1704   str = gst_rtsp_url_get_request_uri (state->uri);
1705   str_len = strlen (str);
1706
1707   /* check for trailing '/' and append one */
1708   if (str[str_len - 1] != '/') {
1709     content_base = g_malloc (str_len + 2);
1710     memcpy (content_base, str, str_len);
1711     content_base[str_len] = '/';
1712     content_base[str_len + 1] = '\0';
1713     g_free (str);
1714   } else {
1715     content_base = str;
1716   }
1717
1718   GST_INFO ("adding content-base: %s", content_base);
1719
1720   gst_rtsp_message_add_header (state->response, GST_RTSP_HDR_CONTENT_BASE,
1721       content_base);
1722   g_free (content_base);
1723
1724   /* add SDP to the response body */
1725   str = gst_sdp_message_as_text (sdp);
1726   gst_rtsp_message_take_body (state->response, (guint8 *) str, strlen (str));
1727   gst_sdp_message_free (sdp);
1728
1729   send_message (client, state->session, state->response, FALSE);
1730
1731   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_DESCRIBE_REQUEST],
1732       0, state);
1733
1734   return TRUE;
1735
1736   /* ERRORS */
1737 no_uri:
1738   {
1739     GST_ERROR ("client %p: no uri", client);
1740     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, state);
1741     return FALSE;
1742   }
1743 no_media:
1744   {
1745     GST_ERROR ("client %p: no media", client);
1746     /* error reply is already sent */
1747     return FALSE;
1748   }
1749 no_sdp:
1750   {
1751     GST_ERROR ("client %p: can't create SDP", client);
1752     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, state);
1753     g_object_unref (media);
1754     return FALSE;
1755   }
1756 }
1757
1758 static gboolean
1759 handle_options_request (GstRTSPClient * client, GstRTSPClientState * state)
1760 {
1761   GstRTSPMethod options;
1762   gchar *str;
1763
1764   options = GST_RTSP_DESCRIBE |
1765       GST_RTSP_OPTIONS |
1766       GST_RTSP_PAUSE |
1767       GST_RTSP_PLAY |
1768       GST_RTSP_SETUP |
1769       GST_RTSP_GET_PARAMETER | GST_RTSP_SET_PARAMETER | GST_RTSP_TEARDOWN;
1770
1771   str = gst_rtsp_options_as_text (options);
1772
1773   gst_rtsp_message_init_response (state->response, GST_RTSP_STS_OK,
1774       gst_rtsp_status_as_text (GST_RTSP_STS_OK), state->request);
1775
1776   gst_rtsp_message_add_header (state->response, GST_RTSP_HDR_PUBLIC, str);
1777   g_free (str);
1778
1779   send_message (client, state->session, state->response, FALSE);
1780
1781   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_OPTIONS_REQUEST],
1782       0, state);
1783
1784   return TRUE;
1785 }
1786
1787 /* remove duplicate and trailing '/' */
1788 static void
1789 sanitize_uri (GstRTSPUrl * uri)
1790 {
1791   gint i, len;
1792   gchar *s, *d;
1793   gboolean have_slash, prev_slash;
1794
1795   s = d = uri->abspath;
1796   len = strlen (uri->abspath);
1797
1798   prev_slash = FALSE;
1799
1800   for (i = 0; i < len; i++) {
1801     have_slash = s[i] == '/';
1802     *d = s[i];
1803     if (!have_slash || !prev_slash)
1804       d++;
1805     prev_slash = have_slash;
1806   }
1807   len = d - uri->abspath;
1808   /* don't remove the first slash if that's the only thing left */
1809   if (len > 1 && *(d - 1) == '/')
1810     d--;
1811   *d = '\0';
1812 }
1813
1814 static void
1815 client_session_finalized (GstRTSPClient * client, GstRTSPSession * session)
1816 {
1817   GstRTSPClientPrivate *priv = client->priv;
1818
1819   GST_INFO ("client %p: session %p finished", client, session);
1820
1821   /* unlink all media managed in this session */
1822   client_unlink_session (client, session);
1823
1824   /* remove the session */
1825   if (!(priv->sessions = g_list_remove (priv->sessions, session))) {
1826     GST_INFO ("client %p: all sessions finalized, close the connection",
1827         client);
1828     close_connection (client);
1829   }
1830 }
1831
1832 static GPrivate current_state;
1833
1834 /**
1835  * gst_rtsp_client_state_get_current:
1836  *
1837  * Get the current #GstRTSPClientState. This object is retrieved from the
1838  * current thread that is handling the request for a client.
1839  *
1840  * Returns: a #GstRTSPClientState
1841  */
1842 GstRTSPClientState *
1843 gst_rtsp_client_state_get_current (void)
1844 {
1845   GSList *l;
1846
1847   l = g_private_get (&current_state);
1848   if (l == NULL)
1849     return NULL;
1850
1851   return (GstRTSPClientState *) (l->data);
1852
1853 }
1854
1855 /**
1856  * gst_rtsp_client_state_push_current:
1857  * @state: a ##GstRTSPClientState
1858  *
1859  * Pushes @state onto the state stack. The current
1860  * state can then be received using gst_rtsp_client_state_get_current().
1861  **/
1862 void
1863 gst_rtsp_client_state_push_current (GstRTSPClientState * state)
1864 {
1865   GSList *l;
1866
1867   g_return_if_fail (state != NULL);
1868
1869   l = g_private_get (&current_state);
1870   l = g_slist_prepend (l, state);
1871   g_private_set (&current_state, l);
1872 }
1873
1874 /**
1875  * gst_rtsp_client_state_pop_current:
1876  * @state: a #GstRTSPClientState
1877  *
1878  * Pops @state off the state stack (verifying that @state
1879  * is on the top of the stack).
1880  **/
1881 void
1882 gst_rtsp_client_state_pop_current (GstRTSPClientState * state)
1883 {
1884   GSList *l;
1885
1886   l = g_private_get (&current_state);
1887
1888   g_return_if_fail (l != NULL);
1889   g_return_if_fail (l->data == state);
1890
1891   l = g_slist_delete_link (l, l);
1892   g_private_set (&current_state, l);
1893 }
1894
1895 static void
1896 handle_request (GstRTSPClient * client, GstRTSPMessage * request)
1897 {
1898   GstRTSPClientPrivate *priv = client->priv;
1899   GstRTSPMethod method;
1900   const gchar *uristr;
1901   GstRTSPUrl *uri = NULL;
1902   GstRTSPVersion version;
1903   GstRTSPResult res;
1904   GstRTSPSession *session = NULL;
1905   GstRTSPClientState state = { NULL };
1906   GstRTSPMessage response = { 0 };
1907   gchar *sessid;
1908
1909   state.conn = priv->connection;
1910   state.client = client;
1911   state.request = request;
1912   state.response = &response;
1913   state.auth = priv->auth;
1914   gst_rtsp_client_state_push_current (&state);
1915
1916   if (gst_debug_category_get_threshold (rtsp_client_debug) >= GST_LEVEL_LOG) {
1917     gst_rtsp_message_dump (request);
1918   }
1919
1920   GST_INFO ("client %p: received a request", client);
1921
1922   gst_rtsp_message_parse_request (request, &method, &uristr, &version);
1923
1924   /* we can only handle 1.0 requests */
1925   if (version != GST_RTSP_VERSION_1_0)
1926     goto not_supported;
1927
1928   state.method = method;
1929
1930   /* we always try to parse the url first */
1931   if (strcmp (uristr, "*") == 0) {
1932     /* special case where we have * as uri, keep uri = NULL */
1933   } else if (gst_rtsp_url_parse (uristr, &uri) != GST_RTSP_OK)
1934     goto bad_request;
1935
1936   /* get the session if there is any */
1937   res = gst_rtsp_message_get_header (request, GST_RTSP_HDR_SESSION, &sessid, 0);
1938   if (res == GST_RTSP_OK) {
1939     if (priv->session_pool == NULL)
1940       goto no_pool;
1941
1942     /* we had a session in the request, find it again */
1943     if (!(session = gst_rtsp_session_pool_find (priv->session_pool, sessid)))
1944       goto session_not_found;
1945
1946     /* we add the session to the client list of watched sessions. When a session
1947      * disappears because it times out, we will be notified. If all sessions are
1948      * gone, we will close the connection */
1949     client_watch_session (client, session);
1950   }
1951
1952   /* sanitize the uri */
1953   if (uri)
1954     sanitize_uri (uri);
1955   state.uri = uri;
1956   state.session = session;
1957
1958   if (!gst_rtsp_auth_check (GST_RTSP_AUTH_CHECK_URL))
1959     goto not_authorized;
1960
1961   /* now see what is asked and dispatch to a dedicated handler */
1962   switch (method) {
1963     case GST_RTSP_OPTIONS:
1964       handle_options_request (client, &state);
1965       break;
1966     case GST_RTSP_DESCRIBE:
1967       handle_describe_request (client, &state);
1968       break;
1969     case GST_RTSP_SETUP:
1970       handle_setup_request (client, &state);
1971       break;
1972     case GST_RTSP_PLAY:
1973       handle_play_request (client, &state);
1974       break;
1975     case GST_RTSP_PAUSE:
1976       handle_pause_request (client, &state);
1977       break;
1978     case GST_RTSP_TEARDOWN:
1979       handle_teardown_request (client, &state);
1980       break;
1981     case GST_RTSP_SET_PARAMETER:
1982       handle_set_param_request (client, &state);
1983       break;
1984     case GST_RTSP_GET_PARAMETER:
1985       handle_get_param_request (client, &state);
1986       break;
1987     case GST_RTSP_ANNOUNCE:
1988     case GST_RTSP_RECORD:
1989     case GST_RTSP_REDIRECT:
1990       goto not_implemented;
1991     case GST_RTSP_INVALID:
1992     default:
1993       goto bad_request;
1994   }
1995
1996 done:
1997   gst_rtsp_client_state_pop_current (&state);
1998   if (session)
1999     g_object_unref (session);
2000   if (uri)
2001     gst_rtsp_url_free (uri);
2002   return;
2003
2004   /* ERRORS */
2005 not_supported:
2006   {
2007     GST_ERROR ("client %p: version %d not supported", client, version);
2008     send_generic_response (client, GST_RTSP_STS_RTSP_VERSION_NOT_SUPPORTED,
2009         &state);
2010     goto done;
2011   }
2012 bad_request:
2013   {
2014     GST_ERROR ("client %p: bad request", client);
2015     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, &state);
2016     goto done;
2017   }
2018 no_pool:
2019   {
2020     GST_ERROR ("client %p: no pool configured", client);
2021     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, &state);
2022     goto done;
2023   }
2024 session_not_found:
2025   {
2026     GST_ERROR ("client %p: session not found", client);
2027     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, &state);
2028     goto done;
2029   }
2030 not_authorized:
2031   {
2032     GST_ERROR ("client %p: not allowed", client);
2033     handle_unauthorized_request (client, priv->auth, &state);
2034     goto done;
2035   }
2036 not_implemented:
2037   {
2038     GST_ERROR ("client %p: method %d not implemented", client, method);
2039     send_generic_response (client, GST_RTSP_STS_NOT_IMPLEMENTED, &state);
2040     goto done;
2041   }
2042 }
2043
2044 static void
2045 handle_data (GstRTSPClient * client, GstRTSPMessage * message)
2046 {
2047   GstRTSPClientPrivate *priv = client->priv;
2048   GstRTSPResult res;
2049   guint8 channel;
2050   GList *walk;
2051   guint8 *data;
2052   guint size;
2053   GstBuffer *buffer;
2054   gboolean handled;
2055
2056   /* find the stream for this message */
2057   res = gst_rtsp_message_parse_data (message, &channel);
2058   if (res != GST_RTSP_OK)
2059     return;
2060
2061   gst_rtsp_message_steal_body (message, &data, &size);
2062
2063   buffer = gst_buffer_new_wrapped (data, size);
2064
2065   handled = FALSE;
2066   for (walk = priv->transports; walk; walk = g_list_next (walk)) {
2067     GstRTSPStreamTransport *trans;
2068     GstRTSPStream *stream;
2069     const GstRTSPTransport *tr;
2070
2071     trans = walk->data;
2072
2073     tr = gst_rtsp_stream_transport_get_transport (trans);
2074     stream = gst_rtsp_stream_transport_get_stream (trans);
2075
2076     /* check for TCP transport */
2077     if (tr->lower_transport == GST_RTSP_LOWER_TRANS_TCP) {
2078       /* dispatch to the stream based on the channel number */
2079       if (tr->interleaved.min == channel) {
2080         gst_rtsp_stream_recv_rtp (stream, buffer);
2081         handled = TRUE;
2082         break;
2083       } else if (tr->interleaved.max == channel) {
2084         gst_rtsp_stream_recv_rtcp (stream, buffer);
2085         handled = TRUE;
2086         break;
2087       }
2088     }
2089   }
2090   if (!handled)
2091     gst_buffer_unref (buffer);
2092 }
2093
2094 /**
2095  * gst_rtsp_client_set_session_pool:
2096  * @client: a #GstRTSPClient
2097  * @pool: a #GstRTSPSessionPool
2098  *
2099  * Set @pool as the sessionpool for @client which it will use to find
2100  * or allocate sessions. the sessionpool is usually inherited from the server
2101  * that created the client but can be overridden later.
2102  */
2103 void
2104 gst_rtsp_client_set_session_pool (GstRTSPClient * client,
2105     GstRTSPSessionPool * pool)
2106 {
2107   GstRTSPSessionPool *old;
2108   GstRTSPClientPrivate *priv;
2109
2110   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2111
2112   priv = client->priv;
2113
2114   if (pool)
2115     g_object_ref (pool);
2116
2117   g_mutex_lock (&priv->lock);
2118   old = priv->session_pool;
2119   priv->session_pool = pool;
2120   g_mutex_unlock (&priv->lock);
2121
2122   if (old)
2123     g_object_unref (old);
2124 }
2125
2126 /**
2127  * gst_rtsp_client_get_session_pool:
2128  * @client: a #GstRTSPClient
2129  *
2130  * Get the #GstRTSPSessionPool object that @client uses to manage its sessions.
2131  *
2132  * Returns: (transfer full): a #GstRTSPSessionPool, unref after usage.
2133  */
2134 GstRTSPSessionPool *
2135 gst_rtsp_client_get_session_pool (GstRTSPClient * client)
2136 {
2137   GstRTSPClientPrivate *priv;
2138   GstRTSPSessionPool *result;
2139
2140   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2141
2142   priv = client->priv;
2143
2144   g_mutex_lock (&priv->lock);
2145   if ((result = priv->session_pool))
2146     g_object_ref (result);
2147   g_mutex_unlock (&priv->lock);
2148
2149   return result;
2150 }
2151
2152 /**
2153  * gst_rtsp_client_set_mount_points:
2154  * @client: a #GstRTSPClient
2155  * @mounts: a #GstRTSPMountPoints
2156  *
2157  * Set @mounts as the mount points for @client which it will use to map urls
2158  * to media streams. These mount points are usually inherited from the server that
2159  * created the client but can be overriden later.
2160  */
2161 void
2162 gst_rtsp_client_set_mount_points (GstRTSPClient * client,
2163     GstRTSPMountPoints * mounts)
2164 {
2165   GstRTSPClientPrivate *priv;
2166   GstRTSPMountPoints *old;
2167
2168   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2169
2170   priv = client->priv;
2171
2172   if (mounts)
2173     g_object_ref (mounts);
2174
2175   g_mutex_lock (&priv->lock);
2176   old = priv->mount_points;
2177   priv->mount_points = mounts;
2178   g_mutex_unlock (&priv->lock);
2179
2180   if (old)
2181     g_object_unref (old);
2182 }
2183
2184 /**
2185  * gst_rtsp_client_get_mount_points:
2186  * @client: a #GstRTSPClient
2187  *
2188  * Get the #GstRTSPMountPoints object that @client uses to manage its sessions.
2189  *
2190  * Returns: (transfer full): a #GstRTSPMountPoints, unref after usage.
2191  */
2192 GstRTSPMountPoints *
2193 gst_rtsp_client_get_mount_points (GstRTSPClient * client)
2194 {
2195   GstRTSPClientPrivate *priv;
2196   GstRTSPMountPoints *result;
2197
2198   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2199
2200   priv = client->priv;
2201
2202   g_mutex_lock (&priv->lock);
2203   if ((result = priv->mount_points))
2204     g_object_ref (result);
2205   g_mutex_unlock (&priv->lock);
2206
2207   return result;
2208 }
2209
2210 /**
2211  * gst_rtsp_client_set_use_client_settings:
2212  * @client: a #GstRTSPClient
2213  * @use_client_settings: whether to use client settings for multicast
2214  *
2215  * Use client transport settings (destination and ttl) for multicast.
2216  * When @use_client_settings is %FALSE, the server settings will be
2217  * used.
2218  */
2219 void
2220 gst_rtsp_client_set_use_client_settings (GstRTSPClient * client,
2221     gboolean use_client_settings)
2222 {
2223   GstRTSPClientPrivate *priv;
2224
2225   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2226
2227   priv = client->priv;
2228
2229   g_mutex_lock (&priv->lock);
2230   priv->use_client_settings = use_client_settings;
2231   g_mutex_unlock (&priv->lock);
2232 }
2233
2234 /**
2235  * gst_rtsp_client_get_use_client_settings:
2236  * @client: a #GstRTSPClient
2237  *
2238  * Check if client transport settings (destination and ttl) for multicast
2239  * will be used.
2240  */
2241 gboolean
2242 gst_rtsp_client_get_use_client_settings (GstRTSPClient * client)
2243 {
2244   GstRTSPClientPrivate *priv;
2245   gboolean res;
2246
2247   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), FALSE);
2248
2249   priv = client->priv;
2250
2251   g_mutex_lock (&priv->lock);
2252   res = priv->use_client_settings;
2253   g_mutex_unlock (&priv->lock);
2254
2255   return res;
2256 }
2257
2258 /**
2259  * gst_rtsp_client_set_auth:
2260  * @client: a #GstRTSPClient
2261  * @auth: a #GstRTSPAuth
2262  *
2263  * configure @auth to be used as the authentication manager of @client.
2264  */
2265 void
2266 gst_rtsp_client_set_auth (GstRTSPClient * client, GstRTSPAuth * auth)
2267 {
2268   GstRTSPClientPrivate *priv;
2269   GstRTSPAuth *old;
2270
2271   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2272
2273   priv = client->priv;
2274
2275   if (auth)
2276     g_object_ref (auth);
2277
2278   g_mutex_lock (&priv->lock);
2279   old = priv->auth;
2280   priv->auth = auth;
2281   g_mutex_unlock (&priv->lock);
2282
2283   if (old)
2284     g_object_unref (old);
2285 }
2286
2287
2288 /**
2289  * gst_rtsp_client_get_auth:
2290  * @client: a #GstRTSPClient
2291  *
2292  * Get the #GstRTSPAuth used as the authentication manager of @client.
2293  *
2294  * Returns: (transfer full): the #GstRTSPAuth of @client. g_object_unref() after
2295  * usage.
2296  */
2297 GstRTSPAuth *
2298 gst_rtsp_client_get_auth (GstRTSPClient * client)
2299 {
2300   GstRTSPClientPrivate *priv;
2301   GstRTSPAuth *result;
2302
2303   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2304
2305   priv = client->priv;
2306
2307   g_mutex_lock (&priv->lock);
2308   if ((result = priv->auth))
2309     g_object_ref (result);
2310   g_mutex_unlock (&priv->lock);
2311
2312   return result;
2313 }
2314
2315 /**
2316  * gst_rtsp_client_set_thread_pool:
2317  * @client: a #GstRTSPClient
2318  * @pool: a #GstRTSPThreadPool
2319  *
2320  * configure @pool to be used as the thread pool of @client.
2321  */
2322 void
2323 gst_rtsp_client_set_thread_pool (GstRTSPClient * client,
2324     GstRTSPThreadPool * pool)
2325 {
2326   GstRTSPClientPrivate *priv;
2327   GstRTSPThreadPool *old;
2328
2329   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2330
2331   priv = client->priv;
2332
2333   if (pool)
2334     g_object_ref (pool);
2335
2336   g_mutex_lock (&priv->lock);
2337   old = priv->thread_pool;
2338   priv->thread_pool = pool;
2339   g_mutex_unlock (&priv->lock);
2340
2341   if (old)
2342     g_object_unref (old);
2343 }
2344
2345 /**
2346  * gst_rtsp_client_get_thread_pool:
2347  * @client: a #GstRTSPClient
2348  *
2349  * Get the #GstRTSPThreadPool used as the thread pool of @client.
2350  *
2351  * Returns: (transfer full): the #GstRTSPThreadPool of @client. g_object_unref() after
2352  * usage.
2353  */
2354 GstRTSPThreadPool *
2355 gst_rtsp_client_get_thread_pool (GstRTSPClient * client)
2356 {
2357   GstRTSPClientPrivate *priv;
2358   GstRTSPThreadPool *result;
2359
2360   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2361
2362   priv = client->priv;
2363
2364   g_mutex_lock (&priv->lock);
2365   if ((result = priv->thread_pool))
2366     g_object_ref (result);
2367   g_mutex_unlock (&priv->lock);
2368
2369   return result;
2370 }
2371
2372 /**
2373  * gst_rtsp_client_set_connection:
2374  * @client: a #GstRTSPClient
2375  * @conn: (transfer full): a #GstRTSPConnection
2376  *
2377  * Set the #GstRTSPConnection of @client. This function takes ownership of
2378  * @conn.
2379  *
2380  * Returns: %TRUE on success.
2381  */
2382 gboolean
2383 gst_rtsp_client_set_connection (GstRTSPClient * client,
2384     GstRTSPConnection * conn)
2385 {
2386   GstRTSPClientPrivate *priv;
2387   GSocket *read_socket;
2388   GSocketAddress *address;
2389   GstRTSPUrl *url;
2390   GError *error = NULL;
2391
2392   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), FALSE);
2393   g_return_val_if_fail (conn != NULL, FALSE);
2394
2395   priv = client->priv;
2396
2397   read_socket = gst_rtsp_connection_get_read_socket (conn);
2398
2399   if (!(address = g_socket_get_local_address (read_socket, &error)))
2400     goto no_address;
2401
2402   g_free (priv->server_ip);
2403   /* keep the original ip that the client connected to */
2404   if (G_IS_INET_SOCKET_ADDRESS (address)) {
2405     GInetAddress *iaddr;
2406
2407     iaddr = g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (address));
2408
2409     /* socket might be ipv6 but adress still ipv4 */
2410     priv->is_ipv6 = g_inet_address_get_family (iaddr) == G_SOCKET_FAMILY_IPV6;
2411     priv->server_ip = g_inet_address_to_string (iaddr);
2412     g_object_unref (address);
2413   } else {
2414     priv->is_ipv6 = g_socket_get_family (read_socket) == G_SOCKET_FAMILY_IPV6;
2415     priv->server_ip = g_strdup ("unknown");
2416   }
2417
2418   GST_INFO ("client %p connected to server ip %s, ipv6 = %d", client,
2419       priv->server_ip, priv->is_ipv6);
2420
2421   url = gst_rtsp_connection_get_url (conn);
2422   GST_INFO ("added new client %p ip %s:%d", client, url->host, url->port);
2423
2424   priv->connection = conn;
2425
2426   return TRUE;
2427
2428   /* ERRORS */
2429 no_address:
2430   {
2431     GST_ERROR ("could not get local address %s", error->message);
2432     g_error_free (error);
2433     return FALSE;
2434   }
2435 }
2436
2437 /**
2438  * gst_rtsp_client_get_connection:
2439  * @client: a #GstRTSPClient
2440  *
2441  * Get the #GstRTSPConnection of @client.
2442  *
2443  * Returns: (transfer none): the #GstRTSPConnection of @client.
2444  * The connection object returned remains valid until the client is freed.
2445  */
2446 GstRTSPConnection *
2447 gst_rtsp_client_get_connection (GstRTSPClient * client)
2448 {
2449   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2450
2451   return client->priv->connection;
2452 }
2453
2454 /**
2455  * gst_rtsp_client_set_send_func:
2456  * @client: a #GstRTSPClient
2457  * @func: a #GstRTSPClientSendFunc
2458  * @user_data: user data passed to @func
2459  * @notify: called when @user_data is no longer in use
2460  *
2461  * Set @func as the callback that will be called when a new message needs to be
2462  * sent to the client. @user_data is passed to @func and @notify is called when
2463  * @user_data is no longer in use.
2464  *
2465  * By default, the client will send the messages on the #GstRTSPConnection that
2466  * was configured with gst_rtsp_client_attach() was called.
2467  */
2468 void
2469 gst_rtsp_client_set_send_func (GstRTSPClient * client,
2470     GstRTSPClientSendFunc func, gpointer user_data, GDestroyNotify notify)
2471 {
2472   GstRTSPClientPrivate *priv;
2473   GDestroyNotify old_notify;
2474   gpointer old_data;
2475
2476   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
2477
2478   priv = client->priv;
2479
2480   g_mutex_lock (&priv->send_lock);
2481   priv->send_func = func;
2482   old_notify = priv->send_notify;
2483   old_data = priv->send_data;
2484   priv->send_notify = notify;
2485   priv->send_data = user_data;
2486   g_mutex_unlock (&priv->send_lock);
2487
2488   if (old_notify)
2489     old_notify (old_data);
2490 }
2491
2492 /**
2493  * gst_rtsp_client_handle_message:
2494  * @client: a #GstRTSPClient
2495  * @message: an #GstRTSPMessage
2496  *
2497  * Let the client handle @message.
2498  *
2499  * Returns: a #GstRTSPResult.
2500  */
2501 GstRTSPResult
2502 gst_rtsp_client_handle_message (GstRTSPClient * client,
2503     GstRTSPMessage * message)
2504 {
2505   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), GST_RTSP_EINVAL);
2506   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
2507
2508   switch (message->type) {
2509     case GST_RTSP_MESSAGE_REQUEST:
2510       handle_request (client, message);
2511       break;
2512     case GST_RTSP_MESSAGE_RESPONSE:
2513       break;
2514     case GST_RTSP_MESSAGE_DATA:
2515       handle_data (client, message);
2516       break;
2517     default:
2518       break;
2519   }
2520   return GST_RTSP_OK;
2521 }
2522
2523 /**
2524  * gst_rtsp_client_send_request:
2525  * @client: a #GstRTSPClient
2526  * @session: a #GstRTSPSession to send the request to or %NULL
2527  * @request: The request #GstRTSPMessage to send
2528  *
2529  * Send a request message to the remote end. @request must be a
2530  * #GST_RTSP_MESSAGE_REQUEST.
2531  */
2532 GstRTSPResult
2533 gst_rtsp_client_send_request (GstRTSPClient * client, GstRTSPSession * session,
2534     GstRTSPMessage * request)
2535 {
2536   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), GST_RTSP_EINVAL);
2537   g_return_val_if_fail (request != NULL, GST_RTSP_EINVAL);
2538   g_return_val_if_fail (request->type == GST_RTSP_MESSAGE_REQUEST,
2539       GST_RTSP_EINVAL);
2540
2541   send_message (client, session, request, FALSE);
2542
2543   return GST_RTSP_OK;
2544 }
2545
2546 static GstRTSPResult
2547 do_send_message (GstRTSPClient * client, GstRTSPMessage * message,
2548     gboolean close, gpointer user_data)
2549 {
2550   GstRTSPClientPrivate *priv = client->priv;
2551
2552   /* send the response and store the seq number so we can wait until it's
2553    * written to the client to close the connection */
2554   return gst_rtsp_watch_send_message (priv->watch, message, close ?
2555       &priv->close_seq : NULL);
2556 }
2557
2558 static GstRTSPResult
2559 message_received (GstRTSPWatch * watch, GstRTSPMessage * message,
2560     gpointer user_data)
2561 {
2562   return gst_rtsp_client_handle_message (GST_RTSP_CLIENT (user_data), message);
2563 }
2564
2565 static GstRTSPResult
2566 message_sent (GstRTSPWatch * watch, guint cseq, gpointer user_data)
2567 {
2568   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2569   GstRTSPClientPrivate *priv = client->priv;
2570
2571   if (priv->close_seq && priv->close_seq == cseq) {
2572     priv->close_seq = 0;
2573     close_connection (client);
2574   }
2575
2576   return GST_RTSP_OK;
2577 }
2578
2579 static GstRTSPResult
2580 closed (GstRTSPWatch * watch, gpointer user_data)
2581 {
2582   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2583   GstRTSPClientPrivate *priv = client->priv;
2584   const gchar *tunnelid;
2585
2586   GST_INFO ("client %p: connection closed", client);
2587
2588   if ((tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection))) {
2589     g_mutex_lock (&tunnels_lock);
2590     /* remove from tunnelids */
2591     g_hash_table_remove (tunnels, tunnelid);
2592     g_mutex_unlock (&tunnels_lock);
2593   }
2594
2595   gst_rtsp_client_set_send_func (client, NULL, NULL, NULL);
2596
2597   return GST_RTSP_OK;
2598 }
2599
2600 static GstRTSPResult
2601 error (GstRTSPWatch * watch, GstRTSPResult result, gpointer user_data)
2602 {
2603   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2604   gchar *str;
2605
2606   str = gst_rtsp_strresult (result);
2607   GST_INFO ("client %p: received an error %s", client, str);
2608   g_free (str);
2609
2610   return GST_RTSP_OK;
2611 }
2612
2613 static GstRTSPResult
2614 error_full (GstRTSPWatch * watch, GstRTSPResult result,
2615     GstRTSPMessage * message, guint id, gpointer user_data)
2616 {
2617   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2618   gchar *str;
2619
2620   str = gst_rtsp_strresult (result);
2621   GST_INFO
2622       ("client %p: error when handling message %p with id %d: %s",
2623       client, message, id, str);
2624   g_free (str);
2625
2626   return GST_RTSP_OK;
2627 }
2628
2629 static gboolean
2630 remember_tunnel (GstRTSPClient * client)
2631 {
2632   GstRTSPClientPrivate *priv = client->priv;
2633   const gchar *tunnelid;
2634
2635   /* store client in the pending tunnels */
2636   tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection);
2637   if (tunnelid == NULL)
2638     goto no_tunnelid;
2639
2640   GST_INFO ("client %p: inserting tunnel session %s", client, tunnelid);
2641
2642   /* we can't have two clients connecting with the same tunnelid */
2643   g_mutex_lock (&tunnels_lock);
2644   if (g_hash_table_lookup (tunnels, tunnelid))
2645     goto tunnel_existed;
2646
2647   g_hash_table_insert (tunnels, g_strdup (tunnelid), g_object_ref (client));
2648   g_mutex_unlock (&tunnels_lock);
2649
2650   return TRUE;
2651
2652   /* ERRORS */
2653 no_tunnelid:
2654   {
2655     GST_ERROR ("client %p: no tunnelid provided", client);
2656     return FALSE;
2657   }
2658 tunnel_existed:
2659   {
2660     g_mutex_unlock (&tunnels_lock);
2661     GST_ERROR ("client %p: tunnel session %s already existed", client,
2662         tunnelid);
2663     return FALSE;
2664   }
2665 }
2666
2667 static GstRTSPStatusCode
2668 tunnel_start (GstRTSPWatch * watch, gpointer user_data)
2669 {
2670   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2671   GstRTSPClientPrivate *priv = client->priv;
2672
2673   GST_INFO ("client %p: tunnel start (connection %p)", client,
2674       priv->connection);
2675
2676   if (!remember_tunnel (client))
2677     goto tunnel_error;
2678
2679   return GST_RTSP_STS_OK;
2680
2681   /* ERRORS */
2682 tunnel_error:
2683   {
2684     GST_ERROR ("client %p: error starting tunnel", client);
2685     return GST_RTSP_STS_SERVICE_UNAVAILABLE;
2686   }
2687 }
2688
2689 static GstRTSPResult
2690 tunnel_lost (GstRTSPWatch * watch, gpointer user_data)
2691 {
2692   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2693   GstRTSPClientPrivate *priv = client->priv;
2694
2695   GST_WARNING ("client %p: tunnel lost (connection %p)", client,
2696       priv->connection);
2697
2698   /* ignore error, it'll only be a problem when the client does a POST again */
2699   remember_tunnel (client);
2700
2701   return GST_RTSP_OK;
2702 }
2703
2704 static GstRTSPResult
2705 tunnel_complete (GstRTSPWatch * watch, gpointer user_data)
2706 {
2707   const gchar *tunnelid;
2708   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2709   GstRTSPClientPrivate *priv = client->priv;
2710   GstRTSPClient *oclient;
2711   GstRTSPClientPrivate *opriv;
2712
2713   GST_INFO ("client %p: tunnel complete", client);
2714
2715   /* find previous tunnel */
2716   tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection);
2717   if (tunnelid == NULL)
2718     goto no_tunnelid;
2719
2720   g_mutex_lock (&tunnels_lock);
2721   if (!(oclient = g_hash_table_lookup (tunnels, tunnelid)))
2722     goto no_tunnel;
2723
2724   /* remove the old client from the table. ref before because removing it will
2725    * remove the ref to it. */
2726   g_object_ref (oclient);
2727   g_hash_table_remove (tunnels, tunnelid);
2728
2729   opriv = oclient->priv;
2730
2731   if (opriv->watch == NULL)
2732     goto tunnel_closed;
2733   g_mutex_unlock (&tunnels_lock);
2734
2735   GST_INFO ("client %p: found tunnel %p (old %p, new %p)", client, oclient,
2736       opriv->connection, priv->connection);
2737
2738   /* merge the tunnels into the first client */
2739   gst_rtsp_connection_do_tunnel (opriv->connection, priv->connection);
2740   gst_rtsp_watch_reset (opriv->watch);
2741   g_object_unref (oclient);
2742
2743   return GST_RTSP_OK;
2744
2745   /* ERRORS */
2746 no_tunnelid:
2747   {
2748     GST_ERROR ("client %p: no tunnelid provided", client);
2749     return GST_RTSP_ERROR;
2750   }
2751 no_tunnel:
2752   {
2753     g_mutex_unlock (&tunnels_lock);
2754     GST_ERROR ("client %p: tunnel session %s not found", client, tunnelid);
2755     return GST_RTSP_ERROR;
2756   }
2757 tunnel_closed:
2758   {
2759     g_mutex_unlock (&tunnels_lock);
2760     GST_ERROR ("client %p: tunnel session %s was closed", client, tunnelid);
2761     g_object_unref (oclient);
2762     return GST_RTSP_ERROR;
2763   }
2764 }
2765
2766 static GstRTSPWatchFuncs watch_funcs = {
2767   message_received,
2768   message_sent,
2769   closed,
2770   error,
2771   tunnel_start,
2772   tunnel_complete,
2773   error_full,
2774   tunnel_lost
2775 };
2776
2777 static void
2778 client_watch_notify (GstRTSPClient * client)
2779 {
2780   GstRTSPClientPrivate *priv = client->priv;
2781
2782   GST_INFO ("client %p: watch destroyed", client);
2783   priv->watch = NULL;
2784   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_CLOSED], 0, NULL);
2785   g_object_unref (client);
2786 }
2787
2788 /**
2789  * gst_rtsp_client_attach:
2790  * @client: a #GstRTSPClient
2791  * @context: (allow-none): a #GMainContext
2792  *
2793  * Attaches @client to @context. When the mainloop for @context is run, the
2794  * client will be dispatched. When @context is NULL, the default context will be
2795  * used).
2796  *
2797  * This function should be called when the client properties and urls are fully
2798  * configured and the client is ready to start.
2799  *
2800  * Returns: the ID (greater than 0) for the source within the GMainContext.
2801  */
2802 guint
2803 gst_rtsp_client_attach (GstRTSPClient * client, GMainContext * context)
2804 {
2805   GstRTSPClientPrivate *priv;
2806   guint res;
2807
2808   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), 0);
2809   priv = client->priv;
2810   g_return_val_if_fail (priv->connection != NULL, 0);
2811   g_return_val_if_fail (priv->watch == NULL, 0);
2812
2813   /* create watch for the connection and attach */
2814   priv->watch = gst_rtsp_watch_new (priv->connection, &watch_funcs,
2815       g_object_ref (client), (GDestroyNotify) client_watch_notify);
2816   gst_rtsp_client_set_send_func (client, do_send_message, priv->watch,
2817       (GDestroyNotify) gst_rtsp_watch_unref);
2818
2819   /* FIXME make this configurable. We don't want to do this yet because it will
2820    * be superceeded by a cache object later */
2821   gst_rtsp_watch_set_send_backlog (priv->watch, 0, 100);
2822
2823   GST_INFO ("attaching to context %p", context);
2824   res = gst_rtsp_watch_attach (priv->watch, context);
2825
2826   return res;
2827 }
2828
2829 /**
2830  * gst_rtsp_client_session_filter:
2831  * @client: a #GstRTSPclient
2832  * @func: (scope call): a callback
2833  * @user_data: user data passed to @func
2834  *
2835  * Call @func for each session managed by @client. The result value of @func
2836  * determines what happens to the session. @func will be called with @client
2837  * locked so no further actions on @client can be performed from @func.
2838  *
2839  * If @func returns #GST_RTSP_FILTER_REMOVE, the session will be removed from
2840  * @client.
2841  *
2842  * If @func returns #GST_RTSP_FILTER_KEEP, the session will remain in @client.
2843  *
2844  * If @func returns #GST_RTSP_FILTER_REF, the session will remain in @client but
2845  * will also be added with an additional ref to the result #GList of this
2846  * function..
2847  *
2848  * Returns: (element-type GstRTSPSession) (transfer full): a #GList with all
2849  * sessions for which @func returned #GST_RTSP_FILTER_REF. After usage, each
2850  * element in the #GList should be unreffed before the list is freed.
2851  */
2852 GList *
2853 gst_rtsp_client_session_filter (GstRTSPClient * client,
2854     GstRTSPClientSessionFilterFunc func, gpointer user_data)
2855 {
2856   GstRTSPClientPrivate *priv;
2857   GList *result, *walk, *next;
2858
2859   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
2860   g_return_val_if_fail (func != NULL, NULL);
2861
2862   priv = client->priv;
2863
2864   result = NULL;
2865
2866   g_mutex_lock (&priv->lock);
2867   for (walk = priv->sessions; walk; walk = next) {
2868     GstRTSPSession *sess = walk->data;
2869
2870     next = g_list_next (walk);
2871
2872     switch (func (client, sess, user_data)) {
2873       case GST_RTSP_FILTER_REMOVE:
2874         /* stop watching the session and pretent it went away */
2875         client_cleanup_session (client, sess);
2876         break;
2877       case GST_RTSP_FILTER_REF:
2878         result = g_list_prepend (result, g_object_ref (sess));
2879         break;
2880       case GST_RTSP_FILTER_KEEP:
2881       default:
2882         break;
2883     }
2884   }
2885   g_mutex_unlock (&priv->lock);
2886
2887   return result;
2888 }