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