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