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