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