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