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