client: remove reference to server
[platform/upstream/gstreamer.git] / gst / rtsp-server / rtsp-client.c
1 /* GStreamer
2  * Copyright (C) 2008 Wim Taymans <wim.taymans at gmail.com>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
17  * Boston, MA 02110-1301, USA.
18  */
19
20 #include <stdio.h>
21 #include <string.h>
22
23 #include "rtsp-client.h"
24 #include "rtsp-sdp.h"
25 #include "rtsp-params.h"
26
27 static GMutex tunnels_lock;
28 static GHashTable *tunnels;
29
30 #define DEFAULT_SESSION_POOL            NULL
31 #define DEFAULT_MOUNT_POINTS            NULL
32 #define DEFAULT_USE_CLIENT_SETTINGS     FALSE
33
34 enum
35 {
36   PROP_0,
37   PROP_SESSION_POOL,
38   PROP_MOUNT_POINTS,
39   PROP_USE_CLIENT_SETTINGS,
40   PROP_LAST
41 };
42
43 enum
44 {
45   SIGNAL_CLOSED,
46   SIGNAL_NEW_SESSION,
47   SIGNAL_OPTIONS_REQUEST,
48   SIGNAL_DESCRIBE_REQUEST,
49   SIGNAL_SETUP_REQUEST,
50   SIGNAL_PLAY_REQUEST,
51   SIGNAL_PAUSE_REQUEST,
52   SIGNAL_TEARDOWN_REQUEST,
53   SIGNAL_SET_PARAMETER_REQUEST,
54   SIGNAL_GET_PARAMETER_REQUEST,
55   SIGNAL_LAST
56 };
57
58 GST_DEBUG_CATEGORY_STATIC (rtsp_client_debug);
59 #define GST_CAT_DEFAULT rtsp_client_debug
60
61 static guint gst_rtsp_client_signals[SIGNAL_LAST] = { 0 };
62
63 static void gst_rtsp_client_get_property (GObject * object, guint propid,
64     GValue * value, GParamSpec * pspec);
65 static void gst_rtsp_client_set_property (GObject * object, guint propid,
66     const GValue * value, GParamSpec * pspec);
67 static void gst_rtsp_client_finalize (GObject * obj);
68
69 static GstSDPMessage *create_sdp (GstRTSPClient * client, GstRTSPMedia * media);
70 static void client_session_finalized (GstRTSPClient * client,
71     GstRTSPSession * session);
72 static void unlink_session_transports (GstRTSPClient * client,
73     GstRTSPSession * session, GstRTSPSessionMedia * media);
74
75 G_DEFINE_TYPE (GstRTSPClient, gst_rtsp_client, G_TYPE_OBJECT);
76
77 static void
78 gst_rtsp_client_class_init (GstRTSPClientClass * klass)
79 {
80   GObjectClass *gobject_class;
81
82   gobject_class = G_OBJECT_CLASS (klass);
83
84   gobject_class->get_property = gst_rtsp_client_get_property;
85   gobject_class->set_property = gst_rtsp_client_set_property;
86   gobject_class->finalize = gst_rtsp_client_finalize;
87
88   klass->create_sdp = create_sdp;
89
90   g_object_class_install_property (gobject_class, PROP_SESSION_POOL,
91       g_param_spec_object ("session-pool", "Session Pool",
92           "The session pool to use for client session",
93           GST_TYPE_RTSP_SESSION_POOL,
94           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
95
96   g_object_class_install_property (gobject_class, PROP_MOUNT_POINTS,
97       g_param_spec_object ("mount-points", "Mount Points",
98           "The mount points to use for client session",
99           GST_TYPE_RTSP_MOUNT_POINTS,
100           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
101
102   g_object_class_install_property (gobject_class, PROP_USE_CLIENT_SETTINGS,
103       g_param_spec_boolean ("use-client-settings", "Use Client Settings",
104           "Use client settings for ttl and destination in multicast",
105           DEFAULT_USE_CLIENT_SETTINGS,
106           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
107
108   gst_rtsp_client_signals[SIGNAL_CLOSED] =
109       g_signal_new ("closed", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
110       G_STRUCT_OFFSET (GstRTSPClientClass, closed), NULL, NULL,
111       g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0, G_TYPE_NONE);
112
113   gst_rtsp_client_signals[SIGNAL_NEW_SESSION] =
114       g_signal_new ("new-session", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
115       G_STRUCT_OFFSET (GstRTSPClientClass, new_session), NULL, NULL,
116       g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1, GST_TYPE_RTSP_SESSION);
117
118   gst_rtsp_client_signals[SIGNAL_OPTIONS_REQUEST] =
119       g_signal_new ("options-request", G_TYPE_FROM_CLASS (klass),
120       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, options_request),
121       NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1,
122       G_TYPE_POINTER);
123
124   gst_rtsp_client_signals[SIGNAL_DESCRIBE_REQUEST] =
125       g_signal_new ("describe-request", G_TYPE_FROM_CLASS (klass),
126       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, describe_request),
127       NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1,
128       G_TYPE_POINTER);
129
130   gst_rtsp_client_signals[SIGNAL_SETUP_REQUEST] =
131       g_signal_new ("setup-request", G_TYPE_FROM_CLASS (klass),
132       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, setup_request),
133       NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1,
134       G_TYPE_POINTER);
135
136   gst_rtsp_client_signals[SIGNAL_PLAY_REQUEST] =
137       g_signal_new ("play-request", G_TYPE_FROM_CLASS (klass),
138       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, play_request),
139       NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1,
140       G_TYPE_POINTER);
141
142   gst_rtsp_client_signals[SIGNAL_PAUSE_REQUEST] =
143       g_signal_new ("pause-request", G_TYPE_FROM_CLASS (klass),
144       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, pause_request),
145       NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1,
146       G_TYPE_POINTER);
147
148   gst_rtsp_client_signals[SIGNAL_TEARDOWN_REQUEST] =
149       g_signal_new ("teardown-request", G_TYPE_FROM_CLASS (klass),
150       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, teardown_request),
151       NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1,
152       G_TYPE_POINTER);
153
154   gst_rtsp_client_signals[SIGNAL_SET_PARAMETER_REQUEST] =
155       g_signal_new ("set-parameter-request", G_TYPE_FROM_CLASS (klass),
156       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass,
157           set_parameter_request), NULL, NULL, g_cclosure_marshal_VOID__POINTER,
158       G_TYPE_NONE, 1, G_TYPE_POINTER);
159
160   gst_rtsp_client_signals[SIGNAL_GET_PARAMETER_REQUEST] =
161       g_signal_new ("get-parameter-request", G_TYPE_FROM_CLASS (klass),
162       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass,
163           get_parameter_request), NULL, NULL, g_cclosure_marshal_VOID__POINTER,
164       G_TYPE_NONE, 1, G_TYPE_POINTER);
165
166   tunnels =
167       g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_object_unref);
168   g_mutex_init (&tunnels_lock);
169
170   GST_DEBUG_CATEGORY_INIT (rtsp_client_debug, "rtspclient", 0, "GstRTSPClient");
171 }
172
173 static void
174 gst_rtsp_client_init (GstRTSPClient * client)
175 {
176   g_mutex_init (&client->lock);
177   client->use_client_settings = DEFAULT_USE_CLIENT_SETTINGS;
178   client->close_response_seq = 0;
179 }
180
181 static void
182 client_unlink_session (GstRTSPClient * client, GstRTSPSession * session)
183 {
184   /* unlink all media managed in this session */
185   while (session->medias) {
186     GstRTSPSessionMedia *media = session->medias->data;
187
188     gst_rtsp_session_media_set_state (media, GST_STATE_NULL);
189     unlink_session_transports (client, session, media);
190     /* unmanage the media in the session. this will modify session->medias */
191     gst_rtsp_session_release_media (session, media);
192   }
193 }
194
195 static void
196 client_cleanup_sessions (GstRTSPClient * client)
197 {
198   GList *sessions;
199
200   /* remove weak-ref from sessions */
201   for (sessions = client->sessions; sessions; sessions = g_list_next (sessions)) {
202     GstRTSPSession *session = (GstRTSPSession *) sessions->data;
203     g_object_weak_unref (G_OBJECT (session),
204         (GWeakNotify) client_session_finalized, client);
205     client_unlink_session (client, session);
206   }
207   g_list_free (client->sessions);
208   client->sessions = NULL;
209 }
210
211 /* A client is finalized when the connection is broken */
212 static void
213 gst_rtsp_client_finalize (GObject * obj)
214 {
215   GstRTSPClient *client = GST_RTSP_CLIENT (obj);
216
217   GST_INFO ("finalize client %p", client);
218
219   if (client->watch)
220     g_source_destroy ((GSource *) client->watch);
221
222   client_cleanup_sessions (client);
223
224   gst_rtsp_connection_free (client->connection);
225   if (client->session_pool)
226     g_object_unref (client->session_pool);
227   if (client->mount_points)
228     g_object_unref (client->mount_points);
229   if (client->auth)
230     g_object_unref (client->auth);
231
232   if (client->uri)
233     gst_rtsp_url_free (client->uri);
234   if (client->media) {
235     gst_rtsp_media_unprepare (client->media);
236     g_object_unref (client->media);
237   }
238
239   g_free (client->server_ip);
240   g_mutex_clear (&client->lock);
241
242   G_OBJECT_CLASS (gst_rtsp_client_parent_class)->finalize (obj);
243 }
244
245 static void
246 gst_rtsp_client_get_property (GObject * object, guint propid,
247     GValue * value, GParamSpec * pspec)
248 {
249   GstRTSPClient *client = GST_RTSP_CLIENT (object);
250
251   switch (propid) {
252     case PROP_SESSION_POOL:
253       g_value_take_object (value, gst_rtsp_client_get_session_pool (client));
254       break;
255     case PROP_MOUNT_POINTS:
256       g_value_take_object (value, gst_rtsp_client_get_mount_points (client));
257       break;
258     case PROP_USE_CLIENT_SETTINGS:
259       g_value_set_boolean (value,
260           gst_rtsp_client_get_use_client_settings (client));
261       break;
262     default:
263       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, propid, pspec);
264   }
265 }
266
267 static void
268 gst_rtsp_client_set_property (GObject * object, guint propid,
269     const GValue * value, GParamSpec * pspec)
270 {
271   GstRTSPClient *client = GST_RTSP_CLIENT (object);
272
273   switch (propid) {
274     case PROP_SESSION_POOL:
275       gst_rtsp_client_set_session_pool (client, g_value_get_object (value));
276       break;
277     case PROP_MOUNT_POINTS:
278       gst_rtsp_client_set_mount_points (client, g_value_get_object (value));
279       break;
280     case PROP_USE_CLIENT_SETTINGS:
281       gst_rtsp_client_set_use_client_settings (client,
282           g_value_get_boolean (value));
283       break;
284     default:
285       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, propid, pspec);
286   }
287 }
288
289 /**
290  * gst_rtsp_client_new:
291  *
292  * Create a new #GstRTSPClient instance.
293  *
294  * Returns: a new #GstRTSPClient
295  */
296 GstRTSPClient *
297 gst_rtsp_client_new (void)
298 {
299   GstRTSPClient *result;
300
301   result = g_object_new (GST_TYPE_RTSP_CLIENT, NULL);
302
303   return result;
304 }
305
306 static void
307 send_response (GstRTSPClient * client, GstRTSPSession * session,
308     GstRTSPMessage * response, gboolean close)
309 {
310   gst_rtsp_message_add_header (response, GST_RTSP_HDR_SERVER,
311       "GStreamer RTSP server");
312
313   /* remove any previous header */
314   gst_rtsp_message_remove_header (response, GST_RTSP_HDR_SESSION, -1);
315
316   /* add the new session header for new session ids */
317   if (session) {
318     gst_rtsp_message_take_header (response, GST_RTSP_HDR_SESSION,
319         gst_rtsp_session_get_header (session));
320   }
321
322   if (gst_debug_category_get_threshold (rtsp_client_debug) >= GST_LEVEL_LOG) {
323     gst_rtsp_message_dump (response);
324   }
325
326   if (close) {
327     gst_rtsp_message_add_header (response, GST_RTSP_HDR_CONNECTION, "close");
328   }
329   /* send the response and store the seq number so we can wait until it's
330    * written to the client to close the connection */
331   gst_rtsp_watch_send_message (client->watch, response, close ?
332       &client->close_response_seq : NULL);
333   gst_rtsp_message_unset (response);
334 }
335
336 static void
337 send_generic_response (GstRTSPClient * client, GstRTSPStatusCode code,
338     GstRTSPClientState * state)
339 {
340   gst_rtsp_message_init_response (state->response, code,
341       gst_rtsp_status_as_text (code), state->request);
342
343   send_response (client, NULL, state->response, FALSE);
344 }
345
346 static void
347 handle_unauthorized_request (GstRTSPClient * client, GstRTSPAuth * auth,
348     GstRTSPClientState * state)
349 {
350   gst_rtsp_message_init_response (state->response, GST_RTSP_STS_UNAUTHORIZED,
351       gst_rtsp_status_as_text (GST_RTSP_STS_UNAUTHORIZED), state->request);
352
353   if (auth) {
354     /* and let the authentication manager setup the auth tokens */
355     gst_rtsp_auth_setup_auth (auth, client, 0, state);
356   }
357
358   send_response (client, state->session, state->response, FALSE);
359 }
360
361
362 static gboolean
363 compare_uri (const GstRTSPUrl * uri1, const GstRTSPUrl * uri2)
364 {
365   if (uri1 == NULL || uri2 == NULL)
366     return FALSE;
367
368   if (strcmp (uri1->abspath, uri2->abspath))
369     return FALSE;
370
371   return TRUE;
372 }
373
374 /* this function is called to initially find the media for the DESCRIBE request
375  * but is cached for when the same client (without breaking the connection) is
376  * doing a setup for the exact same url. */
377 static GstRTSPMedia *
378 find_media (GstRTSPClient * client, GstRTSPClientState * state)
379 {
380   GstRTSPMediaFactory *factory;
381   GstRTSPMedia *media;
382   GstRTSPAuth *auth;
383
384   if (!compare_uri (client->uri, state->uri)) {
385     /* remove any previously cached values before we try to construct a new
386      * media for uri */
387     if (client->uri)
388       gst_rtsp_url_free (client->uri);
389     client->uri = NULL;
390     if (client->media) {
391       gst_rtsp_media_unprepare (client->media);
392       g_object_unref (client->media);
393     }
394     client->media = NULL;
395
396     if (!client->mount_points)
397       goto no_mount_points;
398
399     /* find the factory for the uri first */
400     if (!(factory =
401             gst_rtsp_mount_points_find_factory (client->mount_points,
402                 state->uri)))
403       goto no_factory;
404
405     state->factory = factory;
406
407     /* check if we have access to the factory */
408     if ((auth = gst_rtsp_media_factory_get_auth (factory))) {
409       if (!gst_rtsp_auth_check (auth, client, 0, state))
410         goto not_allowed;
411
412       g_object_unref (auth);
413     }
414
415     /* prepare the media and add it to the pipeline */
416     if (!(media = gst_rtsp_media_factory_construct (factory, state->uri)))
417       goto no_media;
418
419     g_object_unref (factory);
420     factory = NULL;
421     state->factory = NULL;
422
423     /* set ipv6 on the media before preparing */
424     media->is_ipv6 = client->is_ipv6;
425     state->media = media;
426
427     /* prepare the media */
428     if (!(gst_rtsp_media_prepare (media)))
429       goto no_prepare;
430
431     /* now keep track of the uri and the media */
432     client->uri = gst_rtsp_url_copy (state->uri);
433     client->media = media;
434   } else {
435     /* we have seen this uri before, used cached media */
436     media = client->media;
437     state->media = media;
438     GST_INFO ("reusing cached media %p", media);
439   }
440
441   if (media)
442     g_object_ref (media);
443
444   return media;
445
446   /* ERRORS */
447 no_mount_points:
448   {
449     GST_ERROR ("client %p: no mount points configured", client);
450     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, state);
451     return NULL;
452   }
453 no_factory:
454   {
455     GST_ERROR ("client %p: no factory for uri", client);
456     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, state);
457     return NULL;
458   }
459 not_allowed:
460   {
461     GST_ERROR ("client %p: unauthorized request", client);
462     handle_unauthorized_request (client, auth, state);
463     g_object_unref (factory);
464     g_object_unref (auth);
465     return NULL;
466   }
467 no_media:
468   {
469     GST_ERROR ("client %p: can't create media", client);
470     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, state);
471     g_object_unref (factory);
472     return NULL;
473   }
474 no_prepare:
475   {
476     GST_ERROR ("client %p: can't prepare media", client);
477     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, state);
478     g_object_unref (media);
479     return NULL;
480   }
481 }
482
483 static gboolean
484 do_send_data (GstBuffer * buffer, guint8 channel, GstRTSPClient * client)
485 {
486   GstRTSPMessage message = { 0 };
487   GstMapInfo map_info;
488   guint8 *data;
489   guint usize;
490
491   gst_rtsp_message_init_data (&message, channel);
492
493   /* FIXME, need some sort of iovec RTSPMessage here */
494   if (!gst_buffer_map (buffer, &map_info, GST_MAP_READ))
495     return FALSE;
496
497   gst_rtsp_message_take_body (&message, map_info.data, map_info.size);
498
499   /* FIXME, client->watch could have been finalized here, we need to keep an
500    * extra refcount to the watch.  */
501   gst_rtsp_watch_send_message (client->watch, &message, NULL);
502
503   gst_rtsp_message_steal_body (&message, &data, &usize);
504   gst_buffer_unmap (buffer, &map_info);
505
506   gst_rtsp_message_unset (&message);
507
508   return TRUE;
509 }
510
511 static void
512 link_transport (GstRTSPClient * client, GstRTSPSession * session,
513     GstRTSPStreamTransport * trans)
514 {
515   GST_DEBUG ("client %p: linking transport %p", client, trans);
516   gst_rtsp_stream_transport_set_callbacks (trans,
517       (GstRTSPSendFunc) do_send_data,
518       (GstRTSPSendFunc) do_send_data, client, NULL);
519
520   client->transports = g_list_prepend (client->transports, trans);
521
522   /* make sure our session can't expire */
523   gst_rtsp_session_prevent_expire (session);
524 }
525
526 static void
527 unlink_transport (GstRTSPClient * client, GstRTSPSession * session,
528     GstRTSPStreamTransport * trans)
529 {
530   GST_DEBUG ("client %p: unlinking transport %p", client, trans);
531   gst_rtsp_stream_transport_set_callbacks (trans, NULL, NULL, NULL, NULL);
532
533   client->transports = g_list_remove (client->transports, trans);
534
535   /* our session can now expire */
536   gst_rtsp_session_allow_expire (session);
537 }
538
539 static void
540 unlink_session_transports (GstRTSPClient * client, GstRTSPSession * session,
541     GstRTSPSessionMedia * media)
542 {
543   guint n_streams, i;
544
545   n_streams = gst_rtsp_media_n_streams (media->media);
546   for (i = 0; i < n_streams; i++) {
547     GstRTSPStreamTransport *trans;
548     GstRTSPTransport *tr;
549
550     /* get the transport, if there is no transport configured, skip this stream */
551     trans = gst_rtsp_session_media_get_transport (media, i);
552     if (trans == NULL)
553       continue;
554
555     tr = trans->transport;
556
557     if (tr->lower_transport == GST_RTSP_LOWER_TRANS_TCP) {
558       /* for TCP, unlink the stream from the TCP connection of the client */
559       unlink_transport (client, session, trans);
560     }
561   }
562 }
563
564 static void
565 close_connection (GstRTSPClient * client)
566 {
567   const gchar *tunnelid;
568
569   GST_DEBUG ("client %p: closing connection", client);
570
571   if ((tunnelid = gst_rtsp_connection_get_tunnelid (client->connection))) {
572     g_mutex_lock (&tunnels_lock);
573     /* remove from tunnelids */
574     g_hash_table_remove (tunnels, tunnelid);
575     g_mutex_unlock (&tunnels_lock);
576   }
577
578   gst_rtsp_connection_close (client->connection);
579 }
580
581 static gboolean
582 handle_teardown_request (GstRTSPClient * client, GstRTSPClientState * state)
583 {
584   GstRTSPSession *session;
585   GstRTSPSessionMedia *media;
586   GstRTSPStatusCode code;
587
588   if (!state->session)
589     goto no_session;
590
591   session = state->session;
592
593   /* get a handle to the configuration of the media in the session */
594   media = gst_rtsp_session_get_media (session, state->uri);
595   if (!media)
596     goto not_found;
597
598   state->sessmedia = media;
599
600   /* unlink the all TCP callbacks */
601   unlink_session_transports (client, session, media);
602
603   /* remove the session from the watched sessions */
604   g_object_weak_unref (G_OBJECT (session),
605       (GWeakNotify) client_session_finalized, client);
606   client->sessions = g_list_remove (client->sessions, session);
607
608   gst_rtsp_session_media_set_state (media, GST_STATE_NULL);
609
610   /* unmanage the media in the session, returns false if all media session
611    * are torn down. */
612   if (!gst_rtsp_session_release_media (session, media)) {
613     /* remove the session */
614     gst_rtsp_session_pool_remove (client->session_pool, session);
615   }
616   /* construct the response now */
617   code = GST_RTSP_STS_OK;
618   gst_rtsp_message_init_response (state->response, code,
619       gst_rtsp_status_as_text (code), state->request);
620
621   send_response (client, session, state->response, TRUE);
622
623   /* we emit the signal before closing the connection */
624   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_TEARDOWN_REQUEST],
625       0, state);
626
627   return TRUE;
628
629   /* ERRORS */
630 no_session:
631   {
632     GST_ERROR ("client %p: no session", client);
633     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, state);
634     return FALSE;
635   }
636 not_found:
637   {
638     GST_ERROR ("client %p: no media for uri", client);
639     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, state);
640     return FALSE;
641   }
642 }
643
644 static gboolean
645 handle_get_param_request (GstRTSPClient * client, GstRTSPClientState * state)
646 {
647   GstRTSPResult res;
648   guint8 *data;
649   guint size;
650
651   res = gst_rtsp_message_get_body (state->request, &data, &size);
652   if (res != GST_RTSP_OK)
653     goto bad_request;
654
655   if (size == 0) {
656     /* no body, keep-alive request */
657     send_generic_response (client, GST_RTSP_STS_OK, state);
658   } else {
659     /* there is a body, handle the params */
660     res = gst_rtsp_params_get (client, state);
661     if (res != GST_RTSP_OK)
662       goto bad_request;
663
664     send_response (client, state->session, state->response, FALSE);
665   }
666
667   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_GET_PARAMETER_REQUEST],
668       0, state);
669
670   return TRUE;
671
672   /* ERRORS */
673 bad_request:
674   {
675     GST_ERROR ("client %p: bad request", client);
676     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, state);
677     return FALSE;
678   }
679 }
680
681 static gboolean
682 handle_set_param_request (GstRTSPClient * client, GstRTSPClientState * state)
683 {
684   GstRTSPResult res;
685   guint8 *data;
686   guint size;
687
688   res = gst_rtsp_message_get_body (state->request, &data, &size);
689   if (res != GST_RTSP_OK)
690     goto bad_request;
691
692   if (size == 0) {
693     /* no body, keep-alive request */
694     send_generic_response (client, GST_RTSP_STS_OK, state);
695   } else {
696     /* there is a body, handle the params */
697     res = gst_rtsp_params_set (client, state);
698     if (res != GST_RTSP_OK)
699       goto bad_request;
700
701     send_response (client, state->session, state->response, FALSE);
702   }
703
704   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_SET_PARAMETER_REQUEST],
705       0, state);
706
707   return TRUE;
708
709   /* ERRORS */
710 bad_request:
711   {
712     GST_ERROR ("client %p: bad request", client);
713     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, state);
714     return FALSE;
715   }
716 }
717
718 static gboolean
719 handle_pause_request (GstRTSPClient * client, GstRTSPClientState * state)
720 {
721   GstRTSPSession *session;
722   GstRTSPSessionMedia *media;
723   GstRTSPStatusCode code;
724
725   if (!(session = state->session))
726     goto no_session;
727
728   /* get a handle to the configuration of the media in the session */
729   media = gst_rtsp_session_get_media (session, state->uri);
730   if (!media)
731     goto not_found;
732
733   state->sessmedia = media;
734
735   /* the session state must be playing or recording */
736   if (media->state != GST_RTSP_STATE_PLAYING &&
737       media->state != GST_RTSP_STATE_RECORDING)
738     goto invalid_state;
739
740   /* unlink the all TCP callbacks */
741   unlink_session_transports (client, session, media);
742
743   /* then pause sending */
744   gst_rtsp_session_media_set_state (media, GST_STATE_PAUSED);
745
746   /* construct the response now */
747   code = GST_RTSP_STS_OK;
748   gst_rtsp_message_init_response (state->response, code,
749       gst_rtsp_status_as_text (code), state->request);
750
751   send_response (client, session, state->response, FALSE);
752
753   /* the state is now READY */
754   media->state = GST_RTSP_STATE_READY;
755
756   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_PAUSE_REQUEST],
757       0, state);
758
759   return TRUE;
760
761   /* ERRORS */
762 no_session:
763   {
764     GST_ERROR ("client %p: no seesion", client);
765     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, state);
766     return FALSE;
767   }
768 not_found:
769   {
770     GST_ERROR ("client %p: no media for uri", client);
771     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, state);
772     return FALSE;
773   }
774 invalid_state:
775   {
776     GST_ERROR ("client %p: not PLAYING or RECORDING", client);
777     send_generic_response (client, GST_RTSP_STS_METHOD_NOT_VALID_IN_THIS_STATE,
778         state);
779     return FALSE;
780   }
781 }
782
783 static gboolean
784 handle_play_request (GstRTSPClient * client, GstRTSPClientState * state)
785 {
786   GstRTSPSession *session;
787   GstRTSPSessionMedia *media;
788   GstRTSPStatusCode code;
789   GString *rtpinfo;
790   guint n_streams, i, infocount;
791   gchar *str;
792   GstRTSPTimeRange *range;
793   GstRTSPResult res;
794
795   if (!(session = state->session))
796     goto no_session;
797
798   /* get a handle to the configuration of the media in the session */
799   media = gst_rtsp_session_get_media (session, state->uri);
800   if (!media)
801     goto not_found;
802
803   state->sessmedia = media;
804
805   /* the session state must be playing or ready */
806   if (media->state != GST_RTSP_STATE_PLAYING &&
807       media->state != GST_RTSP_STATE_READY)
808     goto invalid_state;
809
810   /* parse the range header if we have one */
811   res =
812       gst_rtsp_message_get_header (state->request, GST_RTSP_HDR_RANGE, &str, 0);
813   if (res == GST_RTSP_OK) {
814     if (gst_rtsp_range_parse (str, &range) == GST_RTSP_OK) {
815       /* we have a range, seek to the position */
816       gst_rtsp_media_seek (media->media, range);
817       gst_rtsp_range_free (range);
818     }
819   }
820
821   /* grab RTPInfo from the payloaders now */
822   rtpinfo = g_string_new ("");
823
824   n_streams = gst_rtsp_media_n_streams (media->media);
825   for (i = 0, infocount = 0; i < n_streams; i++) {
826     GstRTSPStreamTransport *trans;
827     GstRTSPTransport *tr;
828     gchar *uristr;
829     guint rtptime, seq;
830
831     /* get the transport, if there is no transport configured, skip this stream */
832     trans = gst_rtsp_session_media_get_transport (media, i);
833     if (trans == NULL) {
834       GST_INFO ("stream %d is not configured", i);
835       continue;
836     }
837     tr = trans->transport;
838
839     if (tr->lower_transport == GST_RTSP_LOWER_TRANS_TCP) {
840       /* for TCP, link the stream to the TCP connection of the client */
841       link_transport (client, session, trans);
842     }
843
844     if (gst_rtsp_stream_get_rtpinfo (trans->stream, &rtptime, &seq)) {
845       if (infocount > 0)
846         g_string_append (rtpinfo, ", ");
847
848       uristr = gst_rtsp_url_get_request_uri (state->uri);
849       g_string_append_printf (rtpinfo, "url=%s/stream=%d;seq=%u;rtptime=%u",
850           uristr, i, seq, rtptime);
851       g_free (uristr);
852
853       infocount++;
854     } else {
855       GST_WARNING ("RTP-Info cannot be determined for stream %d", i);
856     }
857   }
858
859   /* construct the response now */
860   code = GST_RTSP_STS_OK;
861   gst_rtsp_message_init_response (state->response, code,
862       gst_rtsp_status_as_text (code), state->request);
863
864   /* add the RTP-Info header */
865   if (infocount > 0) {
866     str = g_string_free (rtpinfo, FALSE);
867     gst_rtsp_message_take_header (state->response, GST_RTSP_HDR_RTP_INFO, str);
868   } else {
869     g_string_free (rtpinfo, TRUE);
870   }
871
872   /* add the range */
873   str = gst_rtsp_media_get_range_string (media->media, TRUE);
874   gst_rtsp_message_take_header (state->response, GST_RTSP_HDR_RANGE, str);
875
876   send_response (client, session, state->response, FALSE);
877
878   /* start playing after sending the request */
879   gst_rtsp_session_media_set_state (media, GST_STATE_PLAYING);
880
881   media->state = GST_RTSP_STATE_PLAYING;
882
883   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_PLAY_REQUEST],
884       0, state);
885
886   return TRUE;
887
888   /* ERRORS */
889 no_session:
890   {
891     GST_ERROR ("client %p: no session", client);
892     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, state);
893     return FALSE;
894   }
895 not_found:
896   {
897     GST_ERROR ("client %p: media not found", client);
898     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, state);
899     return FALSE;
900   }
901 invalid_state:
902   {
903     GST_ERROR ("client %p: not PLAYING or READY", client);
904     send_generic_response (client, GST_RTSP_STS_METHOD_NOT_VALID_IN_THIS_STATE,
905         state);
906     return FALSE;
907   }
908 }
909
910 static void
911 do_keepalive (GstRTSPSession * session)
912 {
913   GST_INFO ("keep session %p alive", session);
914   gst_rtsp_session_touch (session);
915 }
916
917 /* parse @transport and return a valid transport in @tr. only transports
918  * from @supported are returned. Returns FALSE if no valid transport
919  * was found. */
920 static gboolean
921 parse_transport (const char *transport, GstRTSPLowerTrans supported,
922     GstRTSPTransport * tr)
923 {
924   gint i;
925   gboolean res;
926   gchar **transports;
927
928   res = FALSE;
929   gst_rtsp_transport_init (tr);
930
931   GST_DEBUG ("parsing transports %s", transport);
932
933   transports = g_strsplit (transport, ",", 0);
934
935   /* loop through the transports, try to parse */
936   for (i = 0; transports[i]; i++) {
937     res = gst_rtsp_transport_parse (transports[i], tr);
938     if (res != GST_RTSP_OK) {
939       /* no valid transport, search some more */
940       GST_WARNING ("could not parse transport %s", transports[i]);
941       goto next;
942     }
943
944     /* we have a transport, see if it's RTP/AVP */
945     if (tr->trans != GST_RTSP_TRANS_RTP || tr->profile != GST_RTSP_PROFILE_AVP) {
946       GST_WARNING ("invalid transport %s", transports[i]);
947       goto next;
948     }
949
950     if (!(tr->lower_transport & supported)) {
951       GST_WARNING ("unsupported transport %s", transports[i]);
952       goto next;
953     }
954
955     /* we have a valid transport */
956     GST_INFO ("found valid transport %s", transports[i]);
957     res = TRUE;
958     break;
959
960   next:
961     gst_rtsp_transport_init (tr);
962   }
963   g_strfreev (transports);
964
965   return res;
966 }
967
968 static gboolean
969 handle_blocksize (GstRTSPMedia * media, GstRTSPStream * stream,
970     GstRTSPMessage * request)
971 {
972   gchar *blocksize_str;
973   gboolean ret = TRUE;
974
975   if (gst_rtsp_message_get_header (request, GST_RTSP_HDR_BLOCKSIZE,
976           &blocksize_str, 0) == GST_RTSP_OK) {
977     guint64 blocksize;
978     gchar *end;
979
980     blocksize = g_ascii_strtoull (blocksize_str, &end, 10);
981     if (end == blocksize_str) {
982       GST_ERROR ("failed to parse blocksize");
983       ret = FALSE;
984     } else {
985       /* we don't want to change the mtu when this media
986        * can be shared because it impacts other clients */
987       if (gst_rtsp_media_is_shared (media))
988         return TRUE;
989
990       if (blocksize > G_MAXUINT)
991         blocksize = G_MAXUINT;
992       gst_rtsp_stream_set_mtu (stream, blocksize);
993     }
994   }
995   return ret;
996 }
997
998 static gboolean
999 configure_client_transport (GstRTSPClient * client, GstRTSPClientState * state,
1000     GstRTSPTransport * ct)
1001 {
1002   /* we have a valid transport now, set the destination of the client. */
1003   if (ct->lower_transport == GST_RTSP_LOWER_TRANS_UDP_MCAST) {
1004     if (ct->destination == NULL || !client->use_client_settings) {
1005       GstRTSPAddress *addr;
1006
1007       addr = gst_rtsp_stream_get_address (state->stream);
1008       if (addr == NULL)
1009         goto no_address;
1010
1011       g_free (ct->destination);
1012       ct->destination = g_strdup (addr->address);
1013       ct->port.min = addr->port;
1014       ct->port.max = addr->port + addr->n_ports - 1;
1015       ct->ttl = addr->ttl;
1016     }
1017   } else {
1018     GstRTSPUrl *url;
1019
1020     url = gst_rtsp_connection_get_url (client->connection);
1021     g_free (ct->destination);
1022     ct->destination = g_strdup (url->host);
1023
1024     if (ct->lower_transport & GST_RTSP_LOWER_TRANS_TCP) {
1025       /* check if the client selected channels for TCP */
1026       if (ct->interleaved.min == -1 || ct->interleaved.max == -1) {
1027         gst_rtsp_session_media_alloc_channels (state->sessmedia,
1028             &ct->interleaved);
1029       }
1030     }
1031   }
1032   return TRUE;
1033
1034   /* ERRORS */
1035 no_address:
1036   {
1037     GST_ERROR_OBJECT (client, "failed to acquire address for stream");
1038     return FALSE;
1039   }
1040 }
1041
1042 static GstRTSPTransport *
1043 make_server_transport (GstRTSPClient * client, GstRTSPClientState * state,
1044     GstRTSPTransport * ct)
1045 {
1046   GstRTSPTransport *st;
1047
1048   /* prepare the server transport */
1049   gst_rtsp_transport_new (&st);
1050
1051   st->trans = ct->trans;
1052   st->profile = ct->profile;
1053   st->lower_transport = ct->lower_transport;
1054
1055   switch (st->lower_transport) {
1056     case GST_RTSP_LOWER_TRANS_UDP:
1057       st->client_port = ct->client_port;
1058       st->server_port = state->stream->server_port;
1059       break;
1060     case GST_RTSP_LOWER_TRANS_UDP_MCAST:
1061       st->port = ct->port;
1062       st->destination = g_strdup (ct->destination);
1063       st->ttl = ct->ttl;
1064       break;
1065     case GST_RTSP_LOWER_TRANS_TCP:
1066       st->interleaved = ct->interleaved;
1067     default:
1068       break;
1069   }
1070
1071   if (state->stream->session)
1072     g_object_get (state->stream->session, "internal-ssrc", &st->ssrc, NULL);
1073
1074   return st;
1075 }
1076
1077 static gboolean
1078 handle_setup_request (GstRTSPClient * client, GstRTSPClientState * state)
1079 {
1080   GstRTSPResult res;
1081   GstRTSPUrl *uri;
1082   gchar *transport;
1083   GstRTSPTransport *ct, *st;
1084   GstRTSPLowerTrans supported;
1085   GstRTSPStatusCode code;
1086   GstRTSPSession *session;
1087   GstRTSPStreamTransport *trans;
1088   gchar *trans_str, *pos;
1089   guint streamid;
1090   GstRTSPSessionMedia *sessmedia;
1091   GstRTSPMedia *media;
1092   GstRTSPStream *stream;
1093
1094   uri = state->uri;
1095
1096   /* the uri contains the stream number we added in the SDP config, which is
1097    * always /stream=%d so we need to strip that off
1098    * parse the stream we need to configure, look for the stream in the abspath
1099    * first and then in the query. */
1100   if (uri->abspath == NULL || !(pos = strstr (uri->abspath, "/stream="))) {
1101     if (uri->query == NULL || !(pos = strstr (uri->query, "/stream=")))
1102       goto bad_request;
1103   }
1104
1105   /* we can mofify the parsed uri in place */
1106   *pos = '\0';
1107
1108   pos += strlen ("/stream=");
1109   if (sscanf (pos, "%u", &streamid) != 1)
1110     goto bad_request;
1111
1112   /* parse the transport */
1113   res =
1114       gst_rtsp_message_get_header (state->request, GST_RTSP_HDR_TRANSPORT,
1115       &transport, 0);
1116   if (res != GST_RTSP_OK)
1117     goto no_transport;
1118
1119   gst_rtsp_transport_new (&ct);
1120
1121   /* our supported transports */
1122   supported = GST_RTSP_LOWER_TRANS_UDP |
1123       GST_RTSP_LOWER_TRANS_UDP_MCAST | GST_RTSP_LOWER_TRANS_TCP;
1124
1125   /* parse and find a usable supported transport */
1126   if (!parse_transport (transport, supported, ct))
1127     goto unsupported_transports;
1128
1129   /* we create the session after parsing stuff so that we don't make
1130    * a session for malformed requests */
1131   if (client->session_pool == NULL)
1132     goto no_pool;
1133
1134   session = state->session;
1135
1136   if (session) {
1137     g_object_ref (session);
1138     /* get a handle to the configuration of the media in the session, this can
1139      * return NULL if this is a new url to manage in this session. */
1140     sessmedia = gst_rtsp_session_get_media (session, uri);
1141   } else {
1142     /* create a session if this fails we probably reached our session limit or
1143      * something. */
1144     if (!(session = gst_rtsp_session_pool_create (client->session_pool)))
1145       goto service_unavailable;
1146
1147     state->session = session;
1148
1149     /* we need a new media configuration in this session */
1150     sessmedia = NULL;
1151   }
1152
1153   /* we have no media, find one and manage it */
1154   if (sessmedia == NULL) {
1155     /* get a handle to the configuration of the media in the session */
1156     if ((media = find_media (client, state))) {
1157       /* manage the media in our session now */
1158       sessmedia = gst_rtsp_session_manage_media (session, uri, media);
1159     }
1160   }
1161
1162   /* if we stil have no media, error */
1163   if (sessmedia == NULL)
1164     goto not_found;
1165
1166   state->sessmedia = sessmedia;
1167   state->media = media = sessmedia->media;
1168
1169   /* now get the stream */
1170   stream = gst_rtsp_media_get_stream (media, streamid);
1171   if (stream == NULL)
1172     goto not_found;
1173
1174   state->stream = stream;
1175
1176   /* set blocksize on this stream */
1177   if (!handle_blocksize (media, stream, state->request))
1178     goto invalid_blocksize;
1179
1180   /* update the client transport */
1181   if (!configure_client_transport (client, state, ct))
1182     goto unsupported_client_transport;
1183
1184   /* set in the session media transport */
1185   trans = gst_rtsp_session_media_set_transport (sessmedia, stream, ct);
1186
1187   /* configure keepalive for this transport */
1188   gst_rtsp_stream_transport_set_keepalive (trans,
1189       (GstRTSPKeepAliveFunc) do_keepalive, session, NULL);
1190
1191   /* create and serialize the server transport */
1192   st = make_server_transport (client, state, ct);
1193   trans_str = gst_rtsp_transport_as_text (st);
1194   gst_rtsp_transport_free (st);
1195
1196   /* construct the response now */
1197   code = GST_RTSP_STS_OK;
1198   gst_rtsp_message_init_response (state->response, code,
1199       gst_rtsp_status_as_text (code), state->request);
1200
1201   gst_rtsp_message_add_header (state->response, GST_RTSP_HDR_TRANSPORT,
1202       trans_str);
1203   g_free (trans_str);
1204
1205   send_response (client, session, state->response, FALSE);
1206
1207   /* update the state */
1208   switch (sessmedia->state) {
1209     case GST_RTSP_STATE_PLAYING:
1210     case GST_RTSP_STATE_RECORDING:
1211     case GST_RTSP_STATE_READY:
1212       /* no state change */
1213       break;
1214     default:
1215       sessmedia->state = GST_RTSP_STATE_READY;
1216       break;
1217   }
1218   g_object_unref (session);
1219
1220   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_SETUP_REQUEST],
1221       0, state);
1222
1223   return TRUE;
1224
1225   /* ERRORS */
1226 bad_request:
1227   {
1228     GST_ERROR ("client %p: bad request", client);
1229     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, state);
1230     return FALSE;
1231   }
1232 not_found:
1233   {
1234     GST_ERROR ("client %p: media not found", client);
1235     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, state);
1236     g_object_unref (session);
1237     gst_rtsp_transport_free (ct);
1238     return FALSE;
1239   }
1240 invalid_blocksize:
1241   {
1242     GST_ERROR ("client %p: invalid blocksize", client);
1243     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, state);
1244     g_object_unref (session);
1245     gst_rtsp_transport_free (ct);
1246     return FALSE;
1247   }
1248 unsupported_client_transport:
1249   {
1250     GST_ERROR ("client %p: unsupported client transport", client);
1251     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, state);
1252     g_object_unref (session);
1253     gst_rtsp_transport_free (ct);
1254     return FALSE;
1255   }
1256 no_transport:
1257   {
1258     GST_ERROR ("client %p: no transport", client);
1259     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, state);
1260     return FALSE;
1261   }
1262 unsupported_transports:
1263   {
1264     GST_ERROR ("client %p: unsupported transports", client);
1265     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, state);
1266     gst_rtsp_transport_free (ct);
1267     return FALSE;
1268   }
1269 no_pool:
1270   {
1271     GST_ERROR ("client %p: no session pool configured", client);
1272     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, state);
1273     gst_rtsp_transport_free (ct);
1274     return FALSE;
1275   }
1276 service_unavailable:
1277   {
1278     GST_ERROR ("client %p: can't create session", client);
1279     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, state);
1280     gst_rtsp_transport_free (ct);
1281     return FALSE;
1282   }
1283 }
1284
1285 static GstSDPMessage *
1286 create_sdp (GstRTSPClient * client, GstRTSPMedia * media)
1287 {
1288   GstSDPMessage *sdp;
1289   GstSDPInfo info;
1290   const gchar *proto;
1291
1292   gst_sdp_message_new (&sdp);
1293
1294   /* some standard things first */
1295   gst_sdp_message_set_version (sdp, "0");
1296
1297   if (client->is_ipv6)
1298     proto = "IP6";
1299   else
1300     proto = "IP4";
1301
1302   gst_sdp_message_set_origin (sdp, "-", "1188340656180883", "1", "IN", proto,
1303       client->server_ip);
1304
1305   gst_sdp_message_set_session_name (sdp, "Session streamed with GStreamer");
1306   gst_sdp_message_set_information (sdp, "rtsp-server");
1307   gst_sdp_message_add_time (sdp, "0", "0", NULL);
1308   gst_sdp_message_add_attribute (sdp, "tool", "GStreamer");
1309   gst_sdp_message_add_attribute (sdp, "type", "broadcast");
1310   gst_sdp_message_add_attribute (sdp, "control", "*");
1311
1312   info.server_proto = proto;
1313   info.server_ip = g_strdup (client->server_ip);
1314
1315   /* create an SDP for the media object */
1316   if (!gst_rtsp_sdp_from_media (sdp, &info, media))
1317     goto no_sdp;
1318
1319   g_free (info.server_ip);
1320
1321   return sdp;
1322
1323   /* ERRORS */
1324 no_sdp:
1325   {
1326     GST_ERROR ("client %p: could not create SDP", client);
1327     g_free (info.server_ip);
1328     gst_sdp_message_free (sdp);
1329     return NULL;
1330   }
1331 }
1332
1333 /* for the describe we must generate an SDP */
1334 static gboolean
1335 handle_describe_request (GstRTSPClient * client, GstRTSPClientState * state)
1336 {
1337   GstRTSPResult res;
1338   GstSDPMessage *sdp;
1339   guint i, str_len;
1340   gchar *str, *content_base;
1341   GstRTSPMedia *media;
1342   GstRTSPClientClass *klass;
1343
1344   klass = GST_RTSP_CLIENT_GET_CLASS (client);
1345
1346   /* check what kind of format is accepted, we don't really do anything with it
1347    * and always return SDP for now. */
1348   for (i = 0; i++;) {
1349     gchar *accept;
1350
1351     res =
1352         gst_rtsp_message_get_header (state->request, GST_RTSP_HDR_ACCEPT,
1353         &accept, i);
1354     if (res == GST_RTSP_ENOTIMPL)
1355       break;
1356
1357     if (g_ascii_strcasecmp (accept, "application/sdp") == 0)
1358       break;
1359   }
1360
1361   /* find the media object for the uri */
1362   if (!(media = find_media (client, state)))
1363     goto no_media;
1364
1365   /* create an SDP for the media object on this client */
1366   if (!(sdp = klass->create_sdp (client, media)))
1367     goto no_sdp;
1368
1369   g_object_unref (media);
1370
1371   gst_rtsp_message_init_response (state->response, GST_RTSP_STS_OK,
1372       gst_rtsp_status_as_text (GST_RTSP_STS_OK), state->request);
1373
1374   gst_rtsp_message_add_header (state->response, GST_RTSP_HDR_CONTENT_TYPE,
1375       "application/sdp");
1376
1377   /* content base for some clients that might screw up creating the setup uri */
1378   str = gst_rtsp_url_get_request_uri (state->uri);
1379   str_len = strlen (str);
1380
1381   /* check for trailing '/' and append one */
1382   if (str[str_len - 1] != '/') {
1383     content_base = g_malloc (str_len + 2);
1384     memcpy (content_base, str, str_len);
1385     content_base[str_len] = '/';
1386     content_base[str_len + 1] = '\0';
1387     g_free (str);
1388   } else {
1389     content_base = str;
1390   }
1391
1392   GST_INFO ("adding content-base: %s", content_base);
1393
1394   gst_rtsp_message_add_header (state->response, GST_RTSP_HDR_CONTENT_BASE,
1395       content_base);
1396   g_free (content_base);
1397
1398   /* add SDP to the response body */
1399   str = gst_sdp_message_as_text (sdp);
1400   gst_rtsp_message_take_body (state->response, (guint8 *) str, strlen (str));
1401   gst_sdp_message_free (sdp);
1402
1403   send_response (client, state->session, state->response, FALSE);
1404
1405   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_DESCRIBE_REQUEST],
1406       0, state);
1407
1408   return TRUE;
1409
1410   /* ERRORS */
1411 no_media:
1412   {
1413     GST_ERROR ("client %p: no media", client);
1414     /* error reply is already sent */
1415     return FALSE;
1416   }
1417 no_sdp:
1418   {
1419     GST_ERROR ("client %p: can't create SDP", client);
1420     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, state);
1421     g_object_unref (media);
1422     return FALSE;
1423   }
1424 }
1425
1426 static gboolean
1427 handle_options_request (GstRTSPClient * client, GstRTSPClientState * state)
1428 {
1429   GstRTSPMethod options;
1430   gchar *str;
1431
1432   options = GST_RTSP_DESCRIBE |
1433       GST_RTSP_OPTIONS |
1434       GST_RTSP_PAUSE |
1435       GST_RTSP_PLAY |
1436       GST_RTSP_SETUP |
1437       GST_RTSP_GET_PARAMETER | GST_RTSP_SET_PARAMETER | GST_RTSP_TEARDOWN;
1438
1439   str = gst_rtsp_options_as_text (options);
1440
1441   gst_rtsp_message_init_response (state->response, GST_RTSP_STS_OK,
1442       gst_rtsp_status_as_text (GST_RTSP_STS_OK), state->request);
1443
1444   gst_rtsp_message_add_header (state->response, GST_RTSP_HDR_PUBLIC, str);
1445   g_free (str);
1446
1447   send_response (client, state->session, state->response, FALSE);
1448
1449   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_OPTIONS_REQUEST],
1450       0, state);
1451
1452   return TRUE;
1453 }
1454
1455 /* remove duplicate and trailing '/' */
1456 static void
1457 sanitize_uri (GstRTSPUrl * uri)
1458 {
1459   gint i, len;
1460   gchar *s, *d;
1461   gboolean have_slash, prev_slash;
1462
1463   s = d = uri->abspath;
1464   len = strlen (uri->abspath);
1465
1466   prev_slash = FALSE;
1467
1468   for (i = 0; i < len; i++) {
1469     have_slash = s[i] == '/';
1470     *d = s[i];
1471     if (!have_slash || !prev_slash)
1472       d++;
1473     prev_slash = have_slash;
1474   }
1475   len = d - uri->abspath;
1476   /* don't remove the first slash if that's the only thing left */
1477   if (len > 1 && *(d - 1) == '/')
1478     d--;
1479   *d = '\0';
1480 }
1481
1482 static void
1483 client_session_finalized (GstRTSPClient * client, GstRTSPSession * session)
1484 {
1485   GST_INFO ("client %p: session %p finished", client, session);
1486
1487   /* unlink all media managed in this session */
1488   client_unlink_session (client, session);
1489
1490   /* remove the session */
1491   if (!(client->sessions = g_list_remove (client->sessions, session))) {
1492     GST_INFO ("client %p: all sessions finalized, close the connection",
1493         client);
1494     close_connection (client);
1495   }
1496 }
1497
1498 static void
1499 client_watch_session (GstRTSPClient * client, GstRTSPSession * session)
1500 {
1501   GList *walk;
1502
1503   for (walk = client->sessions; walk; walk = g_list_next (walk)) {
1504     GstRTSPSession *msession = (GstRTSPSession *) walk->data;
1505
1506     /* we already know about this session */
1507     if (msession == session)
1508       return;
1509   }
1510
1511   GST_INFO ("watching session %p", session);
1512
1513   g_object_weak_ref (G_OBJECT (session), (GWeakNotify) client_session_finalized,
1514       client);
1515   client->sessions = g_list_prepend (client->sessions, session);
1516
1517   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_NEW_SESSION], 0,
1518       session);
1519 }
1520
1521 static void
1522 handle_request (GstRTSPClient * client, GstRTSPMessage * request)
1523 {
1524   GstRTSPMethod method;
1525   const gchar *uristr;
1526   GstRTSPUrl *uri;
1527   GstRTSPVersion version;
1528   GstRTSPResult res;
1529   GstRTSPSession *session;
1530   GstRTSPClientState state = { NULL };
1531   GstRTSPMessage response = { 0 };
1532   gchar *sessid;
1533
1534   state.request = request;
1535   state.response = &response;
1536
1537   if (gst_debug_category_get_threshold (rtsp_client_debug) >= GST_LEVEL_LOG) {
1538     gst_rtsp_message_dump (request);
1539   }
1540
1541   GST_INFO ("client %p: received a request", client);
1542
1543   gst_rtsp_message_parse_request (request, &method, &uristr, &version);
1544
1545   if (version != GST_RTSP_VERSION_1_0) {
1546     /* we can only handle 1.0 requests */
1547     send_generic_response (client, GST_RTSP_STS_RTSP_VERSION_NOT_SUPPORTED,
1548         &state);
1549     return;
1550   }
1551   state.method = method;
1552
1553   /* we always try to parse the url first */
1554   if (gst_rtsp_url_parse (uristr, &uri) != GST_RTSP_OK) {
1555     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, &state);
1556     return;
1557   }
1558
1559   /* sanitize the uri */
1560   sanitize_uri (uri);
1561   state.uri = uri;
1562
1563   /* get the session if there is any */
1564   res = gst_rtsp_message_get_header (request, GST_RTSP_HDR_SESSION, &sessid, 0);
1565   if (res == GST_RTSP_OK) {
1566     if (client->session_pool == NULL)
1567       goto no_pool;
1568
1569     /* we had a session in the request, find it again */
1570     if (!(session = gst_rtsp_session_pool_find (client->session_pool, sessid)))
1571       goto session_not_found;
1572
1573     /* we add the session to the client list of watched sessions. When a session
1574      * disappears because it times out, we will be notified. If all sessions are
1575      * gone, we will close the connection */
1576     client_watch_session (client, session);
1577   } else
1578     session = NULL;
1579
1580   state.session = session;
1581
1582   if (client->auth) {
1583     if (!gst_rtsp_auth_check (client->auth, client, 0, &state))
1584       goto not_authorized;
1585   }
1586
1587   /* now see what is asked and dispatch to a dedicated handler */
1588   switch (method) {
1589     case GST_RTSP_OPTIONS:
1590       handle_options_request (client, &state);
1591       break;
1592     case GST_RTSP_DESCRIBE:
1593       handle_describe_request (client, &state);
1594       break;
1595     case GST_RTSP_SETUP:
1596       handle_setup_request (client, &state);
1597       break;
1598     case GST_RTSP_PLAY:
1599       handle_play_request (client, &state);
1600       break;
1601     case GST_RTSP_PAUSE:
1602       handle_pause_request (client, &state);
1603       break;
1604     case GST_RTSP_TEARDOWN:
1605       handle_teardown_request (client, &state);
1606       break;
1607     case GST_RTSP_SET_PARAMETER:
1608       handle_set_param_request (client, &state);
1609       break;
1610     case GST_RTSP_GET_PARAMETER:
1611       handle_get_param_request (client, &state);
1612       break;
1613     case GST_RTSP_ANNOUNCE:
1614     case GST_RTSP_RECORD:
1615     case GST_RTSP_REDIRECT:
1616       send_generic_response (client, GST_RTSP_STS_NOT_IMPLEMENTED, &state);
1617       break;
1618     case GST_RTSP_INVALID:
1619     default:
1620       send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, &state);
1621       break;
1622   }
1623   if (session)
1624     g_object_unref (session);
1625
1626   gst_rtsp_url_free (uri);
1627   return;
1628
1629   /* ERRORS */
1630 no_pool:
1631   {
1632     GST_ERROR ("client %p: no pool configured", client);
1633     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, &state);
1634     return;
1635   }
1636 session_not_found:
1637   {
1638     GST_ERROR ("client %p: session not found", client);
1639     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, &state);
1640     return;
1641   }
1642 not_authorized:
1643   {
1644     GST_ERROR ("client %p: not allowed", client);
1645     handle_unauthorized_request (client, client->auth, &state);
1646     return;
1647   }
1648 }
1649
1650 static void
1651 handle_data (GstRTSPClient * client, GstRTSPMessage * message)
1652 {
1653   GstRTSPResult res;
1654   guint8 channel;
1655   GList *walk;
1656   guint8 *data;
1657   guint size;
1658   GstBuffer *buffer;
1659   gboolean handled;
1660
1661   /* find the stream for this message */
1662   res = gst_rtsp_message_parse_data (message, &channel);
1663   if (res != GST_RTSP_OK)
1664     return;
1665
1666   gst_rtsp_message_steal_body (message, &data, &size);
1667
1668   buffer = gst_buffer_new_wrapped (data, size);
1669
1670   handled = FALSE;
1671   for (walk = client->transports; walk; walk = g_list_next (walk)) {
1672     GstRTSPStreamTransport *trans;
1673     GstRTSPStream *stream;
1674     GstRTSPTransport *tr;
1675
1676     trans = walk->data;
1677
1678     /* we only add clients with a transport to the list */
1679     tr = trans->transport;
1680     stream = trans->stream;
1681
1682     /* check for TCP transport */
1683     if (tr->lower_transport == GST_RTSP_LOWER_TRANS_TCP) {
1684       /* dispatch to the stream based on the channel number */
1685       if (tr->interleaved.min == channel) {
1686         gst_rtsp_stream_recv_rtp (stream, buffer);
1687         handled = TRUE;
1688         break;
1689       } else if (tr->interleaved.max == channel) {
1690         gst_rtsp_stream_recv_rtcp (stream, buffer);
1691         handled = TRUE;
1692         break;
1693       }
1694     }
1695   }
1696   if (!handled)
1697     gst_buffer_unref (buffer);
1698 }
1699
1700 /**
1701  * gst_rtsp_client_set_session_pool:
1702  * @client: a #GstRTSPClient
1703  * @pool: a #GstRTSPSessionPool
1704  *
1705  * Set @pool as the sessionpool for @client which it will use to find
1706  * or allocate sessions. the sessionpool is usually inherited from the server
1707  * that created the client but can be overridden later.
1708  */
1709 void
1710 gst_rtsp_client_set_session_pool (GstRTSPClient * client,
1711     GstRTSPSessionPool * pool)
1712 {
1713   GstRTSPSessionPool *old;
1714
1715   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
1716
1717   if (pool)
1718     g_object_ref (pool);
1719
1720   g_mutex_lock (&client->lock);
1721   old = client->session_pool;
1722   client->session_pool = pool;
1723   g_mutex_unlock (&client->lock);
1724
1725   if (old)
1726     g_object_unref (old);
1727 }
1728
1729 /**
1730  * gst_rtsp_client_get_session_pool:
1731  * @client: a #GstRTSPClient
1732  *
1733  * Get the #GstRTSPSessionPool object that @client uses to manage its sessions.
1734  *
1735  * Returns: (transfer full): a #GstRTSPSessionPool, unref after usage.
1736  */
1737 GstRTSPSessionPool *
1738 gst_rtsp_client_get_session_pool (GstRTSPClient * client)
1739 {
1740   GstRTSPSessionPool *result;
1741
1742   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
1743
1744   g_mutex_lock (&client->lock);
1745   if ((result = client->session_pool))
1746     g_object_ref (result);
1747   g_mutex_unlock (&client->lock);
1748
1749   return result;
1750 }
1751
1752 /**
1753  * gst_rtsp_client_set_mount_points:
1754  * @client: a #GstRTSPClient
1755  * @mounts: a #GstRTSPMountPoints
1756  *
1757  * Set @mounts as the mount points for @client which it will use to map urls
1758  * to media streams. These mount points are usually inherited from the server that
1759  * created the client but can be overriden later.
1760  */
1761 void
1762 gst_rtsp_client_set_mount_points (GstRTSPClient * client,
1763     GstRTSPMountPoints * mounts)
1764 {
1765   GstRTSPMountPoints *old;
1766
1767   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
1768
1769   if (mounts)
1770     g_object_ref (mounts);
1771
1772   g_mutex_lock (&client->lock);
1773   old = client->mount_points;
1774   client->mount_points = mounts;
1775   g_mutex_unlock (&client->lock);
1776
1777   if (old)
1778     g_object_unref (old);
1779 }
1780
1781 /**
1782  * gst_rtsp_client_get_mount_points:
1783  * @client: a #GstRTSPClient
1784  *
1785  * Get the #GstRTSPMountPoints object that @client uses to manage its sessions.
1786  *
1787  * Returns: (transfer full): a #GstRTSPMountPoints, unref after usage.
1788  */
1789 GstRTSPMountPoints *
1790 gst_rtsp_client_get_mount_points (GstRTSPClient * client)
1791 {
1792   GstRTSPMountPoints *result;
1793
1794   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
1795
1796   g_mutex_lock (&client->lock);
1797   if ((result = client->mount_points))
1798     g_object_ref (result);
1799   g_mutex_unlock (&client->lock);
1800
1801   return result;
1802 }
1803
1804 /**
1805  * gst_rtsp_client_set_use_client_settings:
1806  * @client: a #GstRTSPClient
1807  * @use_client_settings: whether to use client settings for multicast
1808  *
1809  * Use client transport settings (destination and ttl) for multicast.
1810  * When @use_client_settings is %FALSE, the server settings will be
1811  * used.
1812  */
1813 void
1814 gst_rtsp_client_set_use_client_settings (GstRTSPClient * client,
1815     gboolean use_client_settings)
1816 {
1817   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
1818
1819   g_mutex_lock (&client->lock);
1820   client->use_client_settings = use_client_settings;
1821   g_mutex_unlock (&client->lock);
1822 }
1823
1824 /**
1825  * gst_rtsp_client_get_use_client_settings:
1826  * @client: a #GstRTSPClient
1827  *
1828  * Check if client transport settings (destination and ttl) for multicast
1829  * will be used.
1830  */
1831 gboolean
1832 gst_rtsp_client_get_use_client_settings (GstRTSPClient * client)
1833 {
1834   gboolean res;
1835
1836   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), FALSE);
1837
1838   g_mutex_lock (&client->lock);
1839   res = client->use_client_settings;
1840   g_mutex_unlock (&client->lock);
1841
1842   return res;
1843 }
1844
1845 /**
1846  * gst_rtsp_client_set_auth:
1847  * @client: a #GstRTSPClient
1848  * @auth: a #GstRTSPAuth
1849  *
1850  * configure @auth to be used as the authentication manager of @client.
1851  */
1852 void
1853 gst_rtsp_client_set_auth (GstRTSPClient * client, GstRTSPAuth * auth)
1854 {
1855   GstRTSPAuth *old;
1856
1857   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
1858
1859   if (auth)
1860     g_object_ref (auth);
1861
1862   g_mutex_lock (&client->lock);
1863   old = client->auth;
1864   client->auth = auth;
1865   g_mutex_unlock (&client->lock);
1866
1867   if (old)
1868     g_object_unref (old);
1869 }
1870
1871
1872 /**
1873  * gst_rtsp_client_get_auth:
1874  * @client: a #GstRTSPClient
1875  *
1876  * Get the #GstRTSPAuth used as the authentication manager of @client.
1877  *
1878  * Returns: (transfer full): the #GstRTSPAuth of @client. g_object_unref() after
1879  * usage.
1880  */
1881 GstRTSPAuth *
1882 gst_rtsp_client_get_auth (GstRTSPClient * client)
1883 {
1884   GstRTSPAuth *result;
1885
1886   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
1887
1888   g_mutex_lock (&client->lock);
1889   if ((result = client->auth))
1890     g_object_ref (result);
1891   g_mutex_unlock (&client->lock);
1892
1893   return result;
1894 }
1895
1896 static GstRTSPResult
1897 message_received (GstRTSPWatch * watch, GstRTSPMessage * message,
1898     gpointer user_data)
1899 {
1900   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
1901
1902   switch (message->type) {
1903     case GST_RTSP_MESSAGE_REQUEST:
1904       handle_request (client, message);
1905       break;
1906     case GST_RTSP_MESSAGE_RESPONSE:
1907       break;
1908     case GST_RTSP_MESSAGE_DATA:
1909       handle_data (client, message);
1910       break;
1911     default:
1912       break;
1913   }
1914   return GST_RTSP_OK;
1915 }
1916
1917 static GstRTSPResult
1918 message_sent (GstRTSPWatch * watch, guint cseq, gpointer user_data)
1919 {
1920   GstRTSPClient *client;
1921
1922   client = GST_RTSP_CLIENT (user_data);
1923   if (client->close_response_seq && client->close_response_seq == cseq) {
1924     client->close_response_seq = 0;
1925     close_connection (client);
1926   }
1927
1928   return GST_RTSP_OK;
1929 }
1930
1931 static GstRTSPResult
1932 closed (GstRTSPWatch * watch, gpointer user_data)
1933 {
1934   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
1935   const gchar *tunnelid;
1936
1937   GST_INFO ("client %p: connection closed", client);
1938
1939   if ((tunnelid = gst_rtsp_connection_get_tunnelid (client->connection))) {
1940     g_mutex_lock (&tunnels_lock);
1941     /* remove from tunnelids */
1942     g_hash_table_remove (tunnels, tunnelid);
1943     g_mutex_unlock (&tunnels_lock);
1944   }
1945
1946   return GST_RTSP_OK;
1947 }
1948
1949 static GstRTSPResult
1950 error (GstRTSPWatch * watch, GstRTSPResult result, gpointer user_data)
1951 {
1952   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
1953   gchar *str;
1954
1955   str = gst_rtsp_strresult (result);
1956   GST_INFO ("client %p: received an error %s", client, str);
1957   g_free (str);
1958
1959   return GST_RTSP_OK;
1960 }
1961
1962 static GstRTSPResult
1963 error_full (GstRTSPWatch * watch, GstRTSPResult result,
1964     GstRTSPMessage * message, guint id, gpointer user_data)
1965 {
1966   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
1967   gchar *str;
1968
1969   str = gst_rtsp_strresult (result);
1970   GST_INFO
1971       ("client %p: received an error %s when handling message %p with id %d",
1972       client, str, message, id);
1973   g_free (str);
1974
1975   return GST_RTSP_OK;
1976 }
1977
1978 static gboolean
1979 remember_tunnel (GstRTSPClient * client)
1980 {
1981   const gchar *tunnelid;
1982
1983   /* store client in the pending tunnels */
1984   tunnelid = gst_rtsp_connection_get_tunnelid (client->connection);
1985   if (tunnelid == NULL)
1986     goto no_tunnelid;
1987
1988   GST_INFO ("client %p: inserting tunnel session %s", client, tunnelid);
1989
1990   /* we can't have two clients connecting with the same tunnelid */
1991   g_mutex_lock (&tunnels_lock);
1992   if (g_hash_table_lookup (tunnels, tunnelid))
1993     goto tunnel_existed;
1994
1995   g_hash_table_insert (tunnels, g_strdup (tunnelid), g_object_ref (client));
1996   g_mutex_unlock (&tunnels_lock);
1997
1998   return TRUE;
1999
2000   /* ERRORS */
2001 no_tunnelid:
2002   {
2003     GST_ERROR ("client %p: no tunnelid provided", client);
2004     return FALSE;
2005   }
2006 tunnel_existed:
2007   {
2008     g_mutex_unlock (&tunnels_lock);
2009     GST_ERROR ("client %p: tunnel session %s already existed", client,
2010         tunnelid);
2011     return FALSE;
2012   }
2013 }
2014
2015 static GstRTSPStatusCode
2016 tunnel_start (GstRTSPWatch * watch, gpointer user_data)
2017 {
2018   GstRTSPClient *client;
2019
2020   client = GST_RTSP_CLIENT (user_data);
2021
2022   GST_INFO ("client %p: tunnel start (connection %p)", client,
2023       client->connection);
2024
2025   if (!remember_tunnel (client))
2026     goto tunnel_error;
2027
2028   return GST_RTSP_STS_OK;
2029
2030   /* ERRORS */
2031 tunnel_error:
2032   {
2033     GST_ERROR ("client %p: error starting tunnel", client);
2034     return GST_RTSP_STS_SERVICE_UNAVAILABLE;
2035   }
2036 }
2037
2038 static GstRTSPResult
2039 tunnel_lost (GstRTSPWatch * watch, gpointer user_data)
2040 {
2041   GstRTSPClient *client;
2042
2043   client = GST_RTSP_CLIENT (user_data);
2044
2045   GST_WARNING ("client %p: tunnel lost (connection %p)", client,
2046       client->connection);
2047
2048   /* ignore error, it'll only be a problem when the client does a POST again */
2049   remember_tunnel (client);
2050
2051   return GST_RTSP_OK;
2052 }
2053
2054 static GstRTSPResult
2055 tunnel_complete (GstRTSPWatch * watch, gpointer user_data)
2056 {
2057   const gchar *tunnelid;
2058   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
2059   GstRTSPClient *oclient;
2060
2061   GST_INFO ("client %p: tunnel complete", client);
2062
2063   /* find previous tunnel */
2064   tunnelid = gst_rtsp_connection_get_tunnelid (client->connection);
2065   if (tunnelid == NULL)
2066     goto no_tunnelid;
2067
2068   g_mutex_lock (&tunnels_lock);
2069   if (!(oclient = g_hash_table_lookup (tunnels, tunnelid)))
2070     goto no_tunnel;
2071
2072   /* remove the old client from the table. ref before because removing it will
2073    * remove the ref to it. */
2074   g_object_ref (oclient);
2075   g_hash_table_remove (tunnels, tunnelid);
2076
2077   if (oclient->watch == NULL)
2078     goto tunnel_closed;
2079   g_mutex_unlock (&tunnels_lock);
2080
2081   GST_INFO ("client %p: found tunnel %p (old %p, new %p)", client, oclient,
2082       oclient->connection, client->connection);
2083
2084   /* merge the tunnels into the first client */
2085   gst_rtsp_connection_do_tunnel (oclient->connection, client->connection);
2086   gst_rtsp_watch_reset (oclient->watch);
2087   g_object_unref (oclient);
2088
2089   return GST_RTSP_OK;
2090
2091   /* ERRORS */
2092 no_tunnelid:
2093   {
2094     GST_ERROR ("client %p: no tunnelid provided", client);
2095     return GST_RTSP_ERROR;
2096   }
2097 no_tunnel:
2098   {
2099     g_mutex_unlock (&tunnels_lock);
2100     GST_ERROR ("client %p: tunnel session %s not found", client, tunnelid);
2101     return GST_RTSP_ERROR;
2102   }
2103 tunnel_closed:
2104   {
2105     g_mutex_unlock (&tunnels_lock);
2106     GST_ERROR ("client %p: tunnel session %s was closed", client, tunnelid);
2107     g_object_unref (oclient);
2108     return GST_RTSP_ERROR;
2109   }
2110 }
2111
2112 static GstRTSPWatchFuncs watch_funcs = {
2113   message_received,
2114   message_sent,
2115   closed,
2116   error,
2117   tunnel_start,
2118   tunnel_complete,
2119   error_full,
2120   tunnel_lost
2121 };
2122
2123 static void
2124 client_watch_notify (GstRTSPClient * client)
2125 {
2126   GST_INFO ("client %p: watch destroyed", client);
2127   client->watch = NULL;
2128   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_CLOSED], 0, NULL);
2129   g_object_unref (client);
2130 }
2131
2132 static gboolean
2133 setup_client (GstRTSPClient * client, GSocket * socket,
2134     GstRTSPConnection * conn, GError ** error)
2135 {
2136   GSocket *read_socket;
2137   GSocketAddress *address;
2138   GstRTSPUrl *url;
2139
2140   read_socket = gst_rtsp_connection_get_read_socket (conn);
2141   client->is_ipv6 = g_socket_get_family (socket) == G_SOCKET_FAMILY_IPV6;
2142
2143   if (!(address = g_socket_get_remote_address (read_socket, error)))
2144     goto no_address;
2145
2146   g_free (client->server_ip);
2147   /* keep the original ip that the client connected to */
2148   if (G_IS_INET_SOCKET_ADDRESS (address)) {
2149     GInetAddress *iaddr;
2150
2151     iaddr = g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (address));
2152
2153     client->server_ip = g_inet_address_to_string (iaddr);
2154     g_object_unref (address);
2155   } else {
2156     client->server_ip = g_strdup ("unknown");
2157   }
2158
2159   GST_INFO ("client %p connected to server ip %s, ipv6 = %d", client,
2160       client->server_ip, client->is_ipv6);
2161
2162   url = gst_rtsp_connection_get_url (conn);
2163   GST_INFO ("added new client %p ip %s:%d", client, url->host, url->port);
2164
2165   client->connection = conn;
2166
2167   return TRUE;
2168
2169   /* ERRORS */
2170 no_address:
2171   {
2172     GST_ERROR ("could not get remote address %s", (*error)->message);
2173     return FALSE;
2174   }
2175 }
2176
2177 /**
2178  * gst_rtsp_client_use_socket:
2179  * @client: a #GstRTSPClient
2180  * @socket: a #GSocket
2181  * @ip: the IP address of the remote client
2182  * @port: the port used by the other end
2183  * @initial_buffer: any zero terminated initial data that was already read from
2184  *     the socket
2185  * @error: a #GError
2186  *
2187  * Take an existing network socket and use it for an RTSP connection.
2188  *
2189  * Returns: %TRUE on success.
2190  */
2191 gboolean
2192 gst_rtsp_client_use_socket (GstRTSPClient * client, GSocket * socket,
2193     const gchar * ip, gint port, const gchar * initial_buffer, GError ** error)
2194 {
2195   GstRTSPConnection *conn;
2196   GstRTSPResult res;
2197
2198   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), FALSE);
2199   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2200
2201   GST_RTSP_CHECK (gst_rtsp_connection_create_from_socket (socket, ip, port,
2202           initial_buffer, &conn), no_connection);
2203
2204   return setup_client (client, socket, conn, error);
2205
2206   /* ERRORS */
2207 no_connection:
2208   {
2209     gchar *str = gst_rtsp_strresult (res);
2210
2211     GST_ERROR ("could not create connection from socket %p: %s", socket, str);
2212     g_free (str);
2213     return FALSE;
2214   }
2215 }
2216
2217 /**
2218  * gst_rtsp_client_accept:
2219  * @client: a #GstRTSPClient
2220  * @socket: a #GSocket
2221  * @context: the context to run in
2222  * @cancellable: a #GCancellable
2223  * @error: a #GError
2224  *
2225  * Accept a new connection for @client on @socket.
2226  *
2227  * Returns: %TRUE if the client could be accepted.
2228  */
2229 gboolean
2230 gst_rtsp_client_accept (GstRTSPClient * client, GSocket * socket,
2231     GCancellable * cancellable, GError ** error)
2232 {
2233   GstRTSPConnection *conn;
2234   GstRTSPResult res;
2235
2236   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), FALSE);
2237   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2238
2239   /* a new client connected. */
2240   GST_RTSP_CHECK (gst_rtsp_connection_accept (socket, &conn, cancellable),
2241       accept_failed);
2242
2243   return setup_client (client, socket, conn, error);
2244
2245   /* ERRORS */
2246 accept_failed:
2247   {
2248     gchar *str = gst_rtsp_strresult (res);
2249
2250     GST_ERROR ("Could not accept client on server socket %p: %s", socket, str);
2251     g_free (str);
2252     return FALSE;
2253   }
2254 }
2255
2256 /**
2257  * gst_rtsp_client_attach:
2258  * @client: a #GstRTSPClient
2259  * @context: (allow-none): a #GMainContext
2260  *
2261  * Attaches @client to @context. When the mainloop for @context is run, the
2262  * client will be dispatched. When @context is NULL, the default context will be
2263  * used).
2264  *
2265  * This function should be called when the client properties and urls are fully
2266  * configured and the client is ready to start.
2267  *
2268  * Returns: the ID (greater than 0) for the source within the GMainContext.
2269  */
2270 guint
2271 gst_rtsp_client_attach (GstRTSPClient * client, GMainContext * context)
2272 {
2273   guint res;
2274
2275   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), 0);
2276   g_return_val_if_fail (client->watch == NULL, 0);
2277
2278   /* create watch for the connection and attach */
2279   client->watch = gst_rtsp_watch_new (client->connection, &watch_funcs,
2280       g_object_ref (client), (GDestroyNotify) client_watch_notify);
2281
2282   GST_INFO ("attaching to context %p", context);
2283   res = gst_rtsp_watch_attach (client->watch, context);
2284   gst_rtsp_watch_unref (client->watch);
2285
2286   return res;
2287 }