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