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