rtsp-client: Don't leak addr
[platform/upstream/gstreamer.git] / gst / rtsp-server / rtsp-client.c
1 /* GStreamer
2  * Copyright (C) 2008 Wim Taymans <wim.taymans at gmail.com>
3  * Copyright (C) 2015 Centricular Ltd
4  *     Author: Sebastian Dröge <sebastian@centricular.com>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
19  * Boston, MA 02110-1301, USA.
20  */
21 /**
22  * SECTION:rtsp-client
23  * @short_description: A client connection state
24  * @see_also: #GstRTSPServer, #GstRTSPThreadPool
25  *
26  * The client object handles the connection with a client for as long as a TCP
27  * connection is open.
28  *
29  * A #GstRTSPClient is created by #GstRTSPServer when a new connection is
30  * accepted and it inherits the #GstRTSPMountPoints, #GstRTSPSessionPool,
31  * #GstRTSPAuth and #GstRTSPThreadPool from the server.
32  *
33  * The client connection should be configured with the #GstRTSPConnection using
34  * gst_rtsp_client_set_connection() before it can be attached to a #GMainContext
35  * using gst_rtsp_client_attach(). From then on the client will handle requests
36  * on the connection.
37  *
38  * Use gst_rtsp_client_session_filter() to iterate or modify all the
39  * #GstRTSPSession objects managed by the client object.
40  *
41  * Last reviewed on 2013-07-11 (1.0.0)
42  */
43
44 #include <stdio.h>
45 #include <string.h>
46
47 #include <gst/sdp/gstmikey.h>
48 #include <gst/rtsp/gstrtsp-enumtypes.h>
49
50 #include "rtsp-client.h"
51 #include "rtsp-sdp.h"
52 #include "rtsp-params.h"
53
54 #define GST_RTSP_CLIENT_GET_PRIVATE(obj)  \
55    (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_RTSP_CLIENT, GstRTSPClientPrivate))
56
57 /* locking order:
58  * send_lock, lock, tunnels_lock
59  */
60
61 struct _GstRTSPClientPrivate
62 {
63   GMutex lock;                  /* protects everything else */
64   GMutex send_lock;
65   GMutex watch_lock;
66   GstRTSPConnection *connection;
67   GstRTSPWatch *watch;
68   GMainContext *watch_context;
69   guint close_seq;
70   gchar *server_ip;
71   gboolean is_ipv6;
72
73   GstRTSPClientSendFunc send_func;      /* protected by send_lock */
74   gpointer send_data;           /* protected by send_lock */
75   GDestroyNotify send_notify;   /* protected by send_lock */
76
77   GstRTSPSessionPool *session_pool;
78   gulong session_removed_id;
79   GstRTSPMountPoints *mount_points;
80   GstRTSPAuth *auth;
81   GstRTSPThreadPool *thread_pool;
82
83   /* used to cache the media in the last requested DESCRIBE so that
84    * we can pick it up in the next SETUP immediately */
85   gchar *path;
86   GstRTSPMedia *media;
87
88   GHashTable *transports;
89   GList *sessions;
90   guint sessions_cookie;
91
92   gboolean drop_backlog;
93
94   guint rtsp_ctrl_timeout_id;
95   guint rtsp_ctrl_timeout_cnt;
96
97   /* The version currently being used */
98   GstRTSPVersion version;
99
100   GHashTable *pipelined_requests;       /* pipelined_request_id -> session_id */
101 };
102
103 static GMutex tunnels_lock;
104 static GHashTable *tunnels;     /* protected by tunnels_lock */
105
106 /* FIXME make this configurable. We don't want to do this yet because it will
107  * be superceeded by a cache object later */
108 #define WATCH_BACKLOG_SIZE              100
109
110 #define DEFAULT_SESSION_POOL            NULL
111 #define DEFAULT_MOUNT_POINTS            NULL
112 #define DEFAULT_DROP_BACKLOG            TRUE
113
114 #define RTSP_CTRL_CB_INTERVAL           1
115 #define RTSP_CTRL_TIMEOUT_VALUE         60
116
117 enum
118 {
119   PROP_0,
120   PROP_SESSION_POOL,
121   PROP_MOUNT_POINTS,
122   PROP_DROP_BACKLOG,
123   PROP_LAST
124 };
125
126 enum
127 {
128   SIGNAL_CLOSED,
129   SIGNAL_NEW_SESSION,
130   SIGNAL_PRE_OPTIONS_REQUEST,
131   SIGNAL_OPTIONS_REQUEST,
132   SIGNAL_PRE_DESCRIBE_REQUEST,
133   SIGNAL_DESCRIBE_REQUEST,
134   SIGNAL_PRE_SETUP_REQUEST,
135   SIGNAL_SETUP_REQUEST,
136   SIGNAL_PRE_PLAY_REQUEST,
137   SIGNAL_PLAY_REQUEST,
138   SIGNAL_PRE_PAUSE_REQUEST,
139   SIGNAL_PAUSE_REQUEST,
140   SIGNAL_PRE_TEARDOWN_REQUEST,
141   SIGNAL_TEARDOWN_REQUEST,
142   SIGNAL_PRE_SET_PARAMETER_REQUEST,
143   SIGNAL_SET_PARAMETER_REQUEST,
144   SIGNAL_PRE_GET_PARAMETER_REQUEST,
145   SIGNAL_GET_PARAMETER_REQUEST,
146   SIGNAL_HANDLE_RESPONSE,
147   SIGNAL_SEND_MESSAGE,
148   SIGNAL_PRE_ANNOUNCE_REQUEST,
149   SIGNAL_ANNOUNCE_REQUEST,
150   SIGNAL_PRE_RECORD_REQUEST,
151   SIGNAL_RECORD_REQUEST,
152   SIGNAL_CHECK_REQUIREMENTS,
153   SIGNAL_LAST
154 };
155
156 GST_DEBUG_CATEGORY_STATIC (rtsp_client_debug);
157 #define GST_CAT_DEFAULT rtsp_client_debug
158
159 static guint gst_rtsp_client_signals[SIGNAL_LAST] = { 0 };
160
161 static void gst_rtsp_client_get_property (GObject * object, guint propid,
162     GValue * value, GParamSpec * pspec);
163 static void gst_rtsp_client_set_property (GObject * object, guint propid,
164     const GValue * value, GParamSpec * pspec);
165 static void gst_rtsp_client_finalize (GObject * obj);
166
167 static GstSDPMessage *create_sdp (GstRTSPClient * client, GstRTSPMedia * media);
168 static gboolean handle_sdp (GstRTSPClient * client, GstRTSPContext * ctx,
169     GstRTSPMedia * media, GstSDPMessage * sdp);
170 static gboolean default_configure_client_media (GstRTSPClient * client,
171     GstRTSPMedia * media, GstRTSPStream * stream, GstRTSPContext * ctx);
172 static gboolean default_configure_client_transport (GstRTSPClient * client,
173     GstRTSPContext * ctx, GstRTSPTransport * ct);
174 static GstRTSPResult default_params_set (GstRTSPClient * client,
175     GstRTSPContext * ctx);
176 static GstRTSPResult default_params_get (GstRTSPClient * client,
177     GstRTSPContext * ctx);
178 static gchar *default_make_path_from_uri (GstRTSPClient * client,
179     const GstRTSPUrl * uri);
180 static void client_session_removed (GstRTSPSessionPool * pool,
181     GstRTSPSession * session, GstRTSPClient * client);
182 static GstRTSPStatusCode default_pre_signal_handler (GstRTSPClient * client,
183     GstRTSPContext * ctx);
184 static gboolean pre_signal_accumulator (GSignalInvocationHint * ihint,
185     GValue * return_accu, const GValue * handler_return, gpointer data);
186
187 G_DEFINE_TYPE (GstRTSPClient, gst_rtsp_client, G_TYPE_OBJECT);
188
189 static void
190 gst_rtsp_client_class_init (GstRTSPClientClass * klass)
191 {
192   GObjectClass *gobject_class;
193
194   g_type_class_add_private (klass, sizeof (GstRTSPClientPrivate));
195
196   gobject_class = G_OBJECT_CLASS (klass);
197
198   gobject_class->get_property = gst_rtsp_client_get_property;
199   gobject_class->set_property = gst_rtsp_client_set_property;
200   gobject_class->finalize = gst_rtsp_client_finalize;
201
202   klass->create_sdp = create_sdp;
203   klass->handle_sdp = handle_sdp;
204   klass->configure_client_media = default_configure_client_media;
205   klass->configure_client_transport = default_configure_client_transport;
206   klass->params_set = default_params_set;
207   klass->params_get = default_params_get;
208   klass->make_path_from_uri = default_make_path_from_uri;
209
210   klass->pre_options_request = default_pre_signal_handler;
211   klass->pre_describe_request = default_pre_signal_handler;
212   klass->pre_setup_request = default_pre_signal_handler;
213   klass->pre_play_request = default_pre_signal_handler;
214   klass->pre_pause_request = default_pre_signal_handler;
215   klass->pre_teardown_request = default_pre_signal_handler;
216   klass->pre_set_parameter_request = default_pre_signal_handler;
217   klass->pre_get_parameter_request = default_pre_signal_handler;
218   klass->pre_announce_request = default_pre_signal_handler;
219   klass->pre_record_request = default_pre_signal_handler;
220
221   g_object_class_install_property (gobject_class, PROP_SESSION_POOL,
222       g_param_spec_object ("session-pool", "Session Pool",
223           "The session pool to use for client session",
224           GST_TYPE_RTSP_SESSION_POOL,
225           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
226
227   g_object_class_install_property (gobject_class, PROP_MOUNT_POINTS,
228       g_param_spec_object ("mount-points", "Mount Points",
229           "The mount points to use for client session",
230           GST_TYPE_RTSP_MOUNT_POINTS,
231           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
232
233   g_object_class_install_property (gobject_class, PROP_DROP_BACKLOG,
234       g_param_spec_boolean ("drop-backlog", "Drop Backlog",
235           "Drop data when the backlog queue is full",
236           DEFAULT_DROP_BACKLOG, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
237
238   gst_rtsp_client_signals[SIGNAL_CLOSED] =
239       g_signal_new ("closed", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
240       G_STRUCT_OFFSET (GstRTSPClientClass, closed), NULL, NULL,
241       g_cclosure_marshal_generic, G_TYPE_NONE, 0, G_TYPE_NONE);
242
243   gst_rtsp_client_signals[SIGNAL_NEW_SESSION] =
244       g_signal_new ("new-session", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
245       G_STRUCT_OFFSET (GstRTSPClientClass, new_session), NULL, NULL,
246       g_cclosure_marshal_generic, G_TYPE_NONE, 1, GST_TYPE_RTSP_SESSION);
247
248   /**
249    * GstRTSPClient::pre-options-request:
250    * @client: a #GstRTSPClient
251    * @ctx: a #GstRTSPContext
252    *
253    * Returns: a #GstRTSPStatusCode, GST_RTSP_STS_OK in case of success,
254    *          otherwise an appropriate return code
255    *
256    * Since: 1.12
257    */
258   gst_rtsp_client_signals[SIGNAL_PRE_OPTIONS_REQUEST] =
259       g_signal_new ("pre-options-request", G_TYPE_FROM_CLASS (klass),
260       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass,
261           pre_options_request), pre_signal_accumulator, NULL,
262       g_cclosure_marshal_generic, GST_TYPE_RTSP_STATUS_CODE, 1,
263       GST_TYPE_RTSP_CONTEXT);
264
265   gst_rtsp_client_signals[SIGNAL_OPTIONS_REQUEST] =
266       g_signal_new ("options-request", G_TYPE_FROM_CLASS (klass),
267       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, options_request),
268       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 1,
269       GST_TYPE_RTSP_CONTEXT);
270
271   /**
272    * GstRTSPClient::pre-describe-request:
273    * @client: a #GstRTSPClient
274    * @ctx: a #GstRTSPContext
275    *
276    * Returns: a #GstRTSPStatusCode, GST_RTSP_STS_OK in case of success,
277    *          otherwise an appropriate return code
278    *
279    * Since: 1.12
280    */
281   gst_rtsp_client_signals[SIGNAL_PRE_DESCRIBE_REQUEST] =
282       g_signal_new ("pre-describe-request", G_TYPE_FROM_CLASS (klass),
283       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass,
284           pre_describe_request), pre_signal_accumulator, NULL,
285       g_cclosure_marshal_generic, GST_TYPE_RTSP_STATUS_CODE, 1,
286       GST_TYPE_RTSP_CONTEXT);
287
288   gst_rtsp_client_signals[SIGNAL_DESCRIBE_REQUEST] =
289       g_signal_new ("describe-request", G_TYPE_FROM_CLASS (klass),
290       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, describe_request),
291       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 1,
292       GST_TYPE_RTSP_CONTEXT);
293
294   /**
295    * GstRTSPClient::pre-setup-request:
296    * @client: a #GstRTSPClient
297    * @ctx: a #GstRTSPContext
298    *
299    * Returns: a #GstRTSPStatusCode, GST_RTSP_STS_OK in case of success,
300    *          otherwise an appropriate return code
301    *
302    * Since: 1.12
303    */
304   gst_rtsp_client_signals[SIGNAL_PRE_SETUP_REQUEST] =
305       g_signal_new ("pre-setup-request", G_TYPE_FROM_CLASS (klass),
306       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass,
307           pre_setup_request), pre_signal_accumulator, NULL,
308       g_cclosure_marshal_generic, GST_TYPE_RTSP_STATUS_CODE, 1,
309       GST_TYPE_RTSP_CONTEXT);
310
311   gst_rtsp_client_signals[SIGNAL_SETUP_REQUEST] =
312       g_signal_new ("setup-request", G_TYPE_FROM_CLASS (klass),
313       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, setup_request),
314       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 1,
315       GST_TYPE_RTSP_CONTEXT);
316
317   /**
318    * GstRTSPClient::pre-play-request:
319    * @client: a #GstRTSPClient
320    * @ctx: a #GstRTSPContext
321    *
322    * Returns: a #GstRTSPStatusCode, GST_RTSP_STS_OK in case of success,
323    *          otherwise an appropriate return code
324    *
325    * Since: 1.12
326    */
327   gst_rtsp_client_signals[SIGNAL_PRE_PLAY_REQUEST] =
328       g_signal_new ("pre-play-request", G_TYPE_FROM_CLASS (klass),
329       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass,
330           pre_play_request), pre_signal_accumulator, NULL,
331       g_cclosure_marshal_generic, GST_TYPE_RTSP_STATUS_CODE, 1,
332       GST_TYPE_RTSP_CONTEXT);
333
334   gst_rtsp_client_signals[SIGNAL_PLAY_REQUEST] =
335       g_signal_new ("play-request", G_TYPE_FROM_CLASS (klass),
336       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, play_request),
337       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 1,
338       GST_TYPE_RTSP_CONTEXT);
339
340   /**
341    * GstRTSPClient::pre-pause-request:
342    * @client: a #GstRTSPClient
343    * @ctx: a #GstRTSPContext
344    *
345    * Returns: a #GstRTSPStatusCode, GST_RTSP_STS_OK in case of success,
346    *          otherwise an appropriate return code
347    *
348    * Since: 1.12
349    */
350   gst_rtsp_client_signals[SIGNAL_PRE_PAUSE_REQUEST] =
351       g_signal_new ("pre-pause-request", G_TYPE_FROM_CLASS (klass),
352       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass,
353           pre_pause_request), pre_signal_accumulator, NULL,
354       g_cclosure_marshal_generic, GST_TYPE_RTSP_STATUS_CODE, 1,
355       GST_TYPE_RTSP_CONTEXT);
356
357   gst_rtsp_client_signals[SIGNAL_PAUSE_REQUEST] =
358       g_signal_new ("pause-request", G_TYPE_FROM_CLASS (klass),
359       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, pause_request),
360       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 1,
361       GST_TYPE_RTSP_CONTEXT);
362
363   /**
364    * GstRTSPClient::pre-teardown-request:
365    * @client: a #GstRTSPClient
366    * @ctx: a #GstRTSPContext
367    *
368    * Returns: a #GstRTSPStatusCode, GST_RTSP_STS_OK in case of success,
369    *          otherwise an appropriate return code
370    *
371    * Since: 1.12
372    */
373   gst_rtsp_client_signals[SIGNAL_PRE_TEARDOWN_REQUEST] =
374       g_signal_new ("pre-teardown-request", G_TYPE_FROM_CLASS (klass),
375       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass,
376           pre_teardown_request), pre_signal_accumulator, NULL,
377       g_cclosure_marshal_generic, GST_TYPE_RTSP_STATUS_CODE, 1,
378       GST_TYPE_RTSP_CONTEXT);
379
380   gst_rtsp_client_signals[SIGNAL_TEARDOWN_REQUEST] =
381       g_signal_new ("teardown-request", G_TYPE_FROM_CLASS (klass),
382       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, teardown_request),
383       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 1,
384       GST_TYPE_RTSP_CONTEXT);
385
386   /**
387    * GstRTSPClient::pre-set-parameter-request:
388    * @client: a #GstRTSPClient
389    * @ctx: a #GstRTSPContext
390    *
391    * Returns: a #GstRTSPStatusCode, GST_RTSP_STS_OK in case of success,
392    *          otherwise an appropriate return code
393    *
394    * Since: 1.12
395    */
396   gst_rtsp_client_signals[SIGNAL_PRE_SET_PARAMETER_REQUEST] =
397       g_signal_new ("pre-set-parameter-request", G_TYPE_FROM_CLASS (klass),
398       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass,
399           pre_set_parameter_request), pre_signal_accumulator, NULL,
400       g_cclosure_marshal_generic,
401       GST_TYPE_RTSP_STATUS_CODE, 1, GST_TYPE_RTSP_CONTEXT);
402
403   gst_rtsp_client_signals[SIGNAL_SET_PARAMETER_REQUEST] =
404       g_signal_new ("set-parameter-request", G_TYPE_FROM_CLASS (klass),
405       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass,
406           set_parameter_request), NULL, NULL, g_cclosure_marshal_generic,
407       G_TYPE_NONE, 1, GST_TYPE_RTSP_CONTEXT);
408
409   /**
410    * GstRTSPClient::pre-get-parameter-request:
411    * @client: a #GstRTSPClient
412    * @ctx: a #GstRTSPContext
413    *
414    * Returns: a #GstRTSPStatusCode, GST_RTSP_STS_OK in case of success,
415    *          otherwise an appropriate return code
416    *
417    * Since: 1.12
418    */
419   gst_rtsp_client_signals[SIGNAL_PRE_GET_PARAMETER_REQUEST] =
420       g_signal_new ("pre-get-parameter-request", G_TYPE_FROM_CLASS (klass),
421       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass,
422           pre_get_parameter_request), pre_signal_accumulator, NULL,
423       g_cclosure_marshal_generic, GST_TYPE_RTSP_STATUS_CODE, 1,
424       GST_TYPE_RTSP_CONTEXT);
425
426   gst_rtsp_client_signals[SIGNAL_GET_PARAMETER_REQUEST] =
427       g_signal_new ("get-parameter-request", G_TYPE_FROM_CLASS (klass),
428       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass,
429           get_parameter_request), NULL, NULL, g_cclosure_marshal_generic,
430       G_TYPE_NONE, 1, GST_TYPE_RTSP_CONTEXT);
431
432   gst_rtsp_client_signals[SIGNAL_HANDLE_RESPONSE] =
433       g_signal_new ("handle-response", G_TYPE_FROM_CLASS (klass),
434       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass,
435           handle_response), NULL, NULL, g_cclosure_marshal_generic,
436       G_TYPE_NONE, 1, GST_TYPE_RTSP_CONTEXT);
437
438   /**
439    * GstRTSPClient::send-message:
440    * @client: The RTSP client
441    * @session: (type GstRtspServer.RTSPSession): The session
442    * @message: (type GstRtsp.RTSPMessage): The message
443    */
444   gst_rtsp_client_signals[SIGNAL_SEND_MESSAGE] =
445       g_signal_new ("send-message", G_TYPE_FROM_CLASS (klass),
446       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass,
447           send_message), NULL, NULL, g_cclosure_marshal_generic,
448       G_TYPE_NONE, 2, GST_TYPE_RTSP_CONTEXT, G_TYPE_POINTER);
449
450   /**
451    * GstRTSPClient::pre-announce-request:
452    * @client: a #GstRTSPClient
453    * @ctx: a #GstRTSPContext
454    *
455    * Returns: a #GstRTSPStatusCode, GST_RTSP_STS_OK in case of success,
456    *          otherwise an appropriate return code
457    *
458    * Since: 1.12
459    */
460   gst_rtsp_client_signals[SIGNAL_PRE_ANNOUNCE_REQUEST] =
461       g_signal_new ("pre-announce-request", G_TYPE_FROM_CLASS (klass),
462       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass,
463           pre_announce_request), pre_signal_accumulator, NULL,
464       g_cclosure_marshal_generic, GST_TYPE_RTSP_STATUS_CODE, 1,
465       GST_TYPE_RTSP_CONTEXT);
466
467   gst_rtsp_client_signals[SIGNAL_ANNOUNCE_REQUEST] =
468       g_signal_new ("announce-request", G_TYPE_FROM_CLASS (klass),
469       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, announce_request),
470       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 1,
471       GST_TYPE_RTSP_CONTEXT);
472
473   /**
474    * GstRTSPClient::pre-record-request:
475    * @client: a #GstRTSPClient
476    * @ctx: a #GstRTSPContext
477    *
478    * Returns: a #GstRTSPStatusCode, GST_RTSP_STS_OK in case of success,
479    *          otherwise an appropriate return code
480    *
481    * Since: 1.12
482    */
483   gst_rtsp_client_signals[SIGNAL_PRE_RECORD_REQUEST] =
484       g_signal_new ("pre-record-request", G_TYPE_FROM_CLASS (klass),
485       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass,
486           pre_record_request), pre_signal_accumulator, NULL,
487       g_cclosure_marshal_generic, GST_TYPE_RTSP_STATUS_CODE, 1,
488       GST_TYPE_RTSP_CONTEXT);
489
490   gst_rtsp_client_signals[SIGNAL_RECORD_REQUEST] =
491       g_signal_new ("record-request", G_TYPE_FROM_CLASS (klass),
492       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass, record_request),
493       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 1,
494       GST_TYPE_RTSP_CONTEXT);
495
496   /**
497    * GstRTSPClient::check-requirements:
498    * @client: a #GstRTSPClient
499    * @ctx: a #GstRTSPContext
500    * @arr: a NULL-terminated array of strings
501    *
502    * Returns: a newly allocated string with comma-separated list of
503    *          unsupported options. An empty string must be returned if
504    *          all options are supported.
505    *
506    * Since: 1.6
507    */
508   gst_rtsp_client_signals[SIGNAL_CHECK_REQUIREMENTS] =
509       g_signal_new ("check-requirements", G_TYPE_FROM_CLASS (klass),
510       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPClientClass,
511           check_requirements), NULL, NULL, g_cclosure_marshal_generic,
512       G_TYPE_STRING, 2, GST_TYPE_RTSP_CONTEXT, G_TYPE_STRV);
513
514   tunnels =
515       g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_object_unref);
516   g_mutex_init (&tunnels_lock);
517
518   GST_DEBUG_CATEGORY_INIT (rtsp_client_debug, "rtspclient", 0, "GstRTSPClient");
519 }
520
521 static void
522 gst_rtsp_client_init (GstRTSPClient * client)
523 {
524   GstRTSPClientPrivate *priv = GST_RTSP_CLIENT_GET_PRIVATE (client);
525
526   client->priv = priv;
527
528   g_mutex_init (&priv->lock);
529   g_mutex_init (&priv->send_lock);
530   g_mutex_init (&priv->watch_lock);
531   priv->close_seq = 0;
532   priv->drop_backlog = DEFAULT_DROP_BACKLOG;
533   priv->transports =
534       g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL,
535       g_object_unref);
536   priv->pipelined_requests = g_hash_table_new_full (g_str_hash,
537       g_str_equal, g_free, g_free);
538 }
539
540 static GstRTSPFilterResult
541 filter_session_media (GstRTSPSession * sess, GstRTSPSessionMedia * sessmedia,
542     gpointer user_data)
543 {
544   gboolean *closed = user_data;
545   GstRTSPMedia *media;
546   guint i, n_streams;
547   gboolean is_all_udp = TRUE;
548
549   media = gst_rtsp_session_media_get_media (sessmedia);
550   n_streams = gst_rtsp_media_n_streams (media);
551
552   for (i = 0; i < n_streams; i++) {
553     GstRTSPStreamTransport *transport =
554         gst_rtsp_session_media_get_transport (sessmedia, i);
555     const GstRTSPTransport *rtsp_transport;
556
557     if (!transport)
558       continue;
559
560     rtsp_transport = gst_rtsp_stream_transport_get_transport (transport);
561     if (rtsp_transport
562         && rtsp_transport->lower_transport != GST_RTSP_LOWER_TRANS_UDP
563         && rtsp_transport->lower_transport != GST_RTSP_LOWER_TRANS_UDP_MCAST) {
564       is_all_udp = FALSE;
565       break;
566     }
567   }
568
569   if (!is_all_udp || gst_rtsp_media_is_stop_on_disconnect (media)) {
570     gst_rtsp_session_media_set_state (sessmedia, GST_STATE_NULL);
571     return GST_RTSP_FILTER_REMOVE;
572   } else {
573     *closed = FALSE;
574     return GST_RTSP_FILTER_KEEP;
575   }
576 }
577
578 static void
579 client_watch_session (GstRTSPClient * client, GstRTSPSession * session)
580 {
581   GstRTSPClientPrivate *priv = client->priv;
582
583   g_mutex_lock (&priv->lock);
584   /* check if we already know about this session */
585   if (g_list_find (priv->sessions, session) == NULL) {
586     GST_INFO ("watching session %p", session);
587
588     priv->sessions = g_list_prepend (priv->sessions, g_object_ref (session));
589     priv->sessions_cookie++;
590
591     /* connect removed session handler, it will be disconnected when the last
592      * session gets removed  */
593     if (priv->session_removed_id == 0)
594       priv->session_removed_id = g_signal_connect_data (priv->session_pool,
595           "session-removed", G_CALLBACK (client_session_removed),
596           g_object_ref (client), (GClosureNotify) g_object_unref, 0);
597   }
598   g_mutex_unlock (&priv->lock);
599
600   return;
601 }
602
603 /* should be called with lock */
604 static void
605 client_unwatch_session (GstRTSPClient * client, GstRTSPSession * session,
606     GList * link)
607 {
608   GstRTSPClientPrivate *priv = client->priv;
609
610   GST_INFO ("client %p: unwatch session %p", client, session);
611
612   if (link == NULL) {
613     link = g_list_find (priv->sessions, session);
614     if (link == NULL)
615       return;
616   }
617
618   priv->sessions = g_list_delete_link (priv->sessions, link);
619   priv->sessions_cookie++;
620
621   /* if this was the last session, disconnect the handler.
622    * This will also drop the extra client ref */
623   if (!priv->sessions) {
624     g_signal_handler_disconnect (priv->session_pool, priv->session_removed_id);
625     priv->session_removed_id = 0;
626   }
627
628   if (!priv->drop_backlog) {
629     /* unlink all media managed in this session */
630     gst_rtsp_session_filter (session, filter_session_media, client);
631   }
632
633   /* remove the session */
634   g_object_unref (session);
635 }
636
637 static GstRTSPFilterResult
638 cleanup_session (GstRTSPClient * client, GstRTSPSession * sess,
639     gpointer user_data)
640 {
641   gboolean *closed = user_data;
642   GstRTSPClientPrivate *priv = client->priv;
643
644   if (priv->drop_backlog) {
645     /* unlink all media managed in this session. This needs to happen
646      * without the client lock, so we really want to do it here. */
647     gst_rtsp_session_filter (sess, filter_session_media, user_data);
648   }
649
650   if (*closed)
651     return GST_RTSP_FILTER_REMOVE;
652   else
653     return GST_RTSP_FILTER_KEEP;
654 }
655
656 static void
657 clean_cached_media (GstRTSPClient * client, gboolean unprepare)
658 {
659   GstRTSPClientPrivate *priv = client->priv;
660
661   if (priv->path) {
662     g_free (priv->path);
663     priv->path = NULL;
664   }
665   if (priv->media) {
666     if (unprepare)
667       gst_rtsp_media_unprepare (priv->media);
668     g_object_unref (priv->media);
669     priv->media = NULL;
670   }
671 }
672
673 /* A client is finalized when the connection is broken */
674 static void
675 gst_rtsp_client_finalize (GObject * obj)
676 {
677   GstRTSPClient *client = GST_RTSP_CLIENT (obj);
678   GstRTSPClientPrivate *priv = client->priv;
679
680   GST_INFO ("finalize client %p", client);
681
682   if (priv->watch)
683     gst_rtsp_watch_set_flushing (priv->watch, TRUE);
684   gst_rtsp_client_set_send_func (client, NULL, NULL, NULL);
685
686   if (priv->watch)
687     g_source_destroy ((GSource *) priv->watch);
688
689   if (priv->watch_context)
690     g_main_context_unref (priv->watch_context);
691
692   /* all sessions should have been removed by now. We keep a ref to
693    * the client object for the session removed handler. The ref is
694    * dropped when the last session is removed from the list. */
695   g_assert (priv->sessions == NULL);
696   g_assert (priv->session_removed_id == 0);
697
698   g_hash_table_unref (priv->transports);
699   g_hash_table_unref (priv->pipelined_requests);
700
701   if (priv->connection)
702     gst_rtsp_connection_free (priv->connection);
703   if (priv->session_pool) {
704     g_object_unref (priv->session_pool);
705   }
706   if (priv->mount_points)
707     g_object_unref (priv->mount_points);
708   if (priv->auth)
709     g_object_unref (priv->auth);
710   if (priv->thread_pool)
711     g_object_unref (priv->thread_pool);
712
713   clean_cached_media (client, TRUE);
714
715   g_free (priv->server_ip);
716   g_mutex_clear (&priv->lock);
717   g_mutex_clear (&priv->send_lock);
718   g_mutex_clear (&priv->watch_lock);
719
720   G_OBJECT_CLASS (gst_rtsp_client_parent_class)->finalize (obj);
721 }
722
723 static void
724 gst_rtsp_client_get_property (GObject * object, guint propid,
725     GValue * value, GParamSpec * pspec)
726 {
727   GstRTSPClient *client = GST_RTSP_CLIENT (object);
728   GstRTSPClientPrivate *priv = client->priv;
729
730   switch (propid) {
731     case PROP_SESSION_POOL:
732       g_value_take_object (value, gst_rtsp_client_get_session_pool (client));
733       break;
734     case PROP_MOUNT_POINTS:
735       g_value_take_object (value, gst_rtsp_client_get_mount_points (client));
736       break;
737     case PROP_DROP_BACKLOG:
738       g_value_set_boolean (value, priv->drop_backlog);
739       break;
740     default:
741       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, propid, pspec);
742   }
743 }
744
745 static void
746 gst_rtsp_client_set_property (GObject * object, guint propid,
747     const GValue * value, GParamSpec * pspec)
748 {
749   GstRTSPClient *client = GST_RTSP_CLIENT (object);
750   GstRTSPClientPrivate *priv = client->priv;
751
752   switch (propid) {
753     case PROP_SESSION_POOL:
754       gst_rtsp_client_set_session_pool (client, g_value_get_object (value));
755       break;
756     case PROP_MOUNT_POINTS:
757       gst_rtsp_client_set_mount_points (client, g_value_get_object (value));
758       break;
759     case PROP_DROP_BACKLOG:
760       g_mutex_lock (&priv->lock);
761       priv->drop_backlog = g_value_get_boolean (value);
762       g_mutex_unlock (&priv->lock);
763       break;
764     default:
765       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, propid, pspec);
766   }
767 }
768
769 /**
770  * gst_rtsp_client_new:
771  *
772  * Create a new #GstRTSPClient instance.
773  *
774  * Returns: (transfer full): a new #GstRTSPClient
775  */
776 GstRTSPClient *
777 gst_rtsp_client_new (void)
778 {
779   GstRTSPClient *result;
780
781   result = g_object_new (GST_TYPE_RTSP_CLIENT, NULL);
782
783   return result;
784 }
785
786 static void
787 send_message (GstRTSPClient * client, GstRTSPContext * ctx,
788     GstRTSPMessage * message, gboolean close)
789 {
790   GstRTSPClientPrivate *priv = client->priv;
791
792   gst_rtsp_message_add_header (message, GST_RTSP_HDR_SERVER,
793       "GStreamer RTSP server");
794
795   /* remove any previous header */
796   gst_rtsp_message_remove_header (message, GST_RTSP_HDR_SESSION, -1);
797
798   /* add the new session header for new session ids */
799   if (ctx->session) {
800     gst_rtsp_message_take_header (message, GST_RTSP_HDR_SESSION,
801         gst_rtsp_session_get_header (ctx->session));
802   }
803
804   if (gst_debug_category_get_threshold (rtsp_client_debug) >= GST_LEVEL_LOG) {
805     gst_rtsp_message_dump (message);
806   }
807
808   if (close)
809     gst_rtsp_message_add_header (message, GST_RTSP_HDR_CONNECTION, "close");
810
811   if (ctx->request)
812     message->type_data.response.version =
813         ctx->request->type_data.request.version;
814
815   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_SEND_MESSAGE],
816       0, ctx, message);
817
818   g_mutex_lock (&priv->send_lock);
819   if (priv->send_func)
820     priv->send_func (client, message, close, priv->send_data);
821   g_mutex_unlock (&priv->send_lock);
822
823   gst_rtsp_message_unset (message);
824 }
825
826 static void
827 send_generic_response (GstRTSPClient * client, GstRTSPStatusCode code,
828     GstRTSPContext * ctx)
829 {
830   gst_rtsp_message_init_response (ctx->response, code,
831       gst_rtsp_status_as_text (code), ctx->request);
832
833   ctx->session = NULL;
834
835   send_message (client, ctx, ctx->response, FALSE);
836 }
837
838 static void
839 send_option_not_supported_response (GstRTSPClient * client,
840     GstRTSPContext * ctx, const gchar * unsupported_options)
841 {
842   GstRTSPStatusCode code = GST_RTSP_STS_OPTION_NOT_SUPPORTED;
843
844   gst_rtsp_message_init_response (ctx->response, code,
845       gst_rtsp_status_as_text (code), ctx->request);
846
847   if (unsupported_options != NULL) {
848     gst_rtsp_message_add_header (ctx->response, GST_RTSP_HDR_UNSUPPORTED,
849         unsupported_options);
850   }
851
852   ctx->session = NULL;
853
854   send_message (client, ctx, ctx->response, FALSE);
855 }
856
857 static gboolean
858 paths_are_equal (const gchar * path1, const gchar * path2, gint len2)
859 {
860   if (path1 == NULL || path2 == NULL)
861     return FALSE;
862
863   if (strlen (path1) != len2)
864     return FALSE;
865
866   if (strncmp (path1, path2, len2))
867     return FALSE;
868
869   return TRUE;
870 }
871
872 /* this function is called to initially find the media for the DESCRIBE request
873  * but is cached for when the same client (without breaking the connection) is
874  * doing a setup for the exact same url. */
875 static GstRTSPMedia *
876 find_media (GstRTSPClient * client, GstRTSPContext * ctx, gchar * path,
877     gint * matched)
878 {
879   GstRTSPClientPrivate *priv = client->priv;
880   GstRTSPMediaFactory *factory;
881   GstRTSPMedia *media;
882   gint path_len;
883
884   /* find the longest matching factory for the uri first */
885   if (!(factory = gst_rtsp_mount_points_match (priv->mount_points,
886               path, matched)))
887     goto no_factory;
888
889   ctx->factory = factory;
890
891   if (!gst_rtsp_auth_check (GST_RTSP_AUTH_CHECK_MEDIA_FACTORY_ACCESS))
892     goto no_factory_access;
893
894   if (!gst_rtsp_auth_check (GST_RTSP_AUTH_CHECK_MEDIA_FACTORY_CONSTRUCT))
895     goto not_authorized;
896
897   if (matched)
898     path_len = *matched;
899   else
900     path_len = strlen (path);
901
902   if (!paths_are_equal (priv->path, path, path_len)) {
903     /* remove any previously cached values before we try to construct a new
904      * media for uri */
905     clean_cached_media (client, TRUE);
906
907     /* prepare the media and add it to the pipeline */
908     if (!(media = gst_rtsp_media_factory_construct (factory, ctx->uri)))
909       goto no_media;
910
911     ctx->media = media;
912
913     if (!(gst_rtsp_media_get_transport_mode (media) &
914             GST_RTSP_TRANSPORT_MODE_RECORD)) {
915       GstRTSPThread *thread;
916
917       thread = gst_rtsp_thread_pool_get_thread (priv->thread_pool,
918           GST_RTSP_THREAD_TYPE_MEDIA, ctx);
919       if (thread == NULL)
920         goto no_thread;
921
922       /* prepare the media */
923       if (!gst_rtsp_media_prepare (media, thread))
924         goto no_prepare;
925     }
926
927     /* now keep track of the uri and the media */
928     priv->path = g_strndup (path, path_len);
929     priv->media = media;
930   } else {
931     /* we have seen this path before, used cached media */
932     media = priv->media;
933     ctx->media = media;
934     GST_INFO ("reusing cached media %p for path %s", media, priv->path);
935   }
936
937   g_object_unref (factory);
938   ctx->factory = NULL;
939
940   if (media)
941     g_object_ref (media);
942
943   return media;
944
945   /* ERRORS */
946 no_factory:
947   {
948     GST_ERROR ("client %p: no factory for path %s", client, path);
949     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
950     return NULL;
951   }
952 no_factory_access:
953   {
954     g_object_unref (factory);
955     ctx->factory = NULL;
956     GST_ERROR ("client %p: not authorized to see factory path %s", client,
957         path);
958     /* error reply is already sent */
959     return NULL;
960   }
961 not_authorized:
962   {
963     g_object_unref (factory);
964     ctx->factory = NULL;
965     GST_ERROR ("client %p: not authorized for factory path %s", client, path);
966     /* error reply is already sent */
967     return NULL;
968   }
969 no_media:
970   {
971     GST_ERROR ("client %p: can't create media", client);
972     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
973     g_object_unref (factory);
974     ctx->factory = NULL;
975     return NULL;
976   }
977 no_thread:
978   {
979     GST_ERROR ("client %p: can't create thread", client);
980     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, ctx);
981     g_object_unref (media);
982     ctx->media = NULL;
983     g_object_unref (factory);
984     ctx->factory = NULL;
985     return NULL;
986   }
987 no_prepare:
988   {
989     GST_ERROR ("client %p: can't prepare media", client);
990     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, ctx);
991     g_object_unref (media);
992     ctx->media = NULL;
993     g_object_unref (factory);
994     ctx->factory = NULL;
995     return NULL;
996   }
997 }
998
999 static gboolean
1000 do_send_data (GstBuffer * buffer, guint8 channel, GstRTSPClient * client)
1001 {
1002   GstRTSPClientPrivate *priv = client->priv;
1003   GstRTSPMessage message = { 0 };
1004   GstRTSPResult res = GST_RTSP_OK;
1005   GstMapInfo map_info;
1006   guint8 *data;
1007   guint usize;
1008
1009   gst_rtsp_message_init_data (&message, channel);
1010
1011   /* FIXME, need some sort of iovec RTSPMessage here */
1012   if (!gst_buffer_map (buffer, &map_info, GST_MAP_READ))
1013     return FALSE;
1014
1015   gst_rtsp_message_take_body (&message, map_info.data, map_info.size);
1016
1017   g_mutex_lock (&priv->send_lock);
1018   if (priv->send_func)
1019     res = priv->send_func (client, &message, FALSE, priv->send_data);
1020   g_mutex_unlock (&priv->send_lock);
1021
1022   gst_rtsp_message_steal_body (&message, &data, &usize);
1023   gst_buffer_unmap (buffer, &map_info);
1024
1025   gst_rtsp_message_unset (&message);
1026
1027   return res == GST_RTSP_OK;
1028 }
1029
1030 /**
1031  * gst_rtsp_client_close:
1032  * @client: a #GstRTSPClient
1033  *
1034  * Close the connection of @client and remove all media it was managing.
1035  *
1036  * Since: 1.4
1037  */
1038 void
1039 gst_rtsp_client_close (GstRTSPClient * client)
1040 {
1041   GstRTSPClientPrivate *priv = client->priv;
1042   const gchar *tunnelid;
1043
1044   GST_DEBUG ("client %p: closing connection", client);
1045
1046   if (priv->connection) {
1047     if ((tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection))) {
1048       g_mutex_lock (&tunnels_lock);
1049       /* remove from tunnelids */
1050       g_hash_table_remove (tunnels, tunnelid);
1051       g_mutex_unlock (&tunnels_lock);
1052     }
1053     gst_rtsp_connection_close (priv->connection);
1054   }
1055
1056   /* connection is now closed, destroy the watch which will also cause the
1057    * closed signal to be emitted */
1058   if (priv->watch) {
1059     GST_DEBUG ("client %p: destroying watch", client);
1060     g_source_destroy ((GSource *) priv->watch);
1061     priv->watch = NULL;
1062     gst_rtsp_client_set_send_func (client, NULL, NULL, NULL);
1063     g_main_context_unref (priv->watch_context);
1064     priv->watch_context = NULL;
1065   }
1066 }
1067
1068 static gchar *
1069 default_make_path_from_uri (GstRTSPClient * client, const GstRTSPUrl * uri)
1070 {
1071   gchar *path;
1072
1073   if (uri->query)
1074     path = g_strconcat (uri->abspath, "?", uri->query, NULL);
1075   else
1076     path = g_strdup (uri->abspath);
1077
1078   return path;
1079 }
1080
1081 /* Default signal handler function for all "pre-command" signals, like
1082  * pre-options-request. It just returns the RTSP return code 200.
1083  * Subclasses can override this to get another default behaviour.
1084  */
1085 static GstRTSPStatusCode
1086 default_pre_signal_handler (GstRTSPClient * client, GstRTSPContext * ctx)
1087 {
1088   GST_LOG_OBJECT (client, "returning GST_RTSP_STS_OK");
1089   return GST_RTSP_STS_OK;
1090 }
1091
1092 /* The pre-signal accumulator function checks the return value of the signal
1093  * handlers. If any of them returns an RTSP status code that does not start
1094  * with 2 it will return FALSE, no more signal handlers will be called, and
1095  * this last RTSP status code will be the result of the signal emission.
1096  */
1097 static gboolean
1098 pre_signal_accumulator (GSignalInvocationHint * ihint, GValue * return_accu,
1099     const GValue * handler_return, gpointer data)
1100 {
1101   GstRTSPStatusCode handler_value = g_value_get_enum (handler_return);
1102   GstRTSPStatusCode accumulated_value = g_value_get_enum (return_accu);
1103
1104   if (handler_value < 200 || handler_value > 299) {
1105     GST_DEBUG ("handler_value : %d, returning FALSE", handler_value);
1106     g_value_set_enum (return_accu, handler_value);
1107     return FALSE;
1108   }
1109
1110   /* the accumulated value is initiated to 0 by GLib. if current handler value is
1111    * bigger then use that instead
1112    *
1113    * FIXME: Should we prioritize the 2xx codes in a smarter way?
1114    *        Like, "201 Created" > "250 Low On Storage Space" > "200 OK"?
1115    */
1116   if (handler_value > accumulated_value)
1117     g_value_set_enum (return_accu, handler_value);
1118
1119   return TRUE;
1120 }
1121
1122 static gboolean
1123 handle_teardown_request (GstRTSPClient * client, GstRTSPContext * ctx)
1124 {
1125   GstRTSPClientPrivate *priv = client->priv;
1126   GstRTSPClientClass *klass;
1127   GstRTSPSession *session;
1128   GstRTSPSessionMedia *sessmedia;
1129   GstRTSPStatusCode code;
1130   gchar *path;
1131   gint matched;
1132   gboolean keep_session;
1133   GstRTSPStatusCode sig_result;
1134
1135   if (!ctx->session)
1136     goto no_session;
1137
1138   session = ctx->session;
1139
1140   if (!ctx->uri)
1141     goto no_uri;
1142
1143   klass = GST_RTSP_CLIENT_GET_CLASS (client);
1144   path = klass->make_path_from_uri (client, ctx->uri);
1145
1146   /* get a handle to the configuration of the media in the session */
1147   sessmedia = gst_rtsp_session_get_media (session, path, &matched);
1148   if (!sessmedia)
1149     goto not_found;
1150
1151   /* only aggregate control for now.. */
1152   if (path[matched] != '\0')
1153     goto no_aggregate;
1154
1155   g_free (path);
1156
1157   ctx->sessmedia = sessmedia;
1158
1159   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_PRE_TEARDOWN_REQUEST],
1160       0, ctx, &sig_result);
1161   if (sig_result != GST_RTSP_STS_OK) {
1162     goto sig_failed;
1163   }
1164
1165   /* we emit the signal before closing the connection */
1166   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_TEARDOWN_REQUEST],
1167       0, ctx);
1168
1169   gst_rtsp_session_media_set_state (sessmedia, GST_STATE_NULL);
1170
1171   /* unmanage the media in the session, returns false if all media session
1172    * are torn down. */
1173   keep_session = gst_rtsp_session_release_media (session, sessmedia);
1174
1175   /* construct the response now */
1176   code = GST_RTSP_STS_OK;
1177   gst_rtsp_message_init_response (ctx->response, code,
1178       gst_rtsp_status_as_text (code), ctx->request);
1179
1180   send_message (client, ctx, ctx->response, TRUE);
1181
1182   if (!keep_session) {
1183     /* remove the session */
1184     gst_rtsp_session_pool_remove (priv->session_pool, session);
1185   }
1186
1187   return TRUE;
1188
1189   /* ERRORS */
1190 no_session:
1191   {
1192     GST_ERROR ("client %p: no session", client);
1193     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
1194     return FALSE;
1195   }
1196 no_uri:
1197   {
1198     GST_ERROR ("client %p: no uri supplied", client);
1199     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
1200     return FALSE;
1201   }
1202 not_found:
1203   {
1204     GST_ERROR ("client %p: no media for uri", client);
1205     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
1206     g_free (path);
1207     return FALSE;
1208   }
1209 no_aggregate:
1210   {
1211     GST_ERROR ("client %p: no aggregate path %s", client, path);
1212     send_generic_response (client,
1213         GST_RTSP_STS_ONLY_AGGREGATE_OPERATION_ALLOWED, ctx);
1214     g_free (path);
1215     return FALSE;
1216   }
1217 sig_failed:
1218   {
1219     GST_ERROR ("client %p: pre signal returned error: %s", client,
1220         gst_rtsp_status_as_text (sig_result));
1221     send_generic_response (client, sig_result, ctx);
1222     return FALSE;
1223   }
1224 }
1225
1226 static GstRTSPResult
1227 default_params_set (GstRTSPClient * client, GstRTSPContext * ctx)
1228 {
1229   GstRTSPResult res;
1230
1231   res = gst_rtsp_params_set (client, ctx);
1232
1233   return res;
1234 }
1235
1236 static GstRTSPResult
1237 default_params_get (GstRTSPClient * client, GstRTSPContext * ctx)
1238 {
1239   GstRTSPResult res;
1240
1241   res = gst_rtsp_params_get (client, ctx);
1242
1243   return res;
1244 }
1245
1246 static gboolean
1247 handle_get_param_request (GstRTSPClient * client, GstRTSPContext * ctx)
1248 {
1249   GstRTSPResult res;
1250   guint8 *data;
1251   guint size;
1252   GstRTSPStatusCode sig_result;
1253
1254   g_signal_emit (client,
1255       gst_rtsp_client_signals[SIGNAL_PRE_GET_PARAMETER_REQUEST], 0, ctx,
1256       &sig_result);
1257   if (sig_result != GST_RTSP_STS_OK) {
1258     goto sig_failed;
1259   }
1260
1261   res = gst_rtsp_message_get_body (ctx->request, &data, &size);
1262   if (res != GST_RTSP_OK)
1263     goto bad_request;
1264
1265   if (size == 0 || !data || strlen ((char *) data) == 0) {
1266     if (ctx->request->type_data.request.version >= GST_RTSP_VERSION_2_0) {
1267       GST_ERROR_OBJECT (client, "Using PLAY request for keep-alive is forbidden"
1268           " in RTSP 2.0");
1269       goto bad_request;
1270     }
1271
1272     /* no body (or only '\0'), keep-alive request */
1273     send_generic_response (client, GST_RTSP_STS_OK, ctx);
1274   } else {
1275     /* there is a body, handle the params */
1276     res = GST_RTSP_CLIENT_GET_CLASS (client)->params_get (client, ctx);
1277     if (res != GST_RTSP_OK)
1278       goto bad_request;
1279
1280     send_message (client, ctx, ctx->response, FALSE);
1281   }
1282
1283   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_GET_PARAMETER_REQUEST],
1284       0, ctx);
1285
1286   return TRUE;
1287
1288   /* ERRORS */
1289 sig_failed:
1290   {
1291     GST_ERROR ("client %p: pre signal returned error: %s", client,
1292         gst_rtsp_status_as_text (sig_result));
1293     send_generic_response (client, sig_result, ctx);
1294     return FALSE;
1295   }
1296 bad_request:
1297   {
1298     GST_ERROR ("client %p: bad request", client);
1299     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
1300     return FALSE;
1301   }
1302 }
1303
1304 static gboolean
1305 handle_set_param_request (GstRTSPClient * client, GstRTSPContext * ctx)
1306 {
1307   GstRTSPResult res;
1308   guint8 *data;
1309   guint size;
1310   GstRTSPStatusCode sig_result;
1311
1312   g_signal_emit (client,
1313       gst_rtsp_client_signals[SIGNAL_PRE_SET_PARAMETER_REQUEST], 0, ctx,
1314       &sig_result);
1315   if (sig_result != GST_RTSP_STS_OK) {
1316     goto sig_failed;
1317   }
1318
1319   res = gst_rtsp_message_get_body (ctx->request, &data, &size);
1320   if (res != GST_RTSP_OK)
1321     goto bad_request;
1322
1323   if (size == 0 || !data || strlen ((char *) data) == 0) {
1324     /* no body (or only '\0'), keep-alive request */
1325     send_generic_response (client, GST_RTSP_STS_OK, ctx);
1326   } else {
1327     /* there is a body, handle the params */
1328     res = GST_RTSP_CLIENT_GET_CLASS (client)->params_set (client, ctx);
1329     if (res != GST_RTSP_OK)
1330       goto bad_request;
1331
1332     send_message (client, ctx, ctx->response, FALSE);
1333   }
1334
1335   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_SET_PARAMETER_REQUEST],
1336       0, ctx);
1337
1338   return TRUE;
1339
1340   /* ERRORS */
1341 sig_failed:
1342   {
1343     GST_ERROR ("client %p: pre signal returned error: %s", client,
1344         gst_rtsp_status_as_text (sig_result));
1345     send_generic_response (client, sig_result, ctx);
1346     return FALSE;
1347   }
1348 bad_request:
1349   {
1350     GST_ERROR ("client %p: bad request", client);
1351     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
1352     return FALSE;
1353   }
1354 }
1355
1356 static gboolean
1357 handle_pause_request (GstRTSPClient * client, GstRTSPContext * ctx)
1358 {
1359   GstRTSPSession *session;
1360   GstRTSPClientClass *klass;
1361   GstRTSPSessionMedia *sessmedia;
1362   GstRTSPMedia *media;
1363   GstRTSPStatusCode code;
1364   GstRTSPState rtspstate;
1365   gchar *path;
1366   gint matched;
1367   GstRTSPStatusCode sig_result;
1368   guint i, n;
1369
1370   if (!(session = ctx->session))
1371     goto no_session;
1372
1373   if (!ctx->uri)
1374     goto no_uri;
1375
1376   klass = GST_RTSP_CLIENT_GET_CLASS (client);
1377   path = klass->make_path_from_uri (client, ctx->uri);
1378
1379   /* get a handle to the configuration of the media in the session */
1380   sessmedia = gst_rtsp_session_get_media (session, path, &matched);
1381   if (!sessmedia)
1382     goto not_found;
1383
1384   if (path[matched] != '\0')
1385     goto no_aggregate;
1386
1387   g_free (path);
1388
1389   media = gst_rtsp_session_media_get_media (sessmedia);
1390   n = gst_rtsp_media_n_streams (media);
1391   for (i = 0; i < n; i++) {
1392     GstRTSPStream *stream = gst_rtsp_media_get_stream (media, i);
1393
1394     if (gst_rtsp_stream_get_publish_clock_mode (stream) ==
1395         GST_RTSP_PUBLISH_CLOCK_MODE_CLOCK_AND_OFFSET)
1396       goto not_supported;
1397   }
1398
1399   ctx->sessmedia = sessmedia;
1400
1401   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_PRE_PAUSE_REQUEST], 0,
1402       ctx, &sig_result);
1403   if (sig_result != GST_RTSP_STS_OK) {
1404     goto sig_failed;
1405   }
1406
1407   rtspstate = gst_rtsp_session_media_get_rtsp_state (sessmedia);
1408   /* the session state must be playing or recording */
1409   if (rtspstate != GST_RTSP_STATE_PLAYING &&
1410       rtspstate != GST_RTSP_STATE_RECORDING)
1411     goto invalid_state;
1412
1413   /* then pause sending */
1414   gst_rtsp_session_media_set_state (sessmedia, GST_STATE_PAUSED);
1415
1416   /* construct the response now */
1417   code = GST_RTSP_STS_OK;
1418   gst_rtsp_message_init_response (ctx->response, code,
1419       gst_rtsp_status_as_text (code), ctx->request);
1420
1421   send_message (client, ctx, ctx->response, FALSE);
1422
1423   /* the state is now READY */
1424   gst_rtsp_session_media_set_rtsp_state (sessmedia, GST_RTSP_STATE_READY);
1425
1426   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_PAUSE_REQUEST], 0, ctx);
1427
1428   return TRUE;
1429
1430   /* ERRORS */
1431 no_session:
1432   {
1433     GST_ERROR ("client %p: no session", client);
1434     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
1435     return FALSE;
1436   }
1437 no_uri:
1438   {
1439     GST_ERROR ("client %p: no uri supplied", client);
1440     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
1441     return FALSE;
1442   }
1443 not_found:
1444   {
1445     GST_ERROR ("client %p: no media for uri", client);
1446     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
1447     g_free (path);
1448     return FALSE;
1449   }
1450 no_aggregate:
1451   {
1452     GST_ERROR ("client %p: no aggregate path %s", client, path);
1453     send_generic_response (client,
1454         GST_RTSP_STS_ONLY_AGGREGATE_OPERATION_ALLOWED, ctx);
1455     g_free (path);
1456     return FALSE;
1457   }
1458 sig_failed:
1459   {
1460     GST_ERROR ("client %p: pre signal returned error: %s", client,
1461         gst_rtsp_status_as_text (sig_result));
1462     send_generic_response (client, sig_result, ctx);
1463     return FALSE;
1464   }
1465 invalid_state:
1466   {
1467     GST_ERROR ("client %p: not PLAYING or RECORDING", client);
1468     send_generic_response (client, GST_RTSP_STS_METHOD_NOT_VALID_IN_THIS_STATE,
1469         ctx);
1470     return FALSE;
1471   }
1472 not_supported:
1473   {
1474     GST_ERROR ("client %p: pausing not supported", client);
1475     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
1476     return FALSE;
1477   }
1478 }
1479
1480 /* convert @url and @path to a URL used as a content base for the factory
1481  * located at @path */
1482 static gchar *
1483 make_base_url (GstRTSPClient * client, GstRTSPUrl * url, const gchar * path)
1484 {
1485   GstRTSPUrl tmp;
1486   gchar *result;
1487   const gchar *trail;
1488
1489   /* check for trailing '/' and append one */
1490   trail = (path[strlen (path) - 1] != '/' ? "/" : "");
1491
1492   tmp = *url;
1493   tmp.user = NULL;
1494   tmp.passwd = NULL;
1495   tmp.abspath = g_strdup_printf ("%s%s", path, trail);
1496   tmp.query = NULL;
1497   result = gst_rtsp_url_get_request_uri (&tmp);
1498   g_free (tmp.abspath);
1499
1500   return result;
1501 }
1502
1503 static gboolean
1504 handle_play_request (GstRTSPClient * client, GstRTSPContext * ctx)
1505 {
1506   GstRTSPSession *session;
1507   GstRTSPClientClass *klass;
1508   GstRTSPSessionMedia *sessmedia;
1509   GstRTSPMedia *media;
1510   GstRTSPStatusCode code;
1511   GstRTSPUrl *uri;
1512   gchar *str;
1513   GstRTSPTimeRange *range;
1514   GstRTSPResult res;
1515   GstRTSPState rtspstate;
1516   GstRTSPRangeUnit unit = GST_RTSP_RANGE_NPT;
1517   gchar *path, *rtpinfo;
1518   gint matched;
1519   gchar *seek_style = NULL;
1520   GstRTSPStatusCode sig_result;
1521   GPtrArray *transports;
1522
1523   if (!(session = ctx->session))
1524     goto no_session;
1525
1526   if (!(uri = ctx->uri))
1527     goto no_uri;
1528
1529   klass = GST_RTSP_CLIENT_GET_CLASS (client);
1530   path = klass->make_path_from_uri (client, uri);
1531
1532   /* get a handle to the configuration of the media in the session */
1533   sessmedia = gst_rtsp_session_get_media (session, path, &matched);
1534   if (!sessmedia)
1535     goto not_found;
1536
1537   if (path[matched] != '\0')
1538     goto no_aggregate;
1539
1540   g_free (path);
1541
1542   ctx->sessmedia = sessmedia;
1543   ctx->media = media = gst_rtsp_session_media_get_media (sessmedia);
1544
1545   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_PRE_PLAY_REQUEST], 0,
1546       ctx, &sig_result);
1547   if (sig_result != GST_RTSP_STS_OK) {
1548     goto sig_failed;
1549   }
1550
1551   if (!(gst_rtsp_media_get_transport_mode (media) &
1552           GST_RTSP_TRANSPORT_MODE_PLAY))
1553     goto unsupported_mode;
1554
1555   /* the session state must be playing or ready */
1556   rtspstate = gst_rtsp_session_media_get_rtsp_state (sessmedia);
1557   if (rtspstate != GST_RTSP_STATE_PLAYING && rtspstate != GST_RTSP_STATE_READY)
1558     goto invalid_state;
1559
1560   /* update the pipeline */
1561   transports = gst_rtsp_session_media_get_transports (sessmedia);
1562   if (!gst_rtsp_media_complete_pipeline (media, transports)) {
1563     g_ptr_array_unref (transports);
1564     goto pipeline_error;
1565   }
1566   g_ptr_array_unref (transports);
1567
1568   /* in play we first unsuspend, media could be suspended from SDP or PAUSED */
1569   if (!gst_rtsp_media_unsuspend (media))
1570     goto unsuspend_failed;
1571
1572   /* parse the range header if we have one */
1573   res = gst_rtsp_message_get_header (ctx->request, GST_RTSP_HDR_RANGE, &str, 0);
1574   if (res == GST_RTSP_OK) {
1575     if (gst_rtsp_range_parse (str, &range) == GST_RTSP_OK) {
1576       GstRTSPMediaStatus media_status;
1577       GstSeekFlags flags = 0;
1578
1579       if (gst_rtsp_message_get_header (ctx->request, GST_RTSP_HDR_SEEK_STYLE,
1580               &seek_style, 0)) {
1581         if (g_strcmp0 (seek_style, "RAP") == 0)
1582           flags = GST_SEEK_FLAG_ACCURATE;
1583         else if (g_strcmp0 (seek_style, "CoRAP") == 0)
1584           flags = GST_SEEK_FLAG_KEY_UNIT;
1585         else if (g_strcmp0 (seek_style, "First-Prior") == 0)
1586           flags = GST_SEEK_FLAG_KEY_UNIT & GST_SEEK_FLAG_SNAP_BEFORE;
1587         else if (g_strcmp0 (seek_style, "Next") == 0)
1588           flags = GST_SEEK_FLAG_KEY_UNIT & GST_SEEK_FLAG_SNAP_AFTER;
1589         else
1590           GST_FIXME_OBJECT (client, "Add support for seek style %s",
1591               seek_style);
1592       }
1593
1594       /* we have a range, seek to the position */
1595       unit = range->unit;
1596       gst_rtsp_media_seek_full (media, range, flags);
1597       gst_rtsp_range_free (range);
1598
1599       media_status = gst_rtsp_media_get_status (media);
1600       if (media_status == GST_RTSP_MEDIA_STATUS_ERROR)
1601         goto seek_failed;
1602     }
1603   }
1604
1605   /* grab RTPInfo from the media now */
1606   rtpinfo = gst_rtsp_session_media_get_rtpinfo (sessmedia);
1607
1608   /* construct the response now */
1609   code = GST_RTSP_STS_OK;
1610   gst_rtsp_message_init_response (ctx->response, code,
1611       gst_rtsp_status_as_text (code), ctx->request);
1612
1613   /* add the RTP-Info header */
1614   if (rtpinfo)
1615     gst_rtsp_message_take_header (ctx->response, GST_RTSP_HDR_RTP_INFO,
1616         rtpinfo);
1617   if (seek_style)
1618     gst_rtsp_message_add_header (ctx->response, GST_RTSP_HDR_SEEK_STYLE,
1619         seek_style);
1620
1621   /* add the range */
1622   str = gst_rtsp_media_get_range_string (media, TRUE, unit);
1623   if (str)
1624     gst_rtsp_message_take_header (ctx->response, GST_RTSP_HDR_RANGE, str);
1625
1626   send_message (client, ctx, ctx->response, FALSE);
1627
1628   /* start playing after sending the response */
1629   gst_rtsp_session_media_set_state (sessmedia, GST_STATE_PLAYING);
1630
1631   gst_rtsp_session_media_set_rtsp_state (sessmedia, GST_RTSP_STATE_PLAYING);
1632
1633   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_PLAY_REQUEST], 0, ctx);
1634
1635   return TRUE;
1636
1637   /* ERRORS */
1638 no_session:
1639   {
1640     GST_ERROR ("client %p: no session", client);
1641     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
1642     return FALSE;
1643   }
1644 no_uri:
1645   {
1646     GST_ERROR ("client %p: no uri supplied", client);
1647     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
1648     return FALSE;
1649   }
1650 not_found:
1651   {
1652     GST_ERROR ("client %p: media not found", client);
1653     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
1654     return FALSE;
1655   }
1656 no_aggregate:
1657   {
1658     GST_ERROR ("client %p: no aggregate path %s", client, path);
1659     send_generic_response (client,
1660         GST_RTSP_STS_ONLY_AGGREGATE_OPERATION_ALLOWED, ctx);
1661     g_free (path);
1662     return FALSE;
1663   }
1664 sig_failed:
1665   {
1666     GST_ERROR ("client %p: pre signal returned error: %s", client,
1667         gst_rtsp_status_as_text (sig_result));
1668     send_generic_response (client, sig_result, ctx);
1669     return FALSE;
1670   }
1671 invalid_state:
1672   {
1673     GST_ERROR ("client %p: not PLAYING or READY", client);
1674     send_generic_response (client, GST_RTSP_STS_METHOD_NOT_VALID_IN_THIS_STATE,
1675         ctx);
1676     return FALSE;
1677   }
1678 pipeline_error:
1679   {
1680     GST_ERROR ("client %p: failed to configure the pipeline", client);
1681     send_generic_response (client, GST_RTSP_STS_METHOD_NOT_VALID_IN_THIS_STATE,
1682         ctx);
1683     return FALSE;
1684   }
1685 unsuspend_failed:
1686   {
1687     GST_ERROR ("client %p: unsuspend failed", client);
1688     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, ctx);
1689     return FALSE;
1690   }
1691 seek_failed:
1692   {
1693     GST_ERROR ("client %p: seek failed", client);
1694     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, ctx);
1695     return FALSE;
1696   }
1697 unsupported_mode:
1698   {
1699     GST_ERROR ("client %p: media does not support PLAY", client);
1700     send_generic_response (client, GST_RTSP_STS_METHOD_NOT_ALLOWED, ctx);
1701     return FALSE;
1702   }
1703 }
1704
1705 static void
1706 do_keepalive (GstRTSPSession * session)
1707 {
1708   GST_INFO ("keep session %p alive", session);
1709   gst_rtsp_session_touch (session);
1710 }
1711
1712 /* parse @transport and return a valid transport in @tr. only transports
1713  * supported by @stream are returned. Returns FALSE if no valid transport
1714  * was found. */
1715 static gboolean
1716 parse_transport (const char *transport, GstRTSPStream * stream,
1717     GstRTSPTransport * tr)
1718 {
1719   gint i;
1720   gboolean res;
1721   gchar **transports;
1722
1723   res = FALSE;
1724   gst_rtsp_transport_init (tr);
1725
1726   GST_DEBUG ("parsing transports %s", transport);
1727
1728   transports = g_strsplit (transport, ",", 0);
1729
1730   /* loop through the transports, try to parse */
1731   for (i = 0; transports[i]; i++) {
1732     res = gst_rtsp_transport_parse (transports[i], tr);
1733     if (res != GST_RTSP_OK) {
1734       /* no valid transport, search some more */
1735       GST_WARNING ("could not parse transport %s", transports[i]);
1736       goto next;
1737     }
1738
1739     /* we have a transport, see if it's supported */
1740     if (!gst_rtsp_stream_is_transport_supported (stream, tr)) {
1741       GST_WARNING ("unsupported transport %s", transports[i]);
1742       goto next;
1743     }
1744
1745     /* we have a valid transport */
1746     GST_INFO ("found valid transport %s", transports[i]);
1747     res = TRUE;
1748     break;
1749
1750   next:
1751     gst_rtsp_transport_init (tr);
1752   }
1753   g_strfreev (transports);
1754
1755   return res;
1756 }
1757
1758 static gboolean
1759 default_configure_client_media (GstRTSPClient * client, GstRTSPMedia * media,
1760     GstRTSPStream * stream, GstRTSPContext * ctx)
1761 {
1762   GstRTSPMessage *request = ctx->request;
1763   gchar *blocksize_str;
1764
1765   if (gst_rtsp_message_get_header (request, GST_RTSP_HDR_BLOCKSIZE,
1766           &blocksize_str, 0) == GST_RTSP_OK) {
1767     guint64 blocksize;
1768     gchar *end;
1769
1770     blocksize = g_ascii_strtoull (blocksize_str, &end, 10);
1771     if (end == blocksize_str)
1772       goto parse_failed;
1773
1774     /* we don't want to change the mtu when this media
1775      * can be shared because it impacts other clients */
1776     if (gst_rtsp_media_is_shared (media))
1777       goto done;
1778
1779     if (blocksize > G_MAXUINT)
1780       blocksize = G_MAXUINT;
1781
1782     gst_rtsp_stream_set_mtu (stream, blocksize);
1783   }
1784 done:
1785   return TRUE;
1786
1787   /* ERRORS */
1788 parse_failed:
1789   {
1790     GST_ERROR_OBJECT (client, "failed to parse blocksize");
1791     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
1792     return FALSE;
1793   }
1794 }
1795
1796 static gboolean
1797 default_configure_client_transport (GstRTSPClient * client,
1798     GstRTSPContext * ctx, GstRTSPTransport * ct)
1799 {
1800   GstRTSPClientPrivate *priv = client->priv;
1801
1802   /* we have a valid transport now, set the destination of the client. */
1803   if (ct->lower_transport == GST_RTSP_LOWER_TRANS_UDP_MCAST ||
1804       ct->lower_transport == GST_RTSP_LOWER_TRANS_UDP) {
1805
1806     /* allocate UDP ports */
1807     GSocketFamily family;
1808     gboolean use_client_settings = FALSE;
1809
1810     family = priv->is_ipv6 ? G_SOCKET_FAMILY_IPV6 : G_SOCKET_FAMILY_IPV4;
1811     if ((ct->lower_transport == GST_RTSP_LOWER_TRANS_UDP_MCAST) &&
1812         gst_rtsp_auth_check (GST_RTSP_AUTH_CHECK_TRANSPORT_CLIENT_SETTINGS) &&
1813         (ct->destination != NULL))
1814       use_client_settings = TRUE;
1815
1816     if (!gst_rtsp_stream_allocate_udp_sockets (ctx->stream, family, ct,
1817             use_client_settings))
1818       goto error_allocating_ports;
1819
1820     if (ct->lower_transport == GST_RTSP_LOWER_TRANS_UDP_MCAST) {
1821       GstRTSPAddress *addr = NULL;
1822
1823       if (use_client_settings) {
1824         /* the address has been successfully allocated, let's check if it's
1825          * the one requested by the client */
1826         addr = gst_rtsp_stream_reserve_address (ctx->stream, ct->destination,
1827             ct->port.min, ct->port.max - ct->port.min + 1, ct->ttl);
1828
1829         if (addr == NULL)
1830           goto no_address;
1831       } else {
1832         g_free (ct->destination);
1833         addr = gst_rtsp_stream_get_multicast_address (ctx->stream, family);
1834         if (addr == NULL)
1835           goto no_address;
1836         ct->destination = g_strdup (addr->address);
1837         ct->port.min = addr->port;
1838         ct->port.max = addr->port + addr->n_ports - 1;
1839         ct->ttl = addr->ttl;
1840       }
1841
1842       gst_rtsp_address_free (addr);
1843     } else {
1844       GstRTSPUrl *url;
1845
1846       url = gst_rtsp_connection_get_url (priv->connection);
1847       g_free (ct->destination);
1848       ct->destination = g_strdup (url->host);
1849     }
1850   } else {
1851     GstRTSPUrl *url;
1852
1853     url = gst_rtsp_connection_get_url (priv->connection);
1854     g_free (ct->destination);
1855     ct->destination = g_strdup (url->host);
1856
1857     if (ct->lower_transport & GST_RTSP_LOWER_TRANS_TCP) {
1858       GSocket *sock;
1859       GSocketAddress *addr;
1860
1861       sock = gst_rtsp_connection_get_read_socket (priv->connection);
1862       if ((addr = g_socket_get_remote_address (sock, NULL))) {
1863         /* our read port is the sender port of client */
1864         ct->client_port.min =
1865             g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (addr));
1866         g_object_unref (addr);
1867       }
1868       if ((addr = g_socket_get_local_address (sock, NULL))) {
1869         ct->server_port.max =
1870             g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (addr));
1871         g_object_unref (addr);
1872       }
1873       sock = gst_rtsp_connection_get_write_socket (priv->connection);
1874       if ((addr = g_socket_get_remote_address (sock, NULL))) {
1875         /* our write port is the receiver port of client */
1876         ct->client_port.max =
1877             g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (addr));
1878         g_object_unref (addr);
1879       }
1880       if ((addr = g_socket_get_local_address (sock, NULL))) {
1881         ct->server_port.min =
1882             g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (addr));
1883         g_object_unref (addr);
1884       }
1885       /* check if the client selected channels for TCP */
1886       if (ct->interleaved.min == -1 || ct->interleaved.max == -1) {
1887         gst_rtsp_session_media_alloc_channels (ctx->sessmedia,
1888             &ct->interleaved);
1889       }
1890     }
1891   }
1892   return TRUE;
1893
1894   /* ERRORS */
1895 error_allocating_ports:
1896   {
1897     GST_ERROR_OBJECT (client, "Failed to allocate UDP ports");
1898     return FALSE;
1899   }
1900 no_address:
1901   {
1902     GST_ERROR_OBJECT (client, "Failed to acquire address for stream");
1903     return FALSE;
1904   }
1905 }
1906
1907 static GstRTSPTransport *
1908 make_server_transport (GstRTSPClient * client, GstRTSPMedia * media,
1909     GstRTSPContext * ctx, GstRTSPTransport * ct)
1910 {
1911   GstRTSPTransport *st;
1912   GInetAddress *addr;
1913   GSocketFamily family;
1914
1915   /* prepare the server transport */
1916   gst_rtsp_transport_new (&st);
1917
1918   st->trans = ct->trans;
1919   st->profile = ct->profile;
1920   st->lower_transport = ct->lower_transport;
1921   st->mode_play = ct->mode_play;
1922   st->mode_record = ct->mode_record;
1923
1924   addr = g_inet_address_new_from_string (ct->destination);
1925
1926   if (!addr) {
1927     GST_ERROR ("failed to get inet addr from client destination");
1928     family = G_SOCKET_FAMILY_IPV4;
1929   } else {
1930     family = g_inet_address_get_family (addr);
1931     g_object_unref (addr);
1932     addr = NULL;
1933   }
1934
1935   switch (st->lower_transport) {
1936     case GST_RTSP_LOWER_TRANS_UDP:
1937       st->client_port = ct->client_port;
1938       gst_rtsp_stream_get_server_port (ctx->stream, &st->server_port, family);
1939       break;
1940     case GST_RTSP_LOWER_TRANS_UDP_MCAST:
1941       st->port = ct->port;
1942       st->destination = g_strdup (ct->destination);
1943       st->ttl = ct->ttl;
1944       break;
1945     case GST_RTSP_LOWER_TRANS_TCP:
1946       st->interleaved = ct->interleaved;
1947       st->client_port = ct->client_port;
1948       st->server_port = ct->server_port;
1949     default:
1950       break;
1951   }
1952
1953   if ((gst_rtsp_media_get_transport_mode (media) &
1954           GST_RTSP_TRANSPORT_MODE_PLAY))
1955     gst_rtsp_stream_get_ssrc (ctx->stream, &st->ssrc);
1956
1957   return st;
1958 }
1959
1960 #define AES_128_KEY_LEN 16
1961 #define AES_256_KEY_LEN 32
1962
1963 #define HMAC_32_KEY_LEN 4
1964 #define HMAC_80_KEY_LEN 10
1965
1966 static gboolean
1967 mikey_apply_policy (GstCaps * caps, GstMIKEYMessage * msg, guint8 policy)
1968 {
1969   const gchar *srtp_cipher;
1970   const gchar *srtp_auth;
1971   const GstMIKEYPayload *sp;
1972   guint i;
1973
1974   /* loop over Security policy until we find one containing policy */
1975   for (i = 0;; i++) {
1976     if ((sp = gst_mikey_message_find_payload (msg, GST_MIKEY_PT_SP, i)) == NULL)
1977       break;
1978
1979     if (((GstMIKEYPayloadSP *) sp)->policy == policy)
1980       break;
1981   }
1982
1983   /* the default ciphers */
1984   srtp_cipher = "aes-128-icm";
1985   srtp_auth = "hmac-sha1-80";
1986
1987   /* now override the defaults with what is in the Security Policy */
1988   if (sp != NULL) {
1989     guint len;
1990
1991     /* collect all the params and go over them */
1992     len = gst_mikey_payload_sp_get_n_params (sp);
1993     for (i = 0; i < len; i++) {
1994       const GstMIKEYPayloadSPParam *param =
1995           gst_mikey_payload_sp_get_param (sp, i);
1996
1997       switch (param->type) {
1998         case GST_MIKEY_SP_SRTP_ENC_ALG:
1999           switch (param->val[0]) {
2000             case 0:
2001               srtp_cipher = "null";
2002               break;
2003             case 2:
2004             case 1:
2005               srtp_cipher = "aes-128-icm";
2006               break;
2007             default:
2008               break;
2009           }
2010           break;
2011         case GST_MIKEY_SP_SRTP_ENC_KEY_LEN:
2012           switch (param->val[0]) {
2013             case AES_128_KEY_LEN:
2014               srtp_cipher = "aes-128-icm";
2015               break;
2016             case AES_256_KEY_LEN:
2017               srtp_cipher = "aes-256-icm";
2018               break;
2019             default:
2020               break;
2021           }
2022           break;
2023         case GST_MIKEY_SP_SRTP_AUTH_ALG:
2024           switch (param->val[0]) {
2025             case 0:
2026               srtp_auth = "null";
2027               break;
2028             case 2:
2029             case 1:
2030               srtp_auth = "hmac-sha1-80";
2031               break;
2032             default:
2033               break;
2034           }
2035           break;
2036         case GST_MIKEY_SP_SRTP_AUTH_KEY_LEN:
2037           switch (param->val[0]) {
2038             case HMAC_32_KEY_LEN:
2039               srtp_auth = "hmac-sha1-32";
2040               break;
2041             case HMAC_80_KEY_LEN:
2042               srtp_auth = "hmac-sha1-80";
2043               break;
2044             default:
2045               break;
2046           }
2047           break;
2048         case GST_MIKEY_SP_SRTP_SRTP_ENC:
2049           break;
2050         case GST_MIKEY_SP_SRTP_SRTCP_ENC:
2051           break;
2052         default:
2053           break;
2054       }
2055     }
2056   }
2057   /* now configure the SRTP parameters */
2058   gst_caps_set_simple (caps,
2059       "srtp-cipher", G_TYPE_STRING, srtp_cipher,
2060       "srtp-auth", G_TYPE_STRING, srtp_auth,
2061       "srtcp-cipher", G_TYPE_STRING, srtp_cipher,
2062       "srtcp-auth", G_TYPE_STRING, srtp_auth, NULL);
2063
2064   return TRUE;
2065 }
2066
2067 static gboolean
2068 handle_mikey_data (GstRTSPClient * client, GstRTSPContext * ctx,
2069     guint8 * data, gsize size)
2070 {
2071   GstMIKEYMessage *msg;
2072   guint i, n_cs;
2073   GstCaps *caps = NULL;
2074   GstMIKEYPayloadKEMAC *kemac;
2075   const GstMIKEYPayloadKeyData *pkd;
2076   GstBuffer *key;
2077
2078   /* the MIKEY message contains a CSB or crypto session bundle. It is a
2079    * set of Crypto Sessions protected with the same master key.
2080    * In the context of SRTP, an RTP and its RTCP stream is part of a
2081    * crypto session */
2082   if ((msg = gst_mikey_message_new_from_data (data, size, NULL, NULL)) == NULL)
2083     goto parse_failed;
2084
2085   /* we can only handle SRTP crypto sessions for now */
2086   if (msg->map_type != GST_MIKEY_MAP_TYPE_SRTP)
2087     goto invalid_map_type;
2088
2089   /* get the number of crypto sessions. This maps SSRC to its
2090    * security parameters */
2091   n_cs = gst_mikey_message_get_n_cs (msg);
2092   if (n_cs == 0)
2093     goto no_crypto_sessions;
2094
2095   /* we also need keys */
2096   if (!(kemac = (GstMIKEYPayloadKEMAC *) gst_mikey_message_find_payload
2097           (msg, GST_MIKEY_PT_KEMAC, 0)))
2098     goto no_keys;
2099
2100   /* we don't support encrypted keys */
2101   if (kemac->enc_alg != GST_MIKEY_ENC_NULL
2102       || kemac->mac_alg != GST_MIKEY_MAC_NULL)
2103     goto unsupported_encryption;
2104
2105   /* get Key data sub-payload */
2106   pkd = (const GstMIKEYPayloadKeyData *)
2107       gst_mikey_payload_kemac_get_sub (&kemac->pt, 0);
2108
2109   key =
2110       gst_buffer_new_wrapped (g_memdup (pkd->key_data, pkd->key_len),
2111       pkd->key_len);
2112
2113   /* go over all crypto sessions and create the security policy for each
2114    * SSRC */
2115   for (i = 0; i < n_cs; i++) {
2116     const GstMIKEYMapSRTP *map = gst_mikey_message_get_cs_srtp (msg, i);
2117
2118     caps = gst_caps_new_simple ("application/x-srtp",
2119         "ssrc", G_TYPE_UINT, map->ssrc,
2120         "roc", G_TYPE_UINT, map->roc, "srtp-key", GST_TYPE_BUFFER, key, NULL);
2121     mikey_apply_policy (caps, msg, map->policy);
2122
2123     gst_rtsp_stream_update_crypto (ctx->stream, map->ssrc, caps);
2124     gst_caps_unref (caps);
2125   }
2126   gst_mikey_message_unref (msg);
2127   gst_buffer_unref (key);
2128
2129   return TRUE;
2130
2131   /* ERRORS */
2132 parse_failed:
2133   {
2134     GST_DEBUG_OBJECT (client, "failed to parse MIKEY message");
2135     return FALSE;
2136   }
2137 invalid_map_type:
2138   {
2139     GST_DEBUG_OBJECT (client, "invalid map type %d", msg->map_type);
2140     goto cleanup_message;
2141   }
2142 no_crypto_sessions:
2143   {
2144     GST_DEBUG_OBJECT (client, "no crypto sessions");
2145     goto cleanup_message;
2146   }
2147 no_keys:
2148   {
2149     GST_DEBUG_OBJECT (client, "no keys found");
2150     goto cleanup_message;
2151   }
2152 unsupported_encryption:
2153   {
2154     GST_DEBUG_OBJECT (client, "unsupported key encryption");
2155     goto cleanup_message;
2156   }
2157 cleanup_message:
2158   {
2159     gst_mikey_message_unref (msg);
2160     return FALSE;
2161   }
2162 }
2163
2164 #define IS_STRIP_CHAR(c) (g_ascii_isspace ((guchar)(c)) || ((c) == '\"'))
2165
2166 static void
2167 strip_chars (gchar * str)
2168 {
2169   gchar *s;
2170   gsize len;
2171
2172   len = strlen (str);
2173   while (len--) {
2174     if (!IS_STRIP_CHAR (str[len]))
2175       break;
2176     str[len] = '\0';
2177   }
2178   for (s = str; *s && IS_STRIP_CHAR (*s); s++);
2179   memmove (str, s, len + 1);
2180 }
2181
2182 /* KeyMgmt = "KeyMgmt" ":" key-mgmt-spec 0*("," key-mgmt-spec)
2183  * key-mgmt-spec = "prot" "=" KMPID ";" ["uri" "=" %x22 URI %x22 ";"]
2184  */
2185 static gboolean
2186 handle_keymgmt (GstRTSPClient * client, GstRTSPContext * ctx, gchar * keymgmt)
2187 {
2188   gchar **specs;
2189   gint i, j;
2190
2191   specs = g_strsplit (keymgmt, ",", 0);
2192   for (i = 0; specs[i]; i++) {
2193     gchar **split;
2194
2195     split = g_strsplit (specs[i], ";", 0);
2196     for (j = 0; split[j]; j++) {
2197       g_strstrip (split[j]);
2198       if (g_str_has_prefix (split[j], "prot=")) {
2199         g_strstrip (split[j] + 5);
2200         if (!g_str_equal (split[j] + 5, "mikey"))
2201           break;
2202         GST_DEBUG ("found mikey");
2203       } else if (g_str_has_prefix (split[j], "uri=")) {
2204         strip_chars (split[j] + 4);
2205         GST_DEBUG ("found uri '%s'", split[j] + 4);
2206       } else if (g_str_has_prefix (split[j], "data=")) {
2207         guchar *data;
2208         gsize size;
2209         strip_chars (split[j] + 5);
2210         GST_DEBUG ("found data '%s'", split[j] + 5);
2211         data = g_base64_decode_inplace (split[j] + 5, &size);
2212         handle_mikey_data (client, ctx, data, size);
2213       }
2214     }
2215     g_strfreev (split);
2216   }
2217   g_strfreev (specs);
2218   return TRUE;
2219 }
2220
2221 static gboolean
2222 rtsp_ctrl_timeout_cb (gpointer user_data)
2223 {
2224   gboolean res = G_SOURCE_CONTINUE;
2225   GstRTSPClient *client = (GstRTSPClient *) user_data;
2226   GstRTSPClientPrivate *priv = client->priv;
2227
2228   priv->rtsp_ctrl_timeout_cnt += RTSP_CTRL_CB_INTERVAL;
2229
2230   if (priv->rtsp_ctrl_timeout_cnt > RTSP_CTRL_TIMEOUT_VALUE) {
2231     GST_DEBUG ("rtsp control session timeout id=%u expired, closing client.",
2232         priv->rtsp_ctrl_timeout_id);
2233     g_mutex_lock (&priv->lock);
2234     priv->rtsp_ctrl_timeout_id = 0;
2235     priv->rtsp_ctrl_timeout_cnt = 0;
2236     g_mutex_unlock (&priv->lock);
2237     gst_rtsp_client_close (client);
2238
2239     res = G_SOURCE_REMOVE;
2240   }
2241
2242   return res;
2243 }
2244
2245 static void
2246 rtsp_ctrl_timeout_remove (GstRTSPClientPrivate * priv)
2247 {
2248   g_mutex_lock (&priv->lock);
2249
2250   if (priv->rtsp_ctrl_timeout_id != 0) {
2251     g_source_destroy (g_main_context_find_source_by_id (priv->watch_context,
2252             priv->rtsp_ctrl_timeout_id));
2253     GST_DEBUG ("rtsp control session removed timeout id=%u.",
2254         priv->rtsp_ctrl_timeout_id);
2255     priv->rtsp_ctrl_timeout_id = 0;
2256     priv->rtsp_ctrl_timeout_cnt = 0;
2257   }
2258
2259   g_mutex_unlock (&priv->lock);
2260 }
2261
2262 static gboolean
2263 handle_setup_request (GstRTSPClient * client, GstRTSPContext * ctx)
2264 {
2265   GstRTSPClientPrivate *priv = client->priv;
2266   GstRTSPResult res;
2267   GstRTSPUrl *uri;
2268   gchar *transport, *keymgmt;
2269   GstRTSPTransport *ct, *st;
2270   GstRTSPStatusCode code;
2271   GstRTSPSession *session;
2272   GstRTSPStreamTransport *trans;
2273   gchar *trans_str;
2274   GstRTSPSessionMedia *sessmedia;
2275   GstRTSPMedia *media;
2276   GstRTSPStream *stream;
2277   GstRTSPState rtspstate;
2278   GstRTSPClientClass *klass;
2279   gchar *path, *control = NULL;
2280   gint matched;
2281   gboolean new_session = FALSE;
2282   GstRTSPStatusCode sig_result;
2283   gchar *pipelined_request_id = NULL, *accept_range = NULL;
2284
2285   if (!ctx->uri)
2286     goto no_uri;
2287
2288   uri = ctx->uri;
2289   klass = GST_RTSP_CLIENT_GET_CLASS (client);
2290   path = klass->make_path_from_uri (client, uri);
2291
2292   /* parse the transport */
2293   res =
2294       gst_rtsp_message_get_header (ctx->request, GST_RTSP_HDR_TRANSPORT,
2295       &transport, 0);
2296   if (res != GST_RTSP_OK)
2297     goto no_transport;
2298
2299   /* Handle Pipelined-requests if using >= 2.0 */
2300   if (ctx->request->type_data.request.version >= GST_RTSP_VERSION_2_0)
2301     gst_rtsp_message_get_header (ctx->request,
2302         GST_RTSP_HDR_PIPELINED_REQUESTS, &pipelined_request_id, 0);
2303
2304   /* we create the session after parsing stuff so that we don't make
2305    * a session for malformed requests */
2306   if (priv->session_pool == NULL)
2307     goto no_pool;
2308
2309   session = ctx->session;
2310
2311   if (session) {
2312     g_object_ref (session);
2313     /* get a handle to the configuration of the media in the session, this can
2314      * return NULL if this is a new url to manage in this session. */
2315     sessmedia = gst_rtsp_session_get_media (session, path, &matched);
2316   } else {
2317     /* we need a new media configuration in this session */
2318     sessmedia = NULL;
2319   }
2320
2321   /* we have no session media, find one and manage it */
2322   if (sessmedia == NULL) {
2323     /* get a handle to the configuration of the media in the session */
2324     media = find_media (client, ctx, path, &matched);
2325     /* need to suspend the media, if the protocol has changed */
2326     if (media != NULL)
2327       gst_rtsp_media_suspend (media);
2328   } else {
2329     if ((media = gst_rtsp_session_media_get_media (sessmedia)))
2330       g_object_ref (media);
2331     else
2332       goto media_not_found;
2333   }
2334   /* no media, not found then */
2335   if (media == NULL)
2336     goto media_not_found_no_reply;
2337
2338   if (path[matched] == '\0') {
2339     if (gst_rtsp_media_n_streams (media) == 1) {
2340       stream = gst_rtsp_media_get_stream (media, 0);
2341     } else {
2342       goto control_not_found;
2343     }
2344   } else {
2345     /* path is what matched. */
2346     path[matched] = '\0';
2347     /* control is remainder */
2348     control = &path[matched + 1];
2349
2350     /* find the stream now using the control part */
2351     stream = gst_rtsp_media_find_stream (media, control);
2352   }
2353
2354   if (stream == NULL)
2355     goto stream_not_found;
2356
2357   /* now we have a uri identifying a valid media and stream */
2358   ctx->stream = stream;
2359   ctx->media = media;
2360
2361   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_PRE_SETUP_REQUEST], 0,
2362       ctx, &sig_result);
2363   if (sig_result != GST_RTSP_STS_OK) {
2364     goto sig_failed;
2365   }
2366
2367   if (session == NULL) {
2368     /* create a session if this fails we probably reached our session limit or
2369      * something. */
2370     if (!(session = gst_rtsp_session_pool_create (priv->session_pool)))
2371       goto service_unavailable;
2372
2373     /* Pipelined requests should be cleared between sessions */
2374     g_hash_table_remove_all (priv->pipelined_requests);
2375
2376     /* make sure this client is closed when the session is closed */
2377     client_watch_session (client, session);
2378
2379     new_session = TRUE;
2380     /* signal new session */
2381     g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_NEW_SESSION], 0,
2382         session);
2383
2384     ctx->session = session;
2385   }
2386
2387   if (pipelined_request_id) {
2388     g_hash_table_insert (client->priv->pipelined_requests,
2389         g_strdup (pipelined_request_id),
2390         g_strdup (gst_rtsp_session_get_sessionid (session)));
2391   }
2392   rtsp_ctrl_timeout_remove (priv);
2393
2394   if (!klass->configure_client_media (client, media, stream, ctx))
2395     goto configure_media_failed_no_reply;
2396
2397   gst_rtsp_transport_new (&ct);
2398
2399   /* parse and find a usable supported transport */
2400   if (!parse_transport (transport, stream, ct))
2401     goto unsupported_transports;
2402
2403   if ((ct->mode_play
2404           && !(gst_rtsp_media_get_transport_mode (media) &
2405               GST_RTSP_TRANSPORT_MODE_PLAY)) || (ct->mode_record
2406           && !(gst_rtsp_media_get_transport_mode (media) &
2407               GST_RTSP_TRANSPORT_MODE_RECORD)))
2408     goto unsupported_mode;
2409
2410   /* parse the keymgmt */
2411   if (gst_rtsp_message_get_header (ctx->request, GST_RTSP_HDR_KEYMGMT,
2412           &keymgmt, 0) == GST_RTSP_OK) {
2413     if (!handle_keymgmt (client, ctx, keymgmt))
2414       goto keymgmt_error;
2415   }
2416
2417   if (gst_rtsp_message_get_header (ctx->request, GST_RTSP_HDR_ACCEPT_RANGES,
2418           &accept_range, 0) == GST_RTSP_OK) {
2419     GEnumValue *runit = NULL;
2420     gint i;
2421     gchar **valid_ranges;
2422     GEnumClass *runit_class = g_type_class_ref (GST_TYPE_RTSP_RANGE_UNIT);
2423
2424     gst_rtsp_message_dump (ctx->request);
2425     valid_ranges = g_strsplit (accept_range, ",", -1);
2426
2427     for (i = 0; valid_ranges[i]; i++) {
2428       gchar *range = valid_ranges[i];
2429
2430       while (*range == ' ')
2431         range++;
2432
2433       runit = g_enum_get_value_by_nick (runit_class, range);
2434       if (runit)
2435         break;
2436     }
2437     g_strfreev (valid_ranges);
2438     g_type_class_unref (runit_class);
2439
2440     if (!runit)
2441       goto unsupported_range_unit;
2442   }
2443
2444   if (sessmedia == NULL) {
2445     /* manage the media in our session now, if not done already  */
2446     sessmedia =
2447         gst_rtsp_session_manage_media (session, path, g_object_ref (media));
2448     /* if we stil have no media, error */
2449     if (sessmedia == NULL)
2450       goto sessmedia_unavailable;
2451
2452     /* don't cache media anymore */
2453     clean_cached_media (client, FALSE);
2454   }
2455
2456   ctx->sessmedia = sessmedia;
2457
2458   /* update the client transport */
2459   if (!klass->configure_client_transport (client, ctx, ct))
2460     goto unsupported_client_transport;
2461
2462   /* set in the session media transport */
2463   trans = gst_rtsp_session_media_set_transport (sessmedia, stream, ct);
2464
2465   ctx->trans = trans;
2466
2467   /* configure the url used to set this transport, this we will use when
2468    * generating the response for the PLAY request */
2469   gst_rtsp_stream_transport_set_url (trans, uri);
2470   /* configure keepalive for this transport */
2471   gst_rtsp_stream_transport_set_keepalive (trans,
2472       (GstRTSPKeepAliveFunc) do_keepalive, session, NULL);
2473
2474   if (ct->lower_transport == GST_RTSP_LOWER_TRANS_TCP) {
2475     /* our callbacks to send data on this TCP connection */
2476     gst_rtsp_stream_transport_set_callbacks (trans,
2477         (GstRTSPSendFunc) do_send_data,
2478         (GstRTSPSendFunc) do_send_data, client, NULL);
2479
2480     g_hash_table_insert (priv->transports,
2481         GINT_TO_POINTER (ct->interleaved.min), trans);
2482     g_object_ref (trans);
2483     g_hash_table_insert (priv->transports,
2484         GINT_TO_POINTER (ct->interleaved.max), trans);
2485     g_object_ref (trans);
2486   }
2487
2488   /* create and serialize the server transport */
2489   st = make_server_transport (client, media, ctx, ct);
2490   trans_str = gst_rtsp_transport_as_text (st);
2491   gst_rtsp_transport_free (st);
2492
2493   /* construct the response now */
2494   code = GST_RTSP_STS_OK;
2495   gst_rtsp_message_init_response (ctx->response, code,
2496       gst_rtsp_status_as_text (code), ctx->request);
2497
2498   gst_rtsp_message_add_header (ctx->response, GST_RTSP_HDR_TRANSPORT,
2499       trans_str);
2500   g_free (trans_str);
2501
2502   if (pipelined_request_id)
2503     gst_rtsp_message_add_header (ctx->response, GST_RTSP_HDR_PIPELINED_REQUESTS,
2504         pipelined_request_id);
2505
2506   if (ctx->request->type_data.request.version >= GST_RTSP_VERSION_2_0) {
2507     GstClockTimeDiff seekable = gst_rtsp_media_seekable (media);
2508     GString *media_properties = g_string_new (NULL);
2509
2510     if (seekable == -1)
2511       g_string_append (media_properties,
2512           "No-Seeking,Time-Progressing,Time-Duration=0.0");
2513     else if (seekable == 0)
2514       g_string_append (media_properties, "Beginning-Only");
2515     else if (seekable == G_MAXINT64)
2516       g_string_append (media_properties, "Random-Access");
2517     else
2518       g_string_append_printf (media_properties,
2519           "Random-Access=%f, Unlimited, Immutable",
2520           (gdouble) seekable / GST_SECOND);
2521
2522     gst_rtsp_message_add_header (ctx->response, GST_RTSP_HDR_MEDIA_PROPERTIES,
2523         g_string_free (media_properties, FALSE));
2524     /* TODO Check how Accept-Ranges should be filled */
2525     gst_rtsp_message_add_header (ctx->request, GST_RTSP_HDR_ACCEPT_RANGES,
2526         "npt, clock, smpte, clock");
2527   }
2528
2529   send_message (client, ctx, ctx->response, FALSE);
2530
2531   /* update the state */
2532   rtspstate = gst_rtsp_session_media_get_rtsp_state (sessmedia);
2533   switch (rtspstate) {
2534     case GST_RTSP_STATE_PLAYING:
2535     case GST_RTSP_STATE_RECORDING:
2536     case GST_RTSP_STATE_READY:
2537       /* no state change */
2538       break;
2539     default:
2540       gst_rtsp_session_media_set_rtsp_state (sessmedia, GST_RTSP_STATE_READY);
2541       break;
2542   }
2543   g_object_unref (media);
2544   g_object_unref (session);
2545   g_free (path);
2546
2547   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_SETUP_REQUEST], 0, ctx);
2548
2549   return TRUE;
2550
2551   /* ERRORS */
2552 no_uri:
2553   {
2554     GST_ERROR ("client %p: no uri", client);
2555     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
2556     return FALSE;
2557   }
2558 no_transport:
2559   {
2560     GST_ERROR ("client %p: no transport", client);
2561     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, ctx);
2562     goto cleanup_path;
2563   }
2564 no_pool:
2565   {
2566     GST_ERROR ("client %p: no session pool configured", client);
2567     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
2568     goto cleanup_path;
2569   }
2570 media_not_found_no_reply:
2571   {
2572     GST_ERROR ("client %p: media '%s' not found", client, path);
2573     /* error reply is already sent */
2574     goto cleanup_session;
2575   }
2576 media_not_found:
2577   {
2578     GST_ERROR ("client %p: media '%s' not found", client, path);
2579     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
2580     goto cleanup_session;
2581   }
2582 control_not_found:
2583   {
2584     GST_ERROR ("client %p: no control in path '%s'", client, path);
2585     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
2586     g_object_unref (media);
2587     goto cleanup_session;
2588   }
2589 stream_not_found:
2590   {
2591     GST_ERROR ("client %p: stream '%s' not found", client,
2592         GST_STR_NULL (control));
2593     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
2594     g_object_unref (media);
2595     goto cleanup_session;
2596   }
2597 sig_failed:
2598   {
2599     GST_ERROR ("client %p: pre signal returned error: %s", client,
2600         gst_rtsp_status_as_text (sig_result));
2601     send_generic_response (client, sig_result, ctx);
2602     g_object_unref (media);
2603     goto cleanup_path;
2604   }
2605 service_unavailable:
2606   {
2607     GST_ERROR ("client %p: can't create session", client);
2608     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, ctx);
2609     g_object_unref (media);
2610     goto cleanup_session;
2611   }
2612 sessmedia_unavailable:
2613   {
2614     GST_ERROR ("client %p: can't create session media", client);
2615     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, ctx);
2616     goto cleanup_transport;
2617   }
2618 configure_media_failed_no_reply:
2619   {
2620     GST_ERROR ("client %p: configure_media failed", client);
2621     g_object_unref (media);
2622     /* error reply is already sent */
2623     goto cleanup_session;
2624   }
2625 unsupported_transports:
2626   {
2627     GST_ERROR ("client %p: unsupported transports", client);
2628     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, ctx);
2629     goto cleanup_transport;
2630   }
2631 unsupported_client_transport:
2632   {
2633     GST_ERROR ("client %p: unsupported client transport", client);
2634     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, ctx);
2635     goto cleanup_transport;
2636   }
2637 unsupported_mode:
2638   {
2639     GST_ERROR ("client %p: unsupported mode (media play: %d, media record: %d, "
2640         "mode play: %d, mode record: %d)", client,
2641         ! !(gst_rtsp_media_get_transport_mode (media) &
2642             GST_RTSP_TRANSPORT_MODE_PLAY),
2643         ! !(gst_rtsp_media_get_transport_mode (media) &
2644             GST_RTSP_TRANSPORT_MODE_RECORD), ct->mode_play, ct->mode_record);
2645     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_TRANSPORT, ctx);
2646     goto cleanup_transport;
2647   }
2648 unsupported_range_unit:
2649   {
2650     GST_ERROR ("Client %p: does not support any range format we support",
2651         client);
2652     send_generic_response (client, GST_RTSP_STS_NOT_IMPLEMENTED, ctx);
2653     goto cleanup_transport;
2654   }
2655 keymgmt_error:
2656   {
2657     GST_ERROR ("client %p: keymgmt error", client);
2658     send_generic_response (client, GST_RTSP_STS_KEY_MANAGEMENT_FAILURE, ctx);
2659     goto cleanup_transport;
2660   }
2661   {
2662   cleanup_transport:
2663     gst_rtsp_transport_free (ct);
2664     if (media)
2665       g_object_unref (media);
2666   cleanup_session:
2667     if (new_session)
2668       gst_rtsp_session_pool_remove (priv->session_pool, session);
2669     if (session)
2670       g_object_unref (session);
2671   cleanup_path:
2672     g_free (path);
2673     return FALSE;
2674   }
2675 }
2676
2677 static GstSDPMessage *
2678 create_sdp (GstRTSPClient * client, GstRTSPMedia * media)
2679 {
2680   GstRTSPClientPrivate *priv = client->priv;
2681   GstSDPMessage *sdp;
2682   GstSDPInfo info;
2683   const gchar *proto;
2684   guint64 session_id_tmp;
2685   gchar session_id[21];
2686
2687   gst_sdp_message_new (&sdp);
2688
2689   /* some standard things first */
2690   gst_sdp_message_set_version (sdp, "0");
2691
2692   if (priv->is_ipv6)
2693     proto = "IP6";
2694   else
2695     proto = "IP4";
2696
2697   session_id_tmp = (((guint64) g_random_int ()) << 32) | g_random_int ();
2698   g_snprintf (session_id, sizeof (session_id), "%" G_GUINT64_FORMAT,
2699       session_id_tmp);
2700
2701   gst_sdp_message_set_origin (sdp, "-", session_id, "1", "IN", proto,
2702       priv->server_ip);
2703
2704   gst_sdp_message_set_session_name (sdp, "Session streamed with GStreamer");
2705   gst_sdp_message_set_information (sdp, "rtsp-server");
2706   gst_sdp_message_add_time (sdp, "0", "0", NULL);
2707   gst_sdp_message_add_attribute (sdp, "tool", "GStreamer");
2708   gst_sdp_message_add_attribute (sdp, "type", "broadcast");
2709   gst_sdp_message_add_attribute (sdp, "control", "*");
2710
2711   info.is_ipv6 = priv->is_ipv6;
2712   info.server_ip = priv->server_ip;
2713
2714   /* create an SDP for the media object */
2715   if (!gst_rtsp_media_setup_sdp (media, sdp, &info))
2716     goto no_sdp;
2717
2718   return sdp;
2719
2720   /* ERRORS */
2721 no_sdp:
2722   {
2723     GST_ERROR ("client %p: could not create SDP", client);
2724     gst_sdp_message_free (sdp);
2725     return NULL;
2726   }
2727 }
2728
2729 /* for the describe we must generate an SDP */
2730 static gboolean
2731 handle_describe_request (GstRTSPClient * client, GstRTSPContext * ctx)
2732 {
2733   GstRTSPClientPrivate *priv = client->priv;
2734   GstRTSPResult res;
2735   GstSDPMessage *sdp;
2736   guint i;
2737   gchar *path, *str;
2738   GstRTSPMedia *media;
2739   GstRTSPClientClass *klass;
2740   GstRTSPStatusCode sig_result;
2741
2742   klass = GST_RTSP_CLIENT_GET_CLASS (client);
2743
2744   if (!ctx->uri)
2745     goto no_uri;
2746
2747   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_PRE_DESCRIBE_REQUEST],
2748       0, ctx, &sig_result);
2749   if (sig_result != GST_RTSP_STS_OK) {
2750     goto sig_failed;
2751   }
2752
2753   /* check what kind of format is accepted, we don't really do anything with it
2754    * and always return SDP for now. */
2755   for (i = 0;; i++) {
2756     gchar *accept;
2757
2758     res =
2759         gst_rtsp_message_get_header (ctx->request, GST_RTSP_HDR_ACCEPT,
2760         &accept, i);
2761     if (res == GST_RTSP_ENOTIMPL)
2762       break;
2763
2764     if (g_ascii_strcasecmp (accept, "application/sdp") == 0)
2765       break;
2766   }
2767
2768   if (!priv->mount_points)
2769     goto no_mount_points;
2770
2771   if (!(path = gst_rtsp_mount_points_make_path (priv->mount_points, ctx->uri)))
2772     goto no_path;
2773
2774   /* find the media object for the uri */
2775   if (!(media = find_media (client, ctx, path, NULL)))
2776     goto no_media;
2777
2778   if (!(gst_rtsp_media_get_transport_mode (media) &
2779           GST_RTSP_TRANSPORT_MODE_PLAY))
2780     goto unsupported_mode;
2781
2782   /* create an SDP for the media object on this client */
2783   if (!(sdp = klass->create_sdp (client, media)))
2784     goto no_sdp;
2785
2786   /* we suspend after the describe */
2787   gst_rtsp_media_suspend (media);
2788   g_object_unref (media);
2789
2790   gst_rtsp_message_init_response (ctx->response, GST_RTSP_STS_OK,
2791       gst_rtsp_status_as_text (GST_RTSP_STS_OK), ctx->request);
2792
2793   gst_rtsp_message_add_header (ctx->response, GST_RTSP_HDR_CONTENT_TYPE,
2794       "application/sdp");
2795
2796   /* content base for some clients that might screw up creating the setup uri */
2797   str = make_base_url (client, ctx->uri, path);
2798   g_free (path);
2799
2800   GST_INFO ("adding content-base: %s", str);
2801   gst_rtsp_message_take_header (ctx->response, GST_RTSP_HDR_CONTENT_BASE, str);
2802
2803   /* add SDP to the response body */
2804   str = gst_sdp_message_as_text (sdp);
2805   gst_rtsp_message_take_body (ctx->response, (guint8 *) str, strlen (str));
2806   gst_sdp_message_free (sdp);
2807
2808   send_message (client, ctx, ctx->response, FALSE);
2809
2810   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_DESCRIBE_REQUEST],
2811       0, ctx);
2812
2813   return TRUE;
2814
2815   /* ERRORS */
2816 sig_failed:
2817   {
2818     GST_ERROR ("client %p: pre signal returned error: %s", client,
2819         gst_rtsp_status_as_text (sig_result));
2820     send_generic_response (client, sig_result, ctx);
2821     return FALSE;
2822   }
2823 no_uri:
2824   {
2825     GST_ERROR ("client %p: no uri", client);
2826     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
2827     return FALSE;
2828   }
2829 no_mount_points:
2830   {
2831     GST_ERROR ("client %p: no mount points configured", client);
2832     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
2833     return FALSE;
2834   }
2835 no_path:
2836   {
2837     GST_ERROR ("client %p: can't find path for url", client);
2838     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
2839     return FALSE;
2840   }
2841 no_media:
2842   {
2843     GST_ERROR ("client %p: no media", client);
2844     g_free (path);
2845     /* error reply is already sent */
2846     return FALSE;
2847   }
2848 unsupported_mode:
2849   {
2850     GST_ERROR ("client %p: media does not support DESCRIBE", client);
2851     send_generic_response (client, GST_RTSP_STS_METHOD_NOT_ALLOWED, ctx);
2852     g_free (path);
2853     g_object_unref (media);
2854     return FALSE;
2855   }
2856 no_sdp:
2857   {
2858     GST_ERROR ("client %p: can't create SDP", client);
2859     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, ctx);
2860     g_free (path);
2861     g_object_unref (media);
2862     return FALSE;
2863   }
2864 }
2865
2866 static gboolean
2867 handle_sdp (GstRTSPClient * client, GstRTSPContext * ctx, GstRTSPMedia * media,
2868     GstSDPMessage * sdp)
2869 {
2870   GstRTSPClientPrivate *priv = client->priv;
2871   GstRTSPThread *thread;
2872
2873   /* create an SDP for the media object */
2874   if (!gst_rtsp_media_handle_sdp (media, sdp))
2875     goto unhandled_sdp;
2876
2877   thread = gst_rtsp_thread_pool_get_thread (priv->thread_pool,
2878       GST_RTSP_THREAD_TYPE_MEDIA, ctx);
2879   if (thread == NULL)
2880     goto no_thread;
2881
2882   /* prepare the media */
2883   if (!gst_rtsp_media_prepare (media, thread))
2884     goto no_prepare;
2885
2886   return TRUE;
2887
2888   /* ERRORS */
2889 unhandled_sdp:
2890   {
2891     GST_ERROR ("client %p: could not handle SDP", client);
2892     return FALSE;
2893   }
2894 no_thread:
2895   {
2896     GST_ERROR ("client %p: can't create thread", client);
2897     return FALSE;
2898   }
2899 no_prepare:
2900   {
2901     GST_ERROR ("client %p: can't prepare media", client);
2902     return FALSE;
2903   }
2904 }
2905
2906 static gboolean
2907 handle_announce_request (GstRTSPClient * client, GstRTSPContext * ctx)
2908 {
2909   GstRTSPClientPrivate *priv = client->priv;
2910   GstRTSPClientClass *klass;
2911   GstSDPResult sres;
2912   GstSDPMessage *sdp;
2913   GstRTSPMedia *media;
2914   gchar *path, *cont = NULL;
2915   guint8 *data;
2916   guint size;
2917   GstRTSPStatusCode sig_result;
2918
2919   klass = GST_RTSP_CLIENT_GET_CLASS (client);
2920
2921   if (!ctx->uri)
2922     goto no_uri;
2923
2924   if (!priv->mount_points)
2925     goto no_mount_points;
2926
2927   /* check if reply is SDP */
2928   gst_rtsp_message_get_header (ctx->request, GST_RTSP_HDR_CONTENT_TYPE, &cont,
2929       0);
2930   /* could not be set but since the request returned OK, we assume it
2931    * was SDP, else check it. */
2932   if (cont) {
2933     if (g_ascii_strcasecmp (cont, "application/sdp") != 0)
2934       goto wrong_content_type;
2935   }
2936
2937   /* get message body and parse as SDP */
2938   gst_rtsp_message_get_body (ctx->request, &data, &size);
2939   if (data == NULL || size == 0)
2940     goto no_message;
2941
2942   GST_DEBUG ("client %p: parse SDP...", client);
2943   gst_sdp_message_new (&sdp);
2944   sres = gst_sdp_message_parse_buffer (data, size, sdp);
2945   if (sres != GST_SDP_OK)
2946     goto sdp_parse_failed;
2947
2948   if (!(path = gst_rtsp_mount_points_make_path (priv->mount_points, ctx->uri)))
2949     goto no_path;
2950
2951   /* find the media object for the uri */
2952   if (!(media = find_media (client, ctx, path, NULL)))
2953     goto no_media;
2954
2955   ctx->media = media;
2956
2957   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_PRE_ANNOUNCE_REQUEST],
2958       0, ctx, &sig_result);
2959   if (sig_result != GST_RTSP_STS_OK) {
2960     goto sig_failed;
2961   }
2962
2963   if (!(gst_rtsp_media_get_transport_mode (media) &
2964           GST_RTSP_TRANSPORT_MODE_RECORD))
2965     goto unsupported_mode;
2966
2967   /* Tell client subclass about the media */
2968   if (!klass->handle_sdp (client, ctx, media, sdp))
2969     goto unhandled_sdp;
2970
2971   /* we suspend after the announce */
2972   gst_rtsp_media_suspend (media);
2973   g_object_unref (media);
2974
2975   gst_rtsp_message_init_response (ctx->response, GST_RTSP_STS_OK,
2976       gst_rtsp_status_as_text (GST_RTSP_STS_OK), ctx->request);
2977
2978   send_message (client, ctx, ctx->response, FALSE);
2979
2980   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_ANNOUNCE_REQUEST],
2981       0, ctx);
2982
2983   gst_sdp_message_free (sdp);
2984   g_free (path);
2985   return TRUE;
2986
2987 no_uri:
2988   {
2989     GST_ERROR ("client %p: no uri", client);
2990     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
2991     return FALSE;
2992   }
2993 no_mount_points:
2994   {
2995     GST_ERROR ("client %p: no mount points configured", client);
2996     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
2997     return FALSE;
2998   }
2999 no_path:
3000   {
3001     GST_ERROR ("client %p: can't find path for url", client);
3002     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
3003     gst_sdp_message_free (sdp);
3004     return FALSE;
3005   }
3006 wrong_content_type:
3007   {
3008     GST_ERROR ("client %p: unknown content type", client);
3009     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
3010     return FALSE;
3011   }
3012 no_message:
3013   {
3014     GST_ERROR ("client %p: can't find SDP message", client);
3015     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
3016     return FALSE;
3017   }
3018 sdp_parse_failed:
3019   {
3020     GST_ERROR ("client %p: failed to parse SDP message", client);
3021     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
3022     gst_sdp_message_free (sdp);
3023     return FALSE;
3024   }
3025 no_media:
3026   {
3027     GST_ERROR ("client %p: no media", client);
3028     g_free (path);
3029     /* error reply is already sent */
3030     gst_sdp_message_free (sdp);
3031     return FALSE;
3032   }
3033 sig_failed:
3034   {
3035     GST_ERROR ("client %p: pre signal returned error: %s", client,
3036         gst_rtsp_status_as_text (sig_result));
3037     send_generic_response (client, sig_result, ctx);
3038     gst_sdp_message_free (sdp);
3039     return FALSE;
3040   }
3041 unsupported_mode:
3042   {
3043     GST_ERROR ("client %p: media does not support ANNOUNCE", client);
3044     send_generic_response (client, GST_RTSP_STS_METHOD_NOT_ALLOWED, ctx);
3045     g_free (path);
3046     g_object_unref (media);
3047     gst_sdp_message_free (sdp);
3048     return FALSE;
3049   }
3050 unhandled_sdp:
3051   {
3052     GST_ERROR ("client %p: can't handle SDP", client);
3053     send_generic_response (client, GST_RTSP_STS_UNSUPPORTED_MEDIA_TYPE, ctx);
3054     g_free (path);
3055     g_object_unref (media);
3056     gst_sdp_message_free (sdp);
3057     return FALSE;
3058   }
3059 }
3060
3061 static gboolean
3062 handle_record_request (GstRTSPClient * client, GstRTSPContext * ctx)
3063 {
3064   GstRTSPSession *session;
3065   GstRTSPClientClass *klass;
3066   GstRTSPSessionMedia *sessmedia;
3067   GstRTSPMedia *media;
3068   GstRTSPUrl *uri;
3069   GstRTSPState rtspstate;
3070   gchar *path;
3071   gint matched;
3072   GstRTSPStatusCode sig_result;
3073   GPtrArray *transports;
3074
3075   if (!(session = ctx->session))
3076     goto no_session;
3077
3078   if (!(uri = ctx->uri))
3079     goto no_uri;
3080
3081   klass = GST_RTSP_CLIENT_GET_CLASS (client);
3082   path = klass->make_path_from_uri (client, uri);
3083
3084   /* get a handle to the configuration of the media in the session */
3085   sessmedia = gst_rtsp_session_get_media (session, path, &matched);
3086   if (!sessmedia)
3087     goto not_found;
3088
3089   if (path[matched] != '\0')
3090     goto no_aggregate;
3091
3092   g_free (path);
3093
3094   ctx->sessmedia = sessmedia;
3095   ctx->media = media = gst_rtsp_session_media_get_media (sessmedia);
3096
3097   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_PRE_RECORD_REQUEST], 0,
3098       ctx, &sig_result);
3099   if (sig_result != GST_RTSP_STS_OK) {
3100     goto sig_failed;
3101   }
3102
3103   if (!(gst_rtsp_media_get_transport_mode (media) &
3104           GST_RTSP_TRANSPORT_MODE_RECORD))
3105     goto unsupported_mode;
3106
3107   /* the session state must be playing or ready */
3108   rtspstate = gst_rtsp_session_media_get_rtsp_state (sessmedia);
3109   if (rtspstate != GST_RTSP_STATE_PLAYING && rtspstate != GST_RTSP_STATE_READY)
3110     goto invalid_state;
3111
3112   /* update the pipeline */
3113   transports = gst_rtsp_session_media_get_transports (sessmedia);
3114   if (!gst_rtsp_media_complete_pipeline (media, transports)) {
3115     g_ptr_array_unref (transports);
3116     goto pipeline_error;
3117   }
3118   g_ptr_array_unref (transports);
3119
3120   /* in record we first unsuspend, media could be suspended from SDP or PAUSED */
3121   if (!gst_rtsp_media_unsuspend (media))
3122     goto unsuspend_failed;
3123
3124   gst_rtsp_message_init_response (ctx->response, GST_RTSP_STS_OK,
3125       gst_rtsp_status_as_text (GST_RTSP_STS_OK), ctx->request);
3126
3127   send_message (client, ctx, ctx->response, FALSE);
3128
3129   /* start playing after sending the response */
3130   gst_rtsp_session_media_set_state (sessmedia, GST_STATE_PLAYING);
3131
3132   gst_rtsp_session_media_set_rtsp_state (sessmedia, GST_RTSP_STATE_PLAYING);
3133
3134   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_RECORD_REQUEST], 0,
3135       ctx);
3136
3137   return TRUE;
3138
3139   /* ERRORS */
3140 no_session:
3141   {
3142     GST_ERROR ("client %p: no session", client);
3143     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
3144     return FALSE;
3145   }
3146 no_uri:
3147   {
3148     GST_ERROR ("client %p: no uri supplied", client);
3149     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
3150     return FALSE;
3151   }
3152 not_found:
3153   {
3154     GST_ERROR ("client %p: media not found", client);
3155     send_generic_response (client, GST_RTSP_STS_NOT_FOUND, ctx);
3156     return FALSE;
3157   }
3158 no_aggregate:
3159   {
3160     GST_ERROR ("client %p: no aggregate path %s", client, path);
3161     send_generic_response (client,
3162         GST_RTSP_STS_ONLY_AGGREGATE_OPERATION_ALLOWED, ctx);
3163     g_free (path);
3164     return FALSE;
3165   }
3166 sig_failed:
3167   {
3168     GST_ERROR ("client %p: pre signal returned error: %s", client,
3169         gst_rtsp_status_as_text (sig_result));
3170     send_generic_response (client, sig_result, ctx);
3171     return FALSE;
3172   }
3173 unsupported_mode:
3174   {
3175     GST_ERROR ("client %p: media does not support RECORD", client);
3176     send_generic_response (client, GST_RTSP_STS_METHOD_NOT_ALLOWED, ctx);
3177     return FALSE;
3178   }
3179 invalid_state:
3180   {
3181     GST_ERROR ("client %p: not PLAYING or READY", client);
3182     send_generic_response (client, GST_RTSP_STS_METHOD_NOT_VALID_IN_THIS_STATE,
3183         ctx);
3184     return FALSE;
3185   }
3186 pipeline_error:
3187   {
3188     GST_ERROR ("client %p: failed to configure the pipeline", client);
3189     send_generic_response (client, GST_RTSP_STS_METHOD_NOT_VALID_IN_THIS_STATE,
3190         ctx);
3191     return FALSE;
3192   }
3193 unsuspend_failed:
3194   {
3195     GST_ERROR ("client %p: unsuspend failed", client);
3196     send_generic_response (client, GST_RTSP_STS_SERVICE_UNAVAILABLE, ctx);
3197     return FALSE;
3198   }
3199 }
3200
3201 static gboolean
3202 handle_options_request (GstRTSPClient * client, GstRTSPContext * ctx,
3203     GstRTSPVersion version)
3204 {
3205   GstRTSPMethod options;
3206   gchar *str;
3207   GstRTSPStatusCode sig_result;
3208
3209   options = GST_RTSP_DESCRIBE |
3210       GST_RTSP_OPTIONS |
3211       GST_RTSP_PAUSE |
3212       GST_RTSP_PLAY |
3213       GST_RTSP_SETUP |
3214       GST_RTSP_GET_PARAMETER | GST_RTSP_SET_PARAMETER | GST_RTSP_TEARDOWN;
3215
3216   if (version < GST_RTSP_VERSION_2_0) {
3217     options |= GST_RTSP_RECORD;
3218     options |= GST_RTSP_ANNOUNCE;
3219   }
3220
3221   str = gst_rtsp_options_as_text (options);
3222
3223   gst_rtsp_message_init_response (ctx->response, GST_RTSP_STS_OK,
3224       gst_rtsp_status_as_text (GST_RTSP_STS_OK), ctx->request);
3225
3226   gst_rtsp_message_add_header (ctx->response, GST_RTSP_HDR_PUBLIC, str);
3227   g_free (str);
3228
3229   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_PRE_OPTIONS_REQUEST], 0,
3230       ctx, &sig_result);
3231   if (sig_result != GST_RTSP_STS_OK) {
3232     goto sig_failed;
3233   }
3234
3235   send_message (client, ctx, ctx->response, FALSE);
3236
3237   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_OPTIONS_REQUEST],
3238       0, ctx);
3239
3240   return TRUE;
3241
3242 /* ERRORS */
3243 sig_failed:
3244   {
3245     GST_ERROR ("client %p: pre signal returned error: %s", client,
3246         gst_rtsp_status_as_text (sig_result));
3247     send_generic_response (client, sig_result, ctx);
3248     gst_rtsp_message_free (ctx->response);
3249     return FALSE;
3250   }
3251 }
3252
3253 /* remove duplicate and trailing '/' */
3254 static void
3255 sanitize_uri (GstRTSPUrl * uri)
3256 {
3257   gint i, len;
3258   gchar *s, *d;
3259   gboolean have_slash, prev_slash;
3260
3261   s = d = uri->abspath;
3262   len = strlen (uri->abspath);
3263
3264   prev_slash = FALSE;
3265
3266   for (i = 0; i < len; i++) {
3267     have_slash = s[i] == '/';
3268     *d = s[i];
3269     if (!have_slash || !prev_slash)
3270       d++;
3271     prev_slash = have_slash;
3272   }
3273   len = d - uri->abspath;
3274   /* don't remove the first slash if that's the only thing left */
3275   if (len > 1 && *(d - 1) == '/')
3276     d--;
3277   *d = '\0';
3278 }
3279
3280 /* is called when the session is removed from its session pool. */
3281 static void
3282 client_session_removed (GstRTSPSessionPool * pool, GstRTSPSession * session,
3283     GstRTSPClient * client)
3284 {
3285   GstRTSPClientPrivate *priv = client->priv;
3286
3287   GST_INFO ("client %p: session %p removed", client, session);
3288
3289   g_mutex_lock (&priv->lock);
3290   if (priv->watch != NULL)
3291     gst_rtsp_watch_set_send_backlog (priv->watch, 0, 0);
3292   client_unwatch_session (client, session, NULL);
3293   if (priv->watch != NULL)
3294     gst_rtsp_watch_set_send_backlog (priv->watch, 0, WATCH_BACKLOG_SIZE);
3295   g_mutex_unlock (&priv->lock);
3296 }
3297
3298 /* Check for Require headers. Returns TRUE if there are no Require headers,
3299  * otherwise lets the application decide which headers are supported.
3300  * By default all headers are unsupported.
3301  * If there are unsupported options, FALSE will be returned together with
3302  * a newly-allocated string of (comma-separated) unsupported options in
3303  * the unsupported_reqs variable.
3304  *
3305  * There may be multiple Require headers, but we must send one single
3306  * Unsupported header with all the unsupported options as response. If
3307  * an incoming Require header contained a comma-separated list of options
3308  * GstRtspConnection will already have split that list up into multiple
3309  * headers.
3310  */
3311 static gboolean
3312 check_request_requirements (GstRTSPContext * ctx, gchar ** unsupported_reqs)
3313 {
3314   GstRTSPResult res;
3315   GPtrArray *arr = NULL;
3316   GstRTSPMessage *msg = ctx->request;
3317   gchar *reqs = NULL;
3318   gint i;
3319   gchar *sig_result = NULL;
3320   gboolean result = TRUE;
3321
3322   i = 0;
3323   do {
3324     res = gst_rtsp_message_get_header (msg, GST_RTSP_HDR_REQUIRE, &reqs, i++);
3325
3326     if (res == GST_RTSP_ENOTIMPL)
3327       break;
3328
3329     if (arr == NULL)
3330       arr = g_ptr_array_new_with_free_func ((GDestroyNotify) g_free);
3331
3332     g_ptr_array_add (arr, g_strdup (reqs));
3333   }
3334   while (TRUE);
3335
3336   /* if we don't have any Require headers at all, all is fine */
3337   if (i == 1)
3338     return TRUE;
3339
3340   /* otherwise we've now processed at all the Require headers */
3341   g_ptr_array_add (arr, NULL);
3342
3343   g_signal_emit (ctx->client,
3344       gst_rtsp_client_signals[SIGNAL_CHECK_REQUIREMENTS], 0, ctx,
3345       (gchar **) arr->pdata, &sig_result);
3346
3347   if (sig_result == NULL) {
3348     /* no supported options, just report all of the required ones as
3349      * unsupported */
3350     *unsupported_reqs = g_strjoinv (", ", (gchar **) arr->pdata);
3351     result = FALSE;
3352     goto done;
3353   }
3354
3355   if (strlen (sig_result) == 0)
3356     g_free (sig_result);
3357   else {
3358     *unsupported_reqs = sig_result;
3359     result = FALSE;
3360   }
3361
3362 done:
3363   g_ptr_array_unref (arr);
3364   return result;
3365 }
3366
3367 static void
3368 handle_request (GstRTSPClient * client, GstRTSPMessage * request)
3369 {
3370   GstRTSPClientPrivate *priv = client->priv;
3371   GstRTSPMethod method;
3372   const gchar *uristr;
3373   GstRTSPUrl *uri = NULL;
3374   GstRTSPVersion version;
3375   GstRTSPResult res;
3376   GstRTSPSession *session = NULL;
3377   GstRTSPContext sctx = { NULL }, *ctx;
3378   GstRTSPMessage response = { 0 };
3379   gchar *unsupported_reqs = NULL;
3380   gchar *sessid = NULL, *pipelined_request_id = NULL;
3381
3382   if (!(ctx = gst_rtsp_context_get_current ())) {
3383     ctx = &sctx;
3384     ctx->auth = priv->auth;
3385     gst_rtsp_context_push_current (ctx);
3386   }
3387
3388   ctx->conn = priv->connection;
3389   ctx->client = client;
3390   ctx->request = request;
3391   ctx->response = &response;
3392
3393   if (gst_debug_category_get_threshold (rtsp_client_debug) >= GST_LEVEL_LOG) {
3394     gst_rtsp_message_dump (request);
3395   }
3396
3397   gst_rtsp_message_parse_request (request, &method, &uristr, &version);
3398
3399   GST_INFO ("client %p: received a request %s %s %s", client,
3400       gst_rtsp_method_as_text (method), uristr,
3401       gst_rtsp_version_as_text (version));
3402
3403   /* we can only handle 1.0 requests */
3404   if (version != GST_RTSP_VERSION_1_0 && version != GST_RTSP_VERSION_2_0)
3405     goto not_supported;
3406
3407   ctx->method = method;
3408
3409   /* we always try to parse the url first */
3410   if (strcmp (uristr, "*") == 0) {
3411     /* special case where we have * as uri, keep uri = NULL */
3412   } else if (gst_rtsp_url_parse (uristr, &uri) != GST_RTSP_OK) {
3413     /* check if the uristr is an absolute path <=> scheme and host information
3414      * is missing */
3415     gchar *scheme;
3416
3417     scheme = g_uri_parse_scheme (uristr);
3418     if (scheme == NULL && g_str_has_prefix (uristr, "/")) {
3419       gchar *absolute_uristr = NULL;
3420
3421       GST_WARNING_OBJECT (client, "request doesn't contain absolute url");
3422       if (priv->server_ip == NULL) {
3423         GST_WARNING_OBJECT (client, "host information missing");
3424         goto bad_request;
3425       }
3426
3427       absolute_uristr =
3428           g_strdup_printf ("rtsp://%s%s", priv->server_ip, uristr);
3429
3430       GST_DEBUG_OBJECT (client, "absolute url: %s", absolute_uristr);
3431       if (gst_rtsp_url_parse (absolute_uristr, &uri) != GST_RTSP_OK) {
3432         g_free (absolute_uristr);
3433         goto bad_request;
3434       }
3435       g_free (absolute_uristr);
3436     } else {
3437       g_free (scheme);
3438       goto bad_request;
3439     }
3440   }
3441
3442   /* get the session if there is any */
3443   res = gst_rtsp_message_get_header (request, GST_RTSP_HDR_PIPELINED_REQUESTS,
3444       &pipelined_request_id, 0);
3445   if (res == GST_RTSP_OK) {
3446     sessid = g_hash_table_lookup (client->priv->pipelined_requests,
3447         pipelined_request_id);
3448
3449     if (!sessid)
3450       res = GST_RTSP_ERROR;
3451   }
3452
3453   if (res != GST_RTSP_OK)
3454     res =
3455         gst_rtsp_message_get_header (request, GST_RTSP_HDR_SESSION, &sessid, 0);
3456
3457   if (res == GST_RTSP_OK) {
3458     if (priv->session_pool == NULL)
3459       goto no_pool;
3460
3461     /* we had a session in the request, find it again */
3462     if (!(session = gst_rtsp_session_pool_find (priv->session_pool, sessid)))
3463       goto session_not_found;
3464
3465     /* we add the session to the client list of watched sessions. When a session
3466      * disappears because it times out, we will be notified. If all sessions are
3467      * gone, we will close the connection */
3468     client_watch_session (client, session);
3469   }
3470
3471   /* sanitize the uri */
3472   if (uri)
3473     sanitize_uri (uri);
3474   ctx->uri = uri;
3475   ctx->session = session;
3476
3477   if (!gst_rtsp_auth_check (GST_RTSP_AUTH_CHECK_URL))
3478     goto not_authorized;
3479
3480   /* handle any 'Require' headers */
3481   if (!check_request_requirements (ctx, &unsupported_reqs))
3482     goto unsupported_requirement;
3483
3484   /* the backlog must be unlimited while processing requests.
3485    * the causes of this are two cases of deadlocks while streaming over TCP:
3486    *
3487    * 1. consider the scenario where the media pipeline's streaming thread
3488    * is blocking in the appsink (taking the appsink's preroll lock) because
3489    * the backlog is full. when a PAUSE request is received by the RTSP
3490    * client thread then the the state of the session media ought to change
3491    * to PAUSED. while most elements in the pipeline can change state this
3492    * can never happen for the appsink since its preroll lock is taken by
3493    * another thread.
3494    *
3495    * 2. consider the scenario where the media pipeline's streaming thread
3496    * is blocking in the appsink new_sample callback (taking the send lock
3497    * in RTSP client) because the backlog is full. when e.g. a GET request
3498    * is received by the RTSP client thread then a response ought to be sent
3499    * but this can never happen since it requires taking the send lock
3500    * already taken by another thread.
3501    *
3502    * the reason that the backlog is never emptied is that the source used
3503    * for dequeing messages from the backlog is never dispatched because it
3504    * is attached to the same mainloop as the source receving RTSP requests and
3505    * therefore run by the RTSP client thread which is alreayd blocking.
3506    *
3507    * without significant changes the easiest way to cope with this is to
3508    * not block indefinitely when the backlog is full, but rather let the
3509    * backlog grow in size. this in effect means that there can not be any
3510    * upper boundary on its size.
3511    */
3512   if (priv->watch != NULL)
3513     gst_rtsp_watch_set_send_backlog (priv->watch, 0, 0);
3514
3515   /* now see what is asked and dispatch to a dedicated handler */
3516   switch (method) {
3517     case GST_RTSP_OPTIONS:
3518       priv->version = version;
3519       handle_options_request (client, ctx, version);
3520       break;
3521     case GST_RTSP_DESCRIBE:
3522       handle_describe_request (client, ctx);
3523       break;
3524     case GST_RTSP_SETUP:
3525       handle_setup_request (client, ctx);
3526       break;
3527     case GST_RTSP_PLAY:
3528       handle_play_request (client, ctx);
3529       break;
3530     case GST_RTSP_PAUSE:
3531       handle_pause_request (client, ctx);
3532       break;
3533     case GST_RTSP_TEARDOWN:
3534       handle_teardown_request (client, ctx);
3535       break;
3536     case GST_RTSP_SET_PARAMETER:
3537       handle_set_param_request (client, ctx);
3538       break;
3539     case GST_RTSP_GET_PARAMETER:
3540       handle_get_param_request (client, ctx);
3541       break;
3542     case GST_RTSP_ANNOUNCE:
3543       if (version >= GST_RTSP_VERSION_2_0)
3544         goto invalid_command_for_version;
3545       handle_announce_request (client, ctx);
3546       break;
3547     case GST_RTSP_RECORD:
3548       if (version >= GST_RTSP_VERSION_2_0)
3549         goto invalid_command_for_version;
3550       handle_record_request (client, ctx);
3551       break;
3552     case GST_RTSP_REDIRECT:
3553       if (priv->watch != NULL)
3554         gst_rtsp_watch_set_send_backlog (priv->watch, 0, WATCH_BACKLOG_SIZE);
3555       goto not_implemented;
3556     case GST_RTSP_INVALID:
3557     default:
3558       if (priv->watch != NULL)
3559         gst_rtsp_watch_set_send_backlog (priv->watch, 0, WATCH_BACKLOG_SIZE);
3560       goto bad_request;
3561   }
3562
3563   if (priv->watch != NULL)
3564     gst_rtsp_watch_set_send_backlog (priv->watch, 0, WATCH_BACKLOG_SIZE);
3565
3566 done:
3567   if (ctx == &sctx)
3568     gst_rtsp_context_pop_current (ctx);
3569   if (session)
3570     g_object_unref (session);
3571   if (uri)
3572     gst_rtsp_url_free (uri);
3573   return;
3574
3575   /* ERRORS */
3576 not_supported:
3577   {
3578     GST_ERROR ("client %p: version %d not supported", client, version);
3579     send_generic_response (client, GST_RTSP_STS_RTSP_VERSION_NOT_SUPPORTED,
3580         ctx);
3581     goto done;
3582   }
3583 invalid_command_for_version:
3584   {
3585     if (priv->watch != NULL)
3586       gst_rtsp_watch_set_send_backlog (priv->watch, 0, WATCH_BACKLOG_SIZE);
3587
3588     GST_ERROR ("client %p: invalid command for version", client);
3589     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
3590     goto done;
3591   }
3592 bad_request:
3593   {
3594     GST_ERROR ("client %p: bad request", client);
3595     send_generic_response (client, GST_RTSP_STS_BAD_REQUEST, ctx);
3596     goto done;
3597   }
3598 no_pool:
3599   {
3600     GST_ERROR ("client %p: no pool configured", client);
3601     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
3602     goto done;
3603   }
3604 session_not_found:
3605   {
3606     GST_ERROR ("client %p: session not found", client);
3607     send_generic_response (client, GST_RTSP_STS_SESSION_NOT_FOUND, ctx);
3608     goto done;
3609   }
3610 not_authorized:
3611   {
3612     GST_ERROR ("client %p: not allowed", client);
3613     /* error reply is already sent */
3614     goto done;
3615   }
3616 unsupported_requirement:
3617   {
3618     GST_ERROR ("client %p: Required option is not supported (%s)", client,
3619         unsupported_reqs);
3620     send_option_not_supported_response (client, ctx, unsupported_reqs);
3621     g_free (unsupported_reqs);
3622     goto done;
3623   }
3624 not_implemented:
3625   {
3626     GST_ERROR ("client %p: method %d not implemented", client, method);
3627     send_generic_response (client, GST_RTSP_STS_NOT_IMPLEMENTED, ctx);
3628     goto done;
3629   }
3630 }
3631
3632
3633 static void
3634 handle_response (GstRTSPClient * client, GstRTSPMessage * response)
3635 {
3636   GstRTSPClientPrivate *priv = client->priv;
3637   GstRTSPResult res;
3638   GstRTSPSession *session = NULL;
3639   GstRTSPContext sctx = { NULL }, *ctx;
3640   gchar *sessid;
3641
3642   if (!(ctx = gst_rtsp_context_get_current ())) {
3643     ctx = &sctx;
3644     ctx->auth = priv->auth;
3645     gst_rtsp_context_push_current (ctx);
3646   }
3647
3648   ctx->conn = priv->connection;
3649   ctx->client = client;
3650   ctx->request = NULL;
3651   ctx->uri = NULL;
3652   ctx->method = GST_RTSP_INVALID;
3653   ctx->response = response;
3654
3655   if (gst_debug_category_get_threshold (rtsp_client_debug) >= GST_LEVEL_LOG) {
3656     gst_rtsp_message_dump (response);
3657   }
3658
3659   GST_INFO ("client %p: received a response", client);
3660
3661   /* get the session if there is any */
3662   res =
3663       gst_rtsp_message_get_header (response, GST_RTSP_HDR_SESSION, &sessid, 0);
3664   if (res == GST_RTSP_OK) {
3665     if (priv->session_pool == NULL)
3666       goto no_pool;
3667
3668     /* we had a session in the request, find it again */
3669     if (!(session = gst_rtsp_session_pool_find (priv->session_pool, sessid)))
3670       goto session_not_found;
3671
3672     /* we add the session to the client list of watched sessions. When a session
3673      * disappears because it times out, we will be notified. If all sessions are
3674      * gone, we will close the connection */
3675     client_watch_session (client, session);
3676   }
3677
3678   ctx->session = session;
3679
3680   g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_HANDLE_RESPONSE],
3681       0, ctx);
3682
3683 done:
3684   if (ctx == &sctx)
3685     gst_rtsp_context_pop_current (ctx);
3686   if (session)
3687     g_object_unref (session);
3688   return;
3689
3690 no_pool:
3691   {
3692     GST_ERROR ("client %p: no pool configured", client);
3693     goto done;
3694   }
3695 session_not_found:
3696   {
3697     GST_ERROR ("client %p: session not found", client);
3698     goto done;
3699   }
3700 }
3701
3702 static void
3703 handle_data (GstRTSPClient * client, GstRTSPMessage * message)
3704 {
3705   GstRTSPClientPrivate *priv = client->priv;
3706   GstRTSPResult res;
3707   guint8 channel;
3708   guint8 *data;
3709   guint size;
3710   GstBuffer *buffer;
3711   GstRTSPStreamTransport *trans;
3712
3713   /* find the stream for this message */
3714   res = gst_rtsp_message_parse_data (message, &channel);
3715   if (res != GST_RTSP_OK)
3716     return;
3717
3718   gst_rtsp_message_get_body (message, &data, &size);
3719   if (size < 2)
3720     goto invalid_length;
3721
3722   gst_rtsp_message_steal_body (message, &data, &size);
3723
3724   /* Strip trailing \0 (which GstRTSPConnection adds) */
3725   --size;
3726
3727   buffer = gst_buffer_new_wrapped (data, size);
3728
3729   trans =
3730       g_hash_table_lookup (priv->transports, GINT_TO_POINTER ((gint) channel));
3731   if (trans) {
3732     /* dispatch to the stream based on the channel number */
3733     GST_LOG_OBJECT (client, "%u bytes of data on channel %u", size, channel);
3734     gst_rtsp_stream_transport_recv_data (trans, channel, buffer);
3735   } else {
3736     GST_DEBUG_OBJECT (client, "received %u bytes of data for "
3737         "unknown channel %u", size, channel);
3738     gst_buffer_unref (buffer);
3739   }
3740
3741   return;
3742
3743 /* ERRORS */
3744 invalid_length:
3745   {
3746     GST_DEBUG ("client %p: Short message received, ignoring", client);
3747     return;
3748   }
3749 }
3750
3751 /**
3752  * gst_rtsp_client_set_session_pool:
3753  * @client: a #GstRTSPClient
3754  * @pool: (transfer none): a #GstRTSPSessionPool
3755  *
3756  * Set @pool as the sessionpool for @client which it will use to find
3757  * or allocate sessions. the sessionpool is usually inherited from the server
3758  * that created the client but can be overridden later.
3759  */
3760 void
3761 gst_rtsp_client_set_session_pool (GstRTSPClient * client,
3762     GstRTSPSessionPool * pool)
3763 {
3764   GstRTSPSessionPool *old;
3765   GstRTSPClientPrivate *priv;
3766
3767   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
3768
3769   priv = client->priv;
3770
3771   if (pool)
3772     g_object_ref (pool);
3773
3774   g_mutex_lock (&priv->lock);
3775   old = priv->session_pool;
3776   priv->session_pool = pool;
3777
3778   if (priv->session_removed_id) {
3779     g_signal_handler_disconnect (old, priv->session_removed_id);
3780     priv->session_removed_id = 0;
3781   }
3782   g_mutex_unlock (&priv->lock);
3783
3784   /* FIXME, should remove all sessions from the old pool for this client */
3785   if (old)
3786     g_object_unref (old);
3787 }
3788
3789 /**
3790  * gst_rtsp_client_get_session_pool:
3791  * @client: a #GstRTSPClient
3792  *
3793  * Get the #GstRTSPSessionPool object that @client uses to manage its sessions.
3794  *
3795  * Returns: (transfer full): a #GstRTSPSessionPool, unref after usage.
3796  */
3797 GstRTSPSessionPool *
3798 gst_rtsp_client_get_session_pool (GstRTSPClient * client)
3799 {
3800   GstRTSPClientPrivate *priv;
3801   GstRTSPSessionPool *result;
3802
3803   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
3804
3805   priv = client->priv;
3806
3807   g_mutex_lock (&priv->lock);
3808   if ((result = priv->session_pool))
3809     g_object_ref (result);
3810   g_mutex_unlock (&priv->lock);
3811
3812   return result;
3813 }
3814
3815 /**
3816  * gst_rtsp_client_set_mount_points:
3817  * @client: a #GstRTSPClient
3818  * @mounts: (transfer none): a #GstRTSPMountPoints
3819  *
3820  * Set @mounts as the mount points for @client which it will use to map urls
3821  * to media streams. These mount points are usually inherited from the server that
3822  * created the client but can be overriden later.
3823  */
3824 void
3825 gst_rtsp_client_set_mount_points (GstRTSPClient * client,
3826     GstRTSPMountPoints * mounts)
3827 {
3828   GstRTSPClientPrivate *priv;
3829   GstRTSPMountPoints *old;
3830
3831   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
3832
3833   priv = client->priv;
3834
3835   if (mounts)
3836     g_object_ref (mounts);
3837
3838   g_mutex_lock (&priv->lock);
3839   old = priv->mount_points;
3840   priv->mount_points = mounts;
3841   g_mutex_unlock (&priv->lock);
3842
3843   if (old)
3844     g_object_unref (old);
3845 }
3846
3847 /**
3848  * gst_rtsp_client_get_mount_points:
3849  * @client: a #GstRTSPClient
3850  *
3851  * Get the #GstRTSPMountPoints object that @client uses to manage its sessions.
3852  *
3853  * Returns: (transfer full): a #GstRTSPMountPoints, unref after usage.
3854  */
3855 GstRTSPMountPoints *
3856 gst_rtsp_client_get_mount_points (GstRTSPClient * client)
3857 {
3858   GstRTSPClientPrivate *priv;
3859   GstRTSPMountPoints *result;
3860
3861   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
3862
3863   priv = client->priv;
3864
3865   g_mutex_lock (&priv->lock);
3866   if ((result = priv->mount_points))
3867     g_object_ref (result);
3868   g_mutex_unlock (&priv->lock);
3869
3870   return result;
3871 }
3872
3873 /**
3874  * gst_rtsp_client_set_auth:
3875  * @client: a #GstRTSPClient
3876  * @auth: (transfer none): a #GstRTSPAuth
3877  *
3878  * configure @auth to be used as the authentication manager of @client.
3879  */
3880 void
3881 gst_rtsp_client_set_auth (GstRTSPClient * client, GstRTSPAuth * auth)
3882 {
3883   GstRTSPClientPrivate *priv;
3884   GstRTSPAuth *old;
3885
3886   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
3887
3888   priv = client->priv;
3889
3890   if (auth)
3891     g_object_ref (auth);
3892
3893   g_mutex_lock (&priv->lock);
3894   old = priv->auth;
3895   priv->auth = auth;
3896   g_mutex_unlock (&priv->lock);
3897
3898   if (old)
3899     g_object_unref (old);
3900 }
3901
3902
3903 /**
3904  * gst_rtsp_client_get_auth:
3905  * @client: a #GstRTSPClient
3906  *
3907  * Get the #GstRTSPAuth used as the authentication manager of @client.
3908  *
3909  * Returns: (transfer full): the #GstRTSPAuth of @client. g_object_unref() after
3910  * usage.
3911  */
3912 GstRTSPAuth *
3913 gst_rtsp_client_get_auth (GstRTSPClient * client)
3914 {
3915   GstRTSPClientPrivate *priv;
3916   GstRTSPAuth *result;
3917
3918   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
3919
3920   priv = client->priv;
3921
3922   g_mutex_lock (&priv->lock);
3923   if ((result = priv->auth))
3924     g_object_ref (result);
3925   g_mutex_unlock (&priv->lock);
3926
3927   return result;
3928 }
3929
3930 /**
3931  * gst_rtsp_client_set_thread_pool:
3932  * @client: a #GstRTSPClient
3933  * @pool: (transfer none): a #GstRTSPThreadPool
3934  *
3935  * configure @pool to be used as the thread pool of @client.
3936  */
3937 void
3938 gst_rtsp_client_set_thread_pool (GstRTSPClient * client,
3939     GstRTSPThreadPool * pool)
3940 {
3941   GstRTSPClientPrivate *priv;
3942   GstRTSPThreadPool *old;
3943
3944   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
3945
3946   priv = client->priv;
3947
3948   if (pool)
3949     g_object_ref (pool);
3950
3951   g_mutex_lock (&priv->lock);
3952   old = priv->thread_pool;
3953   priv->thread_pool = pool;
3954   g_mutex_unlock (&priv->lock);
3955
3956   if (old)
3957     g_object_unref (old);
3958 }
3959
3960 /**
3961  * gst_rtsp_client_get_thread_pool:
3962  * @client: a #GstRTSPClient
3963  *
3964  * Get the #GstRTSPThreadPool used as the thread pool of @client.
3965  *
3966  * Returns: (transfer full): the #GstRTSPThreadPool of @client. g_object_unref() after
3967  * usage.
3968  */
3969 GstRTSPThreadPool *
3970 gst_rtsp_client_get_thread_pool (GstRTSPClient * client)
3971 {
3972   GstRTSPClientPrivate *priv;
3973   GstRTSPThreadPool *result;
3974
3975   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
3976
3977   priv = client->priv;
3978
3979   g_mutex_lock (&priv->lock);
3980   if ((result = priv->thread_pool))
3981     g_object_ref (result);
3982   g_mutex_unlock (&priv->lock);
3983
3984   return result;
3985 }
3986
3987 /**
3988  * gst_rtsp_client_set_connection:
3989  * @client: a #GstRTSPClient
3990  * @conn: (transfer full): a #GstRTSPConnection
3991  *
3992  * Set the #GstRTSPConnection of @client. This function takes ownership of
3993  * @conn.
3994  *
3995  * Returns: %TRUE on success.
3996  */
3997 gboolean
3998 gst_rtsp_client_set_connection (GstRTSPClient * client,
3999     GstRTSPConnection * conn)
4000 {
4001   GstRTSPClientPrivate *priv;
4002   GSocket *read_socket;
4003   GSocketAddress *address;
4004   GstRTSPUrl *url;
4005   GError *error = NULL;
4006
4007   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), FALSE);
4008   g_return_val_if_fail (conn != NULL, FALSE);
4009
4010   priv = client->priv;
4011
4012   read_socket = gst_rtsp_connection_get_read_socket (conn);
4013
4014   if (!(address = g_socket_get_local_address (read_socket, &error)))
4015     goto no_address;
4016
4017   g_free (priv->server_ip);
4018   /* keep the original ip that the client connected to */
4019   if (G_IS_INET_SOCKET_ADDRESS (address)) {
4020     GInetAddress *iaddr;
4021
4022     iaddr = g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (address));
4023
4024     /* socket might be ipv6 but adress still ipv4 */
4025     priv->is_ipv6 = g_inet_address_get_family (iaddr) == G_SOCKET_FAMILY_IPV6;
4026     priv->server_ip = g_inet_address_to_string (iaddr);
4027     g_object_unref (address);
4028   } else {
4029     priv->is_ipv6 = g_socket_get_family (read_socket) == G_SOCKET_FAMILY_IPV6;
4030     priv->server_ip = g_strdup ("unknown");
4031   }
4032
4033   GST_INFO ("client %p connected to server ip %s, ipv6 = %d", client,
4034       priv->server_ip, priv->is_ipv6);
4035
4036   url = gst_rtsp_connection_get_url (conn);
4037   GST_INFO ("added new client %p ip %s:%d", client, url->host, url->port);
4038
4039   priv->connection = conn;
4040
4041   return TRUE;
4042
4043   /* ERRORS */
4044 no_address:
4045   {
4046     GST_ERROR ("could not get local address %s", error->message);
4047     g_error_free (error);
4048     return FALSE;
4049   }
4050 }
4051
4052 /**
4053  * gst_rtsp_client_get_connection:
4054  * @client: a #GstRTSPClient
4055  *
4056  * Get the #GstRTSPConnection of @client.
4057  *
4058  * Returns: (transfer none): the #GstRTSPConnection of @client.
4059  * The connection object returned remains valid until the client is freed.
4060  */
4061 GstRTSPConnection *
4062 gst_rtsp_client_get_connection (GstRTSPClient * client)
4063 {
4064   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
4065
4066   return client->priv->connection;
4067 }
4068
4069 /**
4070  * gst_rtsp_client_set_send_func:
4071  * @client: a #GstRTSPClient
4072  * @func: (scope notified): a #GstRTSPClientSendFunc
4073  * @user_data: (closure): user data passed to @func
4074  * @notify: (allow-none): called when @user_data is no longer in use
4075  *
4076  * Set @func as the callback that will be called when a new message needs to be
4077  * sent to the client. @user_data is passed to @func and @notify is called when
4078  * @user_data is no longer in use.
4079  *
4080  * By default, the client will send the messages on the #GstRTSPConnection that
4081  * was configured with gst_rtsp_client_attach() was called.
4082  */
4083 void
4084 gst_rtsp_client_set_send_func (GstRTSPClient * client,
4085     GstRTSPClientSendFunc func, gpointer user_data, GDestroyNotify notify)
4086 {
4087   GstRTSPClientPrivate *priv;
4088   GDestroyNotify old_notify;
4089   gpointer old_data;
4090
4091   g_return_if_fail (GST_IS_RTSP_CLIENT (client));
4092
4093   priv = client->priv;
4094
4095   g_mutex_lock (&priv->send_lock);
4096   priv->send_func = func;
4097   old_notify = priv->send_notify;
4098   old_data = priv->send_data;
4099   priv->send_notify = notify;
4100   priv->send_data = user_data;
4101   g_mutex_unlock (&priv->send_lock);
4102
4103   if (old_notify)
4104     old_notify (old_data);
4105 }
4106
4107 /**
4108  * gst_rtsp_client_handle_message:
4109  * @client: a #GstRTSPClient
4110  * @message: (transfer none): an #GstRTSPMessage
4111  *
4112  * Let the client handle @message.
4113  *
4114  * Returns: a #GstRTSPResult.
4115  */
4116 GstRTSPResult
4117 gst_rtsp_client_handle_message (GstRTSPClient * client,
4118     GstRTSPMessage * message)
4119 {
4120   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), GST_RTSP_EINVAL);
4121   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
4122
4123   switch (message->type) {
4124     case GST_RTSP_MESSAGE_REQUEST:
4125       handle_request (client, message);
4126       break;
4127     case GST_RTSP_MESSAGE_RESPONSE:
4128       handle_response (client, message);
4129       break;
4130     case GST_RTSP_MESSAGE_DATA:
4131       handle_data (client, message);
4132       break;
4133     default:
4134       break;
4135   }
4136   return GST_RTSP_OK;
4137 }
4138
4139 /**
4140  * gst_rtsp_client_send_message:
4141  * @client: a #GstRTSPClient
4142  * @session: (allow-none) (transfer none): a #GstRTSPSession to send
4143  *   the message to or %NULL
4144  * @message: (transfer none): The #GstRTSPMessage to send
4145  *
4146  * Send a message message to the remote end. @message must be a
4147  * #GST_RTSP_MESSAGE_REQUEST or a #GST_RTSP_MESSAGE_RESPONSE.
4148  */
4149 GstRTSPResult
4150 gst_rtsp_client_send_message (GstRTSPClient * client, GstRTSPSession * session,
4151     GstRTSPMessage * message)
4152 {
4153   GstRTSPContext sctx = { NULL }
4154   , *ctx;
4155   GstRTSPClientPrivate *priv;
4156
4157   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), GST_RTSP_EINVAL);
4158   g_return_val_if_fail (message != NULL, GST_RTSP_EINVAL);
4159   g_return_val_if_fail (message->type == GST_RTSP_MESSAGE_REQUEST ||
4160       message->type == GST_RTSP_MESSAGE_RESPONSE, GST_RTSP_EINVAL);
4161
4162   priv = client->priv;
4163
4164   if (!(ctx = gst_rtsp_context_get_current ())) {
4165     ctx = &sctx;
4166     ctx->auth = priv->auth;
4167     gst_rtsp_context_push_current (ctx);
4168   }
4169
4170   ctx->conn = priv->connection;
4171   ctx->client = client;
4172   ctx->session = session;
4173
4174   send_message (client, ctx, message, FALSE);
4175
4176   if (ctx == &sctx)
4177     gst_rtsp_context_pop_current (ctx);
4178
4179   return GST_RTSP_OK;
4180 }
4181
4182 static gboolean
4183 do_send_message (GstRTSPClient * client, GstRTSPMessage * message,
4184     gboolean close, gpointer user_data)
4185 {
4186   GstRTSPClientPrivate *priv = client->priv;
4187   GstRTSPResult ret;
4188   GTimeVal time;
4189
4190   time.tv_sec = 1;
4191   time.tv_usec = 0;
4192
4193   do {
4194     /* send the response and store the seq number so we can wait until it's
4195      * written to the client to close the connection */
4196     ret =
4197         gst_rtsp_watch_send_message (priv->watch, message,
4198         close ? &priv->close_seq : NULL);
4199     if (ret == GST_RTSP_OK)
4200       break;
4201
4202     if (ret != GST_RTSP_ENOMEM)
4203       goto error;
4204
4205     /* drop backlog */
4206     if (priv->drop_backlog)
4207       break;
4208
4209     /* queue was full, wait for more space */
4210     GST_DEBUG_OBJECT (client, "waiting for backlog");
4211     ret = gst_rtsp_watch_wait_backlog (priv->watch, &time);
4212     GST_DEBUG_OBJECT (client, "Resend due to backlog full");
4213   } while (ret != GST_RTSP_EINTR);
4214
4215   return ret == GST_RTSP_OK;
4216
4217   /* ERRORS */
4218 error:
4219   {
4220     GST_DEBUG_OBJECT (client, "got error %d", ret);
4221     return ret == GST_RTSP_OK;
4222   }
4223 }
4224
4225 static GstRTSPResult
4226 message_received (GstRTSPWatch * watch, GstRTSPMessage * message,
4227     gpointer user_data)
4228 {
4229   return gst_rtsp_client_handle_message (GST_RTSP_CLIENT (user_data), message);
4230 }
4231
4232 static GstRTSPResult
4233 message_sent (GstRTSPWatch * watch, guint cseq, gpointer user_data)
4234 {
4235   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
4236   GstRTSPClientPrivate *priv = client->priv;
4237
4238   if (priv->close_seq && priv->close_seq == cseq) {
4239     GST_INFO ("client %p: send close message", client);
4240     priv->close_seq = 0;
4241     gst_rtsp_client_close (client);
4242   }
4243
4244   return GST_RTSP_OK;
4245 }
4246
4247 static GstRTSPResult
4248 closed (GstRTSPWatch * watch, gpointer user_data)
4249 {
4250   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
4251   GstRTSPClientPrivate *priv = client->priv;
4252   const gchar *tunnelid;
4253
4254   GST_INFO ("client %p: connection closed", client);
4255
4256   if ((tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection))) {
4257     g_mutex_lock (&tunnels_lock);
4258     /* remove from tunnelids */
4259     g_hash_table_remove (tunnels, tunnelid);
4260     g_mutex_unlock (&tunnels_lock);
4261   }
4262
4263   gst_rtsp_watch_set_flushing (watch, TRUE);
4264   g_mutex_lock (&priv->watch_lock);
4265   gst_rtsp_client_set_send_func (client, NULL, NULL, NULL);
4266   g_mutex_unlock (&priv->watch_lock);
4267
4268   return GST_RTSP_OK;
4269 }
4270
4271 static GstRTSPResult
4272 error (GstRTSPWatch * watch, GstRTSPResult result, gpointer user_data)
4273 {
4274   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
4275   gchar *str;
4276
4277   str = gst_rtsp_strresult (result);
4278   GST_INFO ("client %p: received an error %s", client, str);
4279   g_free (str);
4280
4281   return GST_RTSP_OK;
4282 }
4283
4284 static GstRTSPResult
4285 error_full (GstRTSPWatch * watch, GstRTSPResult result,
4286     GstRTSPMessage * message, guint id, gpointer user_data)
4287 {
4288   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
4289   gchar *str;
4290
4291   str = gst_rtsp_strresult (result);
4292   GST_INFO
4293       ("client %p: error when handling message %p with id %d: %s",
4294       client, message, id, str);
4295   g_free (str);
4296
4297   return GST_RTSP_OK;
4298 }
4299
4300 static gboolean
4301 remember_tunnel (GstRTSPClient * client)
4302 {
4303   GstRTSPClientPrivate *priv = client->priv;
4304   const gchar *tunnelid;
4305
4306   /* store client in the pending tunnels */
4307   tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection);
4308   if (tunnelid == NULL)
4309     goto no_tunnelid;
4310
4311   GST_INFO ("client %p: inserting tunnel session %s", client, tunnelid);
4312
4313   /* we can't have two clients connecting with the same tunnelid */
4314   g_mutex_lock (&tunnels_lock);
4315   if (g_hash_table_lookup (tunnels, tunnelid))
4316     goto tunnel_existed;
4317
4318   g_hash_table_insert (tunnels, g_strdup (tunnelid), g_object_ref (client));
4319   g_mutex_unlock (&tunnels_lock);
4320
4321   return TRUE;
4322
4323   /* ERRORS */
4324 no_tunnelid:
4325   {
4326     GST_ERROR ("client %p: no tunnelid provided", client);
4327     return FALSE;
4328   }
4329 tunnel_existed:
4330   {
4331     g_mutex_unlock (&tunnels_lock);
4332     GST_ERROR ("client %p: tunnel session %s already existed", client,
4333         tunnelid);
4334     return FALSE;
4335   }
4336 }
4337
4338 static GstRTSPResult
4339 tunnel_lost (GstRTSPWatch * watch, gpointer user_data)
4340 {
4341   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
4342   GstRTSPClientPrivate *priv = client->priv;
4343
4344   GST_WARNING ("client %p: tunnel lost (connection %p)", client,
4345       priv->connection);
4346
4347   /* ignore error, it'll only be a problem when the client does a POST again */
4348   remember_tunnel (client);
4349
4350   return GST_RTSP_OK;
4351 }
4352
4353 static gboolean
4354 handle_tunnel (GstRTSPClient * client)
4355 {
4356   GstRTSPClientPrivate *priv = client->priv;
4357   GstRTSPClient *oclient;
4358   GstRTSPClientPrivate *opriv;
4359   const gchar *tunnelid;
4360
4361   tunnelid = gst_rtsp_connection_get_tunnelid (priv->connection);
4362   if (tunnelid == NULL)
4363     goto no_tunnelid;
4364
4365   /* check for previous tunnel */
4366   g_mutex_lock (&tunnels_lock);
4367   oclient = g_hash_table_lookup (tunnels, tunnelid);
4368
4369   if (oclient == NULL) {
4370     /* no previous tunnel, remember tunnel */
4371     g_hash_table_insert (tunnels, g_strdup (tunnelid), g_object_ref (client));
4372     g_mutex_unlock (&tunnels_lock);
4373
4374     GST_INFO ("client %p: no previous tunnel found, remembering tunnel (%p)",
4375         client, priv->connection);
4376   } else {
4377     /* merge both tunnels into the first client */
4378     /* remove the old client from the table. ref before because removing it will
4379      * remove the ref to it. */
4380     g_object_ref (oclient);
4381     g_hash_table_remove (tunnels, tunnelid);
4382     g_mutex_unlock (&tunnels_lock);
4383
4384     opriv = oclient->priv;
4385
4386     g_mutex_lock (&opriv->watch_lock);
4387     if (opriv->watch == NULL)
4388       goto tunnel_closed;
4389
4390     GST_INFO ("client %p: found previous tunnel %p (old %p, new %p)", client,
4391         oclient, opriv->connection, priv->connection);
4392
4393     gst_rtsp_connection_do_tunnel (opriv->connection, priv->connection);
4394     gst_rtsp_watch_reset (priv->watch);
4395     gst_rtsp_watch_reset (opriv->watch);
4396     g_mutex_unlock (&opriv->watch_lock);
4397     g_object_unref (oclient);
4398
4399     /* the old client owns the tunnel now, the new one will be freed */
4400     g_source_destroy ((GSource *) priv->watch);
4401     priv->watch = NULL;
4402     gst_rtsp_client_set_send_func (client, NULL, NULL, NULL);
4403   }
4404
4405   return TRUE;
4406
4407   /* ERRORS */
4408 no_tunnelid:
4409   {
4410     GST_ERROR ("client %p: no tunnelid provided", client);
4411     return FALSE;
4412   }
4413 tunnel_closed:
4414   {
4415     GST_ERROR ("client %p: tunnel session %s was closed", client, tunnelid);
4416     g_mutex_unlock (&opriv->watch_lock);
4417     g_object_unref (oclient);
4418     return FALSE;
4419   }
4420 }
4421
4422 static GstRTSPStatusCode
4423 tunnel_get (GstRTSPWatch * watch, gpointer user_data)
4424 {
4425   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
4426
4427   GST_INFO ("client %p: tunnel get (connection %p)", client,
4428       client->priv->connection);
4429
4430   if (!handle_tunnel (client)) {
4431     return GST_RTSP_STS_SERVICE_UNAVAILABLE;
4432   }
4433
4434   return GST_RTSP_STS_OK;
4435 }
4436
4437 static GstRTSPResult
4438 tunnel_post (GstRTSPWatch * watch, gpointer user_data)
4439 {
4440   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
4441
4442   GST_INFO ("client %p: tunnel post (connection %p)", client,
4443       client->priv->connection);
4444
4445   if (!handle_tunnel (client)) {
4446     return GST_RTSP_ERROR;
4447   }
4448
4449   return GST_RTSP_OK;
4450 }
4451
4452 static GstRTSPResult
4453 tunnel_http_response (GstRTSPWatch * watch, GstRTSPMessage * request,
4454     GstRTSPMessage * response, gpointer user_data)
4455 {
4456   GstRTSPClientClass *klass;
4457
4458   GstRTSPClient *client = GST_RTSP_CLIENT (user_data);
4459   klass = GST_RTSP_CLIENT_GET_CLASS (client);
4460
4461   if (klass->tunnel_http_response) {
4462     klass->tunnel_http_response (client, request, response);
4463   }
4464
4465   return GST_RTSP_OK;
4466 }
4467
4468 static GstRTSPWatchFuncs watch_funcs = {
4469   message_received,
4470   message_sent,
4471   closed,
4472   error,
4473   tunnel_get,
4474   tunnel_post,
4475   error_full,
4476   tunnel_lost,
4477   tunnel_http_response
4478 };
4479
4480 static void
4481 client_watch_notify (GstRTSPClient * client)
4482 {
4483   GstRTSPClientPrivate *priv = client->priv;
4484   gboolean closed = TRUE;
4485
4486   GST_INFO ("client %p: watch destroyed", client);
4487   priv->watch = NULL;
4488   /* remove all sessions if the media says so and so drop the extra client ref */
4489   rtsp_ctrl_timeout_remove (priv);
4490   gst_rtsp_client_session_filter (client, cleanup_session, &closed);
4491   if (closed)
4492     g_signal_emit (client, gst_rtsp_client_signals[SIGNAL_CLOSED], 0, NULL);
4493   g_object_unref (client);
4494 }
4495
4496 /**
4497  * gst_rtsp_client_attach:
4498  * @client: a #GstRTSPClient
4499  * @context: (allow-none): a #GMainContext
4500  *
4501  * Attaches @client to @context. When the mainloop for @context is run, the
4502  * client will be dispatched. When @context is %NULL, the default context will be
4503  * used).
4504  *
4505  * This function should be called when the client properties and urls are fully
4506  * configured and the client is ready to start.
4507  *
4508  * Returns: the ID (greater than 0) for the source within the GMainContext.
4509  */
4510 guint
4511 gst_rtsp_client_attach (GstRTSPClient * client, GMainContext * context)
4512 {
4513   GstRTSPClientPrivate *priv;
4514   GSource *timer_src;
4515   guint res;
4516
4517   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), 0);
4518   priv = client->priv;
4519   g_return_val_if_fail (priv->connection != NULL, 0);
4520   g_return_val_if_fail (priv->watch == NULL, 0);
4521
4522   /* make sure noone will free the context before the watch is destroyed */
4523   priv->watch_context = g_main_context_ref (context);
4524
4525   /* create watch for the connection and attach */
4526   priv->watch = gst_rtsp_watch_new (priv->connection, &watch_funcs,
4527       g_object_ref (client), (GDestroyNotify) client_watch_notify);
4528   gst_rtsp_client_set_send_func (client, do_send_message, priv->watch,
4529       (GDestroyNotify) gst_rtsp_watch_unref);
4530
4531   gst_rtsp_watch_set_send_backlog (priv->watch, 0, WATCH_BACKLOG_SIZE);
4532
4533   GST_INFO ("client %p: attaching to context %p", client, context);
4534   res = gst_rtsp_watch_attach (priv->watch, context);
4535
4536   /* Setting up a timeout for the RTSP control channel until a session
4537    * is up where it is handling timeouts. */
4538   rtsp_ctrl_timeout_remove (priv);      /* removing old if any */
4539   g_mutex_lock (&priv->lock);
4540
4541   timer_src = g_timeout_source_new_seconds (RTSP_CTRL_CB_INTERVAL);
4542   g_source_set_callback (timer_src, rtsp_ctrl_timeout_cb, client, NULL);
4543   priv->rtsp_ctrl_timeout_id = g_source_attach (timer_src, priv->watch_context);
4544   g_source_unref (timer_src);
4545   GST_DEBUG ("rtsp control setting up session timeout id=%u.",
4546       priv->rtsp_ctrl_timeout_id);
4547
4548   g_mutex_unlock (&priv->lock);
4549
4550   return res;
4551 }
4552
4553 /**
4554  * gst_rtsp_client_session_filter:
4555  * @client: a #GstRTSPClient
4556  * @func: (scope call) (allow-none): a callback
4557  * @user_data: user data passed to @func
4558  *
4559  * Call @func for each session managed by @client. The result value of @func
4560  * determines what happens to the session. @func will be called with @client
4561  * locked so no further actions on @client can be performed from @func.
4562  *
4563  * If @func returns #GST_RTSP_FILTER_REMOVE, the session will be removed from
4564  * @client.
4565  *
4566  * If @func returns #GST_RTSP_FILTER_KEEP, the session will remain in @client.
4567  *
4568  * If @func returns #GST_RTSP_FILTER_REF, the session will remain in @client but
4569  * will also be added with an additional ref to the result #GList of this
4570  * function..
4571  *
4572  * When @func is %NULL, #GST_RTSP_FILTER_REF will be assumed for each session.
4573  *
4574  * Returns: (element-type GstRTSPSession) (transfer full): a #GList with all
4575  * sessions for which @func returned #GST_RTSP_FILTER_REF. After usage, each
4576  * element in the #GList should be unreffed before the list is freed.
4577  */
4578 GList *
4579 gst_rtsp_client_session_filter (GstRTSPClient * client,
4580     GstRTSPClientSessionFilterFunc func, gpointer user_data)
4581 {
4582   GstRTSPClientPrivate *priv;
4583   GList *result, *walk, *next;
4584   GHashTable *visited;
4585   guint cookie;
4586
4587   g_return_val_if_fail (GST_IS_RTSP_CLIENT (client), NULL);
4588
4589   priv = client->priv;
4590
4591   result = NULL;
4592   if (func)
4593     visited = g_hash_table_new_full (NULL, NULL, g_object_unref, NULL);
4594
4595   g_mutex_lock (&priv->lock);
4596 restart:
4597   cookie = priv->sessions_cookie;
4598   for (walk = priv->sessions; walk; walk = next) {
4599     GstRTSPSession *sess = walk->data;
4600     GstRTSPFilterResult res;
4601     gboolean changed;
4602
4603     next = g_list_next (walk);
4604
4605     if (func) {
4606       /* only visit each session once */
4607       if (g_hash_table_contains (visited, sess))
4608         continue;
4609
4610       g_hash_table_add (visited, g_object_ref (sess));
4611       g_mutex_unlock (&priv->lock);
4612
4613       res = func (client, sess, user_data);
4614
4615       g_mutex_lock (&priv->lock);
4616     } else
4617       res = GST_RTSP_FILTER_REF;
4618
4619     changed = (cookie != priv->sessions_cookie);
4620
4621     switch (res) {
4622       case GST_RTSP_FILTER_REMOVE:
4623         /* stop watching the session and pretend it went away, if the list was
4624          * changed, we can't use the current list position, try to see if we
4625          * still have the session */
4626         client_unwatch_session (client, sess, changed ? NULL : walk);
4627         cookie = priv->sessions_cookie;
4628         break;
4629       case GST_RTSP_FILTER_REF:
4630         result = g_list_prepend (result, g_object_ref (sess));
4631         break;
4632       case GST_RTSP_FILTER_KEEP:
4633       default:
4634         break;
4635     }
4636     if (changed)
4637       goto restart;
4638   }
4639   g_mutex_unlock (&priv->lock);
4640
4641   if (func)
4642     g_hash_table_unref (visited);
4643
4644   return result;
4645 }