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