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