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