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