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