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