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