6151c836ef626d0828b61f95da92669717cb1c32
[platform/upstream/gstreamer.git] / gst / rtsp-server / rtsp-server.c
1 /* GStreamer
2  * Copyright (C) 2008 Wim Taymans <wim.taymans at gmail.com>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
17  * Boston, MA 02110-1301, USA.
18  */
19
20 #include <stdlib.h>
21 #include <string.h>
22
23 #include "rtsp-server.h"
24 #include "rtsp-client.h"
25
26 #define DEFAULT_ADDRESS         "0.0.0.0"
27 #define DEFAULT_BOUND_PORT      -1
28 /* #define DEFAULT_ADDRESS         "::0" */
29 #define DEFAULT_SERVICE         "8554"
30 #define DEFAULT_BACKLOG         5
31 #define DEFAULT_MAX_THREADS     0
32
33 /* Define to use the SO_LINGER option so that the server sockets can be resused
34  * sooner. Disabled for now because it is not very well implemented by various
35  * OSes and it causes clients to fail to read the TEARDOWN response. */
36 #undef USE_SOLINGER
37
38 enum
39 {
40   PROP_0,
41   PROP_ADDRESS,
42   PROP_SERVICE,
43   PROP_BOUND_PORT,
44   PROP_BACKLOG,
45
46   PROP_SESSION_POOL,
47   PROP_MEDIA_MAPPING,
48   PROP_MAX_THREADS,
49   PROP_LAST
50 };
51
52 enum
53 {
54   SIGNAL_CLIENT_CONNECTED,
55   SIGNAL_LAST
56 };
57
58 G_DEFINE_TYPE (GstRTSPServer, gst_rtsp_server, G_TYPE_OBJECT);
59
60 GST_DEBUG_CATEGORY_STATIC (rtsp_server_debug);
61 #define GST_CAT_DEFAULT rtsp_server_debug
62
63 typedef struct _ClientContext ClientContext;
64
65 static guint gst_rtsp_server_signals[SIGNAL_LAST] = { 0 };
66
67 static void gst_rtsp_server_get_property (GObject * object, guint propid,
68     GValue * value, GParamSpec * pspec);
69 static void gst_rtsp_server_set_property (GObject * object, guint propid,
70     const GValue * value, GParamSpec * pspec);
71 static void gst_rtsp_server_finalize (GObject * object);
72
73 static gpointer do_loop (ClientContext * ctx);
74 static GstRTSPClient *default_create_client (GstRTSPServer * server);
75 static gboolean default_accept_client (GstRTSPServer * server,
76     GstRTSPClient * client, GSocket * socket, GError ** error);
77
78 static void
79 gst_rtsp_server_class_init (GstRTSPServerClass * klass)
80 {
81   GObjectClass *gobject_class;
82
83   gobject_class = G_OBJECT_CLASS (klass);
84
85   gobject_class->get_property = gst_rtsp_server_get_property;
86   gobject_class->set_property = gst_rtsp_server_set_property;
87   gobject_class->finalize = gst_rtsp_server_finalize;
88
89   /**
90    * GstRTSPServer::address:
91    *
92    * The address of the server. This is the address where the server will
93    * listen on.
94    */
95   g_object_class_install_property (gobject_class, PROP_ADDRESS,
96       g_param_spec_string ("address", "Address",
97           "The address the server uses to listen on", DEFAULT_ADDRESS,
98           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
99   /**
100    * GstRTSPServer::service:
101    *
102    * The service of the server. This is either a string with the service name or
103    * a port number (as a string) the server will listen on.
104    */
105   g_object_class_install_property (gobject_class, PROP_SERVICE,
106       g_param_spec_string ("service", "Service",
107           "The service or port number the server uses to listen on",
108           DEFAULT_SERVICE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
109   /**
110    * GstRTSPServer::bound-port:
111    *
112    * The actual port the server is listening on. Can be used to retrieve the
113    * port number when the server is started on port 0, which means bind to a
114    * random port. Set to -1 if the server has not been bound yet.
115    */
116   g_object_class_install_property (gobject_class, PROP_BOUND_PORT,
117       g_param_spec_int ("bound-port", "Bound port",
118           "The port number the server is listening on",
119           -1, G_MAXUINT16, DEFAULT_BOUND_PORT,
120           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
121   /**
122    * GstRTSPServer::backlog:
123    *
124    * The backlog argument defines the maximum length to which the queue of
125    * pending connections for the server may grow. If a connection request arrives
126    * when the queue is full, the client may receive an error with an indication of
127    * ECONNREFUSED or, if the underlying protocol supports retransmission, the
128    * request may be ignored so that a later reattempt at  connection succeeds.
129    */
130   g_object_class_install_property (gobject_class, PROP_BACKLOG,
131       g_param_spec_int ("backlog", "Backlog",
132           "The maximum length to which the queue "
133           "of pending connections may grow", 0, G_MAXINT, DEFAULT_BACKLOG,
134           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
135   /**
136    * GstRTSPServer::session-pool:
137    *
138    * The session pool of the server. By default each server has a separate
139    * session pool but sessions can be shared between servers by setting the same
140    * session pool on multiple servers.
141    */
142   g_object_class_install_property (gobject_class, PROP_SESSION_POOL,
143       g_param_spec_object ("session-pool", "Session Pool",
144           "The session pool to use for client session",
145           GST_TYPE_RTSP_SESSION_POOL,
146           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
147   /**
148    * GstRTSPServer::media-mapping:
149    *
150    * The media mapping to use for this server. By default the server has no
151    * media mapping and thus cannot map urls to media streams.
152    */
153   g_object_class_install_property (gobject_class, PROP_MEDIA_MAPPING,
154       g_param_spec_object ("media-mapping", "Media Mapping",
155           "The media mapping to use for client session",
156           GST_TYPE_RTSP_MEDIA_MAPPING,
157           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
158   /**
159    * GstRTSPServer::max-threads:
160    *
161    * The maximum amount of threads to use for client connections. A value of
162    * 0 means to use only the mainloop, -1 means an unlimited amount of
163    * threads.
164    */
165   g_object_class_install_property (gobject_class, PROP_MAX_THREADS,
166       g_param_spec_int ("max-threads", "Max Threads",
167           "The maximum amount of threads to use for client connections "
168           "(0 = only mainloop, -1 = unlimited)", -1, G_MAXINT,
169           DEFAULT_MAX_THREADS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
170
171   gst_rtsp_server_signals[SIGNAL_CLIENT_CONNECTED] =
172       g_signal_new ("client-connected", G_TYPE_FROM_CLASS (gobject_class),
173       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRTSPServerClass, client_connected),
174       NULL, NULL, g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1,
175       gst_rtsp_client_get_type ());
176
177   klass->create_client = default_create_client;
178   klass->accept_client = default_accept_client;
179
180   klass->pool = g_thread_pool_new ((GFunc) do_loop, klass, -1, FALSE, NULL);
181
182   GST_DEBUG_CATEGORY_INIT (rtsp_server_debug, "rtspserver", 0, "GstRTSPServer");
183 }
184
185 static void
186 gst_rtsp_server_init (GstRTSPServer * server)
187 {
188   g_mutex_init (&server->lock);
189   server->address = g_strdup (DEFAULT_ADDRESS);
190   server->service = g_strdup (DEFAULT_SERVICE);
191   server->socket = NULL;
192   server->backlog = DEFAULT_BACKLOG;
193   server->session_pool = gst_rtsp_session_pool_new ();
194   server->media_mapping = gst_rtsp_media_mapping_new ();
195   server->max_threads = DEFAULT_MAX_THREADS;
196 }
197
198 static void
199 gst_rtsp_server_finalize (GObject * object)
200 {
201   GstRTSPServer *server = GST_RTSP_SERVER (object);
202
203   GST_DEBUG_OBJECT (server, "finalize server");
204
205   g_free (server->address);
206   g_free (server->service);
207
208   if (server->socket)
209     g_object_unref (server->socket);
210
211   g_object_unref (server->session_pool);
212   g_object_unref (server->media_mapping);
213
214   if (server->auth)
215     g_object_unref (server->auth);
216
217   g_mutex_clear (&server->lock);
218
219   G_OBJECT_CLASS (gst_rtsp_server_parent_class)->finalize (object);
220 }
221
222 /**
223  * gst_rtsp_server_new:
224  *
225  * Create a new #GstRTSPServer instance.
226  */
227 GstRTSPServer *
228 gst_rtsp_server_new (void)
229 {
230   GstRTSPServer *result;
231
232   result = g_object_new (GST_TYPE_RTSP_SERVER, NULL);
233
234   return result;
235 }
236
237 /**
238  * gst_rtsp_server_set_address:
239  * @server: a #GstRTSPServer
240  * @address: the address
241  *
242  * Configure @server to accept connections on the given address.
243  *
244  * This function must be called before the server is bound.
245  */
246 void
247 gst_rtsp_server_set_address (GstRTSPServer * server, const gchar * address)
248 {
249   g_return_if_fail (GST_IS_RTSP_SERVER (server));
250   g_return_if_fail (address != NULL);
251
252   GST_RTSP_SERVER_LOCK (server);
253   g_free (server->address);
254   server->address = g_strdup (address);
255   GST_RTSP_SERVER_UNLOCK (server);
256 }
257
258 /**
259  * gst_rtsp_server_get_address:
260  * @server: a #GstRTSPServer
261  *
262  * Get the address on which the server will accept connections.
263  *
264  * Returns: the server address. g_free() after usage.
265  */
266 gchar *
267 gst_rtsp_server_get_address (GstRTSPServer * server)
268 {
269   gchar *result;
270   g_return_val_if_fail (GST_IS_RTSP_SERVER (server), NULL);
271
272   GST_RTSP_SERVER_LOCK (server);
273   result = g_strdup (server->address);
274   GST_RTSP_SERVER_UNLOCK (server);
275
276   return result;
277 }
278
279 /**
280  * gst_rtsp_server_get_bound_port:
281  * @server: a #GstRTSPServer
282  *
283  * Get the port number where the server was bound to.
284  *
285  * Returns: the port number
286  */
287 int
288 gst_rtsp_server_get_bound_port (GstRTSPServer * server)
289 {
290   GSocketAddress *address;
291   int result = -1;
292
293   g_return_val_if_fail (GST_IS_RTSP_SERVER (server), result);
294
295   GST_RTSP_SERVER_LOCK (server);
296   if (server->socket == NULL)
297     goto out;
298
299   address = g_socket_get_local_address (server->socket, NULL);
300   result = g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (address));
301   g_object_unref (address);
302
303 out:
304   GST_RTSP_SERVER_UNLOCK (server);
305
306   return result;
307 }
308
309 /**
310  * gst_rtsp_server_set_service:
311  * @server: a #GstRTSPServer
312  * @service: the service
313  *
314  * Configure @server to accept connections on the given service.
315  * @service should be a string containing the service name (see services(5)) or
316  * a string containing a port number between 1 and 65535.
317  *
318  * This function must be called before the server is bound.
319  */
320 void
321 gst_rtsp_server_set_service (GstRTSPServer * server, const gchar * service)
322 {
323   g_return_if_fail (GST_IS_RTSP_SERVER (server));
324   g_return_if_fail (service != NULL);
325
326   GST_RTSP_SERVER_LOCK (server);
327   g_free (server->service);
328   server->service = g_strdup (service);
329   GST_RTSP_SERVER_UNLOCK (server);
330 }
331
332 /**
333  * gst_rtsp_server_get_service:
334  * @server: a #GstRTSPServer
335  *
336  * Get the service on which the server will accept connections.
337  *
338  * Returns: the service. use g_free() after usage.
339  */
340 gchar *
341 gst_rtsp_server_get_service (GstRTSPServer * server)
342 {
343   gchar *result;
344
345   g_return_val_if_fail (GST_IS_RTSP_SERVER (server), NULL);
346
347   GST_RTSP_SERVER_LOCK (server);
348   result = g_strdup (server->service);
349   GST_RTSP_SERVER_UNLOCK (server);
350
351   return result;
352 }
353
354 /**
355  * gst_rtsp_server_set_backlog:
356  * @server: a #GstRTSPServer
357  * @backlog: the backlog
358  *
359  * configure the maximum amount of requests that may be queued for the
360  * server.
361  *
362  * This function must be called before the server is bound.
363  */
364 void
365 gst_rtsp_server_set_backlog (GstRTSPServer * server, gint backlog)
366 {
367   g_return_if_fail (GST_IS_RTSP_SERVER (server));
368
369   GST_RTSP_SERVER_LOCK (server);
370   server->backlog = backlog;
371   GST_RTSP_SERVER_UNLOCK (server);
372 }
373
374 /**
375  * gst_rtsp_server_get_backlog:
376  * @server: a #GstRTSPServer
377  *
378  * The maximum amount of queued requests for the server.
379  *
380  * Returns: the server backlog.
381  */
382 gint
383 gst_rtsp_server_get_backlog (GstRTSPServer * server)
384 {
385   gint result;
386
387   g_return_val_if_fail (GST_IS_RTSP_SERVER (server), -1);
388
389   GST_RTSP_SERVER_LOCK (server);
390   result = server->backlog;
391   GST_RTSP_SERVER_UNLOCK (server);
392
393   return result;
394 }
395
396 /**
397  * gst_rtsp_server_set_session_pool:
398  * @server: a #GstRTSPServer
399  * @pool: a #GstRTSPSessionPool
400  *
401  * configure @pool to be used as the session pool of @server.
402  */
403 void
404 gst_rtsp_server_set_session_pool (GstRTSPServer * server,
405     GstRTSPSessionPool * pool)
406 {
407   GstRTSPSessionPool *old;
408
409   g_return_if_fail (GST_IS_RTSP_SERVER (server));
410
411   if (pool)
412     g_object_ref (pool);
413
414   GST_RTSP_SERVER_LOCK (server);
415   old = server->session_pool;
416   server->session_pool = pool;
417   GST_RTSP_SERVER_UNLOCK (server);
418
419   if (old)
420     g_object_unref (old);
421 }
422
423 /**
424  * gst_rtsp_server_get_session_pool:
425  * @server: a #GstRTSPServer
426  *
427  * Get the #GstRTSPSessionPool used as the session pool of @server.
428  *
429  * Returns: (transfer full): the #GstRTSPSessionPool used for sessions. g_object_unref() after
430  * usage.
431  */
432 GstRTSPSessionPool *
433 gst_rtsp_server_get_session_pool (GstRTSPServer * server)
434 {
435   GstRTSPSessionPool *result;
436
437   g_return_val_if_fail (GST_IS_RTSP_SERVER (server), NULL);
438
439   GST_RTSP_SERVER_LOCK (server);
440   if ((result = server->session_pool))
441     g_object_ref (result);
442   GST_RTSP_SERVER_UNLOCK (server);
443
444   return result;
445 }
446
447 /**
448  * gst_rtsp_server_set_media_mapping:
449  * @server: a #GstRTSPServer
450  * @mapping: a #GstRTSPMediaMapping
451  *
452  * configure @mapping to be used as the media mapping of @server.
453  */
454 void
455 gst_rtsp_server_set_media_mapping (GstRTSPServer * server,
456     GstRTSPMediaMapping * mapping)
457 {
458   GstRTSPMediaMapping *old;
459
460   g_return_if_fail (GST_IS_RTSP_SERVER (server));
461
462   if (mapping)
463     g_object_ref (mapping);
464
465   GST_RTSP_SERVER_LOCK (server);
466   old = server->media_mapping;
467   server->media_mapping = mapping;
468   GST_RTSP_SERVER_UNLOCK (server);
469
470   if (old)
471     g_object_unref (old);
472 }
473
474
475 /**
476  * gst_rtsp_server_get_media_mapping:
477  * @server: a #GstRTSPServer
478  *
479  * Get the #GstRTSPMediaMapping used as the media mapping of @server.
480  *
481  * Returns: (transfer full): the #GstRTSPMediaMapping of @server. g_object_unref() after
482  * usage.
483  */
484 GstRTSPMediaMapping *
485 gst_rtsp_server_get_media_mapping (GstRTSPServer * server)
486 {
487   GstRTSPMediaMapping *result;
488
489   g_return_val_if_fail (GST_IS_RTSP_SERVER (server), NULL);
490
491   GST_RTSP_SERVER_LOCK (server);
492   if ((result = server->media_mapping))
493     g_object_ref (result);
494   GST_RTSP_SERVER_UNLOCK (server);
495
496   return result;
497 }
498
499 /**
500  * gst_rtsp_server_set_auth:
501  * @server: a #GstRTSPServer
502  * @auth: a #GstRTSPAuth
503  *
504  * configure @auth to be used as the authentication manager of @server.
505  */
506 void
507 gst_rtsp_server_set_auth (GstRTSPServer * server, GstRTSPAuth * auth)
508 {
509   GstRTSPAuth *old;
510
511   g_return_if_fail (GST_IS_RTSP_SERVER (server));
512
513   if (auth)
514     g_object_ref (auth);
515
516   GST_RTSP_SERVER_LOCK (server);
517   old = server->auth;
518   server->auth = auth;
519   GST_RTSP_SERVER_UNLOCK (server);
520
521   if (old)
522     g_object_unref (old);
523 }
524
525
526 /**
527  * gst_rtsp_server_get_auth:
528  * @server: a #GstRTSPServer
529  *
530  * Get the #GstRTSPAuth used as the authentication manager of @server.
531  *
532  * Returns: (transfer full): the #GstRTSPAuth of @server. g_object_unref() after
533  * usage.
534  */
535 GstRTSPAuth *
536 gst_rtsp_server_get_auth (GstRTSPServer * server)
537 {
538   GstRTSPAuth *result;
539
540   g_return_val_if_fail (GST_IS_RTSP_SERVER (server), NULL);
541
542   GST_RTSP_SERVER_LOCK (server);
543   if ((result = server->auth))
544     g_object_ref (result);
545   GST_RTSP_SERVER_UNLOCK (server);
546
547   return result;
548 }
549
550 /**
551  * gst_rtsp_server_set_max_threads:
552  * @server: a #GstRTSPServer
553  * @max_threads: maximum threads
554  *
555  * Set the maximum threads used by the server to handle client requests.
556  * A value of 0 will use the server mainloop, a value of -1 will use an
557  * unlimited number of threads.
558  */
559 void
560 gst_rtsp_server_set_max_threads (GstRTSPServer * server, gint max_threads)
561 {
562   g_return_if_fail (GST_IS_RTSP_SERVER (server));
563
564   GST_RTSP_SERVER_LOCK (server);
565   server->max_threads = max_threads;
566   GST_RTSP_SERVER_UNLOCK (server);
567 }
568
569 /**
570  * gst_rtsp_server_get_max_threads:
571  * @server: a #GstRTSPServer
572  *
573  * Get the maximum number of threads used for client connections.
574  * See gst_rtsp_server_set_max_threads().
575  *
576  * Returns: the maximum number of threads.
577  */
578 gint
579 gst_rtsp_server_get_max_threads (GstRTSPServer * server)
580 {
581   gint res;
582
583   g_return_val_if_fail (GST_IS_RTSP_SERVER (server), -1);
584
585   GST_RTSP_SERVER_LOCK (server);
586   res = server->max_threads;
587   GST_RTSP_SERVER_UNLOCK (server);
588
589   return res;
590 }
591
592
593 static void
594 gst_rtsp_server_get_property (GObject * object, guint propid,
595     GValue * value, GParamSpec * pspec)
596 {
597   GstRTSPServer *server = GST_RTSP_SERVER (object);
598
599   switch (propid) {
600     case PROP_ADDRESS:
601       g_value_take_string (value, gst_rtsp_server_get_address (server));
602       break;
603     case PROP_SERVICE:
604       g_value_take_string (value, gst_rtsp_server_get_service (server));
605       break;
606     case PROP_BOUND_PORT:
607       g_value_set_int (value, gst_rtsp_server_get_bound_port (server));
608       break;
609     case PROP_BACKLOG:
610       g_value_set_int (value, gst_rtsp_server_get_backlog (server));
611       break;
612     case PROP_SESSION_POOL:
613       g_value_take_object (value, gst_rtsp_server_get_session_pool (server));
614       break;
615     case PROP_MEDIA_MAPPING:
616       g_value_take_object (value, gst_rtsp_server_get_media_mapping (server));
617       break;
618     case PROP_MAX_THREADS:
619       g_value_set_int (value, gst_rtsp_server_get_max_threads (server));
620       break;
621     default:
622       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, propid, pspec);
623   }
624 }
625
626 static void
627 gst_rtsp_server_set_property (GObject * object, guint propid,
628     const GValue * value, GParamSpec * pspec)
629 {
630   GstRTSPServer *server = GST_RTSP_SERVER (object);
631
632   switch (propid) {
633     case PROP_ADDRESS:
634       gst_rtsp_server_set_address (server, g_value_get_string (value));
635       break;
636     case PROP_SERVICE:
637       gst_rtsp_server_set_service (server, g_value_get_string (value));
638       break;
639     case PROP_BACKLOG:
640       gst_rtsp_server_set_backlog (server, g_value_get_int (value));
641       break;
642     case PROP_SESSION_POOL:
643       gst_rtsp_server_set_session_pool (server, g_value_get_object (value));
644       break;
645     case PROP_MEDIA_MAPPING:
646       gst_rtsp_server_set_media_mapping (server, g_value_get_object (value));
647       break;
648     case PROP_MAX_THREADS:
649       gst_rtsp_server_set_max_threads (server, g_value_get_int (value));
650       break;
651     default:
652       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, propid, pspec);
653   }
654 }
655
656 /**
657  * gst_rtsp_server_create_socket:
658  * @server: a #GstRTSPServer
659  * @cancellable: a #GCancellable
660  * @error: a #GError
661  *
662  * Create a #GSocket for @server. The socket will listen on the
663  * configured service.
664  *
665  * Returns: (transfer full): the #GSocket for @server or NULL when an error occured.
666  */
667 GSocket *
668 gst_rtsp_server_create_socket (GstRTSPServer * server,
669     GCancellable * cancellable, GError ** error)
670 {
671   GSocketConnectable *conn;
672   GSocketAddressEnumerator *enumerator;
673   GSocket *socket = NULL;
674 #ifdef USE_SOLINGER
675   struct linger linger;
676 #endif
677   GError *sock_error = NULL;
678   GError *bind_error = NULL;
679   guint16 port;
680
681   g_return_val_if_fail (GST_IS_RTSP_SERVER (server), NULL);
682
683   GST_RTSP_SERVER_LOCK (server);
684   GST_DEBUG_OBJECT (server, "getting address info of %s/%s", server->address,
685       server->service);
686
687   /* resolve the server IP address */
688   port = atoi (server->service);
689   if (port != 0 || !strcmp (server->service, "0"))
690     conn = g_network_address_new (server->address, port);
691   else
692     conn = g_network_service_new (server->service, "tcp", server->address);
693
694   enumerator = g_socket_connectable_enumerate (conn);
695   g_object_unref (conn);
696
697   /* create server socket, we loop through all the addresses until we manage to
698    * create a socket and bind. */
699   while (TRUE) {
700     GSocketAddress *sockaddr;
701
702     sockaddr =
703         g_socket_address_enumerator_next (enumerator, cancellable, error);
704     if (!sockaddr) {
705       if (!*error)
706         GST_DEBUG_OBJECT (server, "no more addresses %s",
707             *error ? (*error)->message : "");
708       else
709         GST_DEBUG_OBJECT (server, "failed to retrieve next address %s",
710             (*error)->message);
711       break;
712     }
713
714     /* only keep the first error */
715     socket = g_socket_new (g_socket_address_get_family (sockaddr),
716         G_SOCKET_TYPE_STREAM, G_SOCKET_PROTOCOL_TCP,
717         sock_error ? NULL : &sock_error);
718
719     if (socket == NULL) {
720       GST_DEBUG_OBJECT (server, "failed to make socket (%s), try next",
721           sock_error->message);
722       g_object_unref (sockaddr);
723       continue;
724     }
725
726     if (g_socket_bind (socket, sockaddr, TRUE, bind_error ? NULL : &bind_error)) {
727       g_object_unref (sockaddr);
728       break;
729     }
730
731     GST_DEBUG_OBJECT (server, "failed to bind socket (%s), try next",
732         bind_error->message);
733     g_object_unref (sockaddr);
734     g_object_unref (socket);
735     socket = NULL;
736   }
737   g_object_unref (enumerator);
738
739   if (socket == NULL)
740     goto no_socket;
741
742   g_clear_error (&sock_error);
743   g_clear_error (&bind_error);
744
745   GST_DEBUG_OBJECT (server, "opened sending server socket");
746
747   /* keep connection alive; avoids SIGPIPE during write */
748   g_socket_set_keepalive (socket, TRUE);
749
750 #if 0
751 #ifdef USE_SOLINGER
752   /* make sure socket is reset 5 seconds after close. This ensure that we can
753    * reuse the socket quickly while still having a chance to send data to the
754    * client. */
755   linger.l_onoff = 1;
756   linger.l_linger = 5;
757   if (setsockopt (sockfd, SOL_SOCKET, SO_LINGER,
758           (void *) &linger, sizeof (linger)) < 0)
759     goto linger_failed;
760 #endif
761 #endif
762
763   /* set the server socket to nonblocking */
764   g_socket_set_blocking (socket, FALSE);
765
766   /* set listen backlog */
767   g_socket_set_listen_backlog (socket, server->backlog);
768
769   if (!g_socket_listen (socket, error))
770     goto listen_failed;
771
772   GST_DEBUG_OBJECT (server, "listening on server socket %p with queue of %d",
773       socket, server->backlog);
774
775   GST_RTSP_SERVER_UNLOCK (server);
776
777   return socket;
778
779   /* ERRORS */
780 no_socket:
781   {
782     GST_ERROR_OBJECT (server, "failed to create socket");
783     goto close_error;
784   }
785 #if 0
786 #ifdef USE_SOLINGER
787 linger_failed:
788   {
789     GST_ERROR_OBJECT (server, "failed to no linger socket: %s",
790         g_strerror (errno));
791     goto close_error;
792   }
793 #endif
794 #endif
795 listen_failed:
796   {
797     GST_ERROR_OBJECT (server, "failed to listen on socket: %s",
798         (*error)->message);
799     goto close_error;
800   }
801 close_error:
802   {
803     if (socket)
804       g_object_unref (socket);
805
806     if (sock_error) {
807       if (error == NULL)
808         g_propagate_error (error, sock_error);
809       else
810         g_error_free (sock_error);
811     }
812     if (bind_error) {
813       if ((error == NULL) || (*error == NULL))
814         g_propagate_error (error, bind_error);
815       else
816         g_error_free (bind_error);
817     }
818     GST_RTSP_SERVER_UNLOCK (server);
819     return NULL;
820   }
821 }
822
823 struct _ClientContext
824 {
825   GstRTSPServer *server;
826   GMainLoop *loop;
827   GMainContext *context;
828   GstRTSPClient *client;
829 };
830
831 static void
832 free_client_context (ClientContext * ctx)
833 {
834   g_main_context_unref (ctx->context);
835   if (ctx->loop)
836     g_main_loop_unref (ctx->loop);
837   g_object_unref (ctx->client);
838   g_slice_free (ClientContext, ctx);
839 }
840
841 static gpointer
842 do_loop (ClientContext * ctx)
843 {
844   GST_INFO ("enter mainloop");
845   g_main_loop_run (ctx->loop);
846   GST_INFO ("exit mainloop");
847
848   free_client_context (ctx);
849
850   return NULL;
851 }
852
853 static void
854 unmanage_client (GstRTSPClient * client, ClientContext * ctx)
855 {
856   GstRTSPServer *server = ctx->server;
857
858   GST_DEBUG_OBJECT (server, "unmanage client %p", client);
859
860   g_object_ref (server);
861   gst_rtsp_client_set_server (client, NULL);
862
863   GST_RTSP_SERVER_LOCK (server);
864   server->clients = g_list_remove (server->clients, ctx);
865   GST_RTSP_SERVER_UNLOCK (server);
866
867   if (ctx->loop)
868     g_main_loop_quit (ctx->loop);
869   else
870     free_client_context (ctx);
871
872   g_object_unref (server);
873 }
874
875 /* add the client context to the active list of clients, takes ownership
876  * of client */
877 static void
878 manage_client (GstRTSPServer * server, GstRTSPClient * client)
879 {
880   ClientContext *ctx;
881
882   GST_DEBUG_OBJECT (server, "manage client %p", client);
883   gst_rtsp_client_set_server (client, server);
884
885   ctx = g_slice_new0 (ClientContext);
886   ctx->server = server;
887   ctx->client = client;
888   if (server->max_threads == 0) {
889     GSource *source;
890
891     /* find the context to add the watch */
892     if ((source = g_main_current_source ()))
893       ctx->context = g_main_context_ref (g_source_get_context (source));
894     else
895       ctx->context = NULL;
896   } else {
897     ctx->context = g_main_context_new ();
898     ctx->loop = g_main_loop_new (ctx->context, TRUE);
899   }
900   gst_rtsp_client_attach (client, ctx->context);
901
902   GST_RTSP_SERVER_LOCK (server);
903   g_signal_connect (client, "closed", (GCallback) unmanage_client, ctx);
904   server->clients = g_list_prepend (server->clients, ctx);
905   GST_RTSP_SERVER_UNLOCK (server);
906
907   if (ctx->loop) {
908     GstRTSPServerClass *klass = GST_RTSP_SERVER_GET_CLASS (server);
909
910     g_thread_pool_push (klass->pool, ctx, NULL);
911   }
912 }
913
914 static GstRTSPClient *
915 default_create_client (GstRTSPServer * server)
916 {
917   GstRTSPClient *client;
918
919   /* a new client connected, create a session to handle the client. */
920   client = gst_rtsp_client_new ();
921
922   /* set the session pool that this client should use */
923   GST_RTSP_SERVER_LOCK (server);
924   gst_rtsp_client_set_session_pool (client, server->session_pool);
925   /* set the media mapping that this client should use */
926   gst_rtsp_client_set_media_mapping (client, server->media_mapping);
927   /* set authentication manager */
928   gst_rtsp_client_set_auth (client, server->auth);
929   GST_RTSP_SERVER_UNLOCK (server);
930
931   return client;
932 }
933
934 /* default method for creating a new client object in the server to accept and
935  * handle a client connection on this server */
936 static gboolean
937 default_accept_client (GstRTSPServer * server, GstRTSPClient * client,
938     GSocket * socket, GError ** error)
939 {
940   /* accept connections for that client, this function returns after accepting
941    * the connection and will run the remainder of the communication with the
942    * client asyncronously. */
943   if (!gst_rtsp_client_accept (client, socket, NULL, error))
944     goto accept_failed;
945
946   return TRUE;
947
948   /* ERRORS */
949 accept_failed:
950   {
951     GST_ERROR_OBJECT (server,
952         "Could not accept client on server : %s", (*error)->message);
953     return FALSE;
954   }
955 }
956
957 /**
958  * gst_rtsp_server_transfer_connection:
959  * @server: a #GstRTSPServer
960  * @socket: a network socket
961  * @ip: the IP address of the remote client
962  * @port: the port used by the other end
963  * @initial_buffer: any initial data that was already read from the socket
964  *
965  * Take an existing network socket and use it for an RTSP connection. This
966  * is used when transferring a socket from an HTTP server which should be used
967  * as an RTSP over HTTP tunnel. The @initial_buffer contains any remaining data
968  * that the HTTP server read from the socket while parsing the HTTP header.
969  *
970  * Returns: TRUE if all was ok, FALSE if an error occured.
971  */
972 gboolean
973 gst_rtsp_server_transfer_connection (GstRTSPServer * server, GSocket * socket,
974     const gchar * ip, gint port, const gchar * initial_buffer)
975 {
976   GstRTSPClient *client = NULL;
977   GstRTSPServerClass *klass;
978   GError *error = NULL;
979
980   klass = GST_RTSP_SERVER_GET_CLASS (server);
981
982   if (klass->create_client)
983     client = klass->create_client (server);
984   if (client == NULL)
985     goto client_failed;
986
987   /* a new client connected, create a client object to handle the client. */
988   if (!gst_rtsp_client_use_socket (client, socket, ip,
989           port, initial_buffer, &error)) {
990     goto transfer_failed;
991   }
992
993   /* manage the client connection */
994   manage_client (server, client);
995
996   g_signal_emit (server, gst_rtsp_server_signals[SIGNAL_CLIENT_CONNECTED], 0,
997       client);
998
999   return TRUE;
1000
1001   /* ERRORS */
1002 client_failed:
1003   {
1004     GST_ERROR_OBJECT (server, "failed to create a client");
1005     return FALSE;
1006   }
1007 transfer_failed:
1008   {
1009     GST_ERROR_OBJECT (server, "failed to accept client: %s", error->message);
1010     g_error_free (error);
1011     g_object_unref (client);
1012     return FALSE;
1013   }
1014 }
1015
1016 /**
1017  * gst_rtsp_server_io_func:
1018  * @socket: a #GSocket
1019  * @condition: the condition on @source
1020  * @server: a #GstRTSPServer
1021  *
1022  * A default #GSocketSourceFunc that creates a new #GstRTSPClient to accept and handle a
1023  * new connection on @socket or @server.
1024  *
1025  * Returns: TRUE if the source could be connected, FALSE if an error occured.
1026  */
1027 gboolean
1028 gst_rtsp_server_io_func (GSocket * socket, GIOCondition condition,
1029     GstRTSPServer * server)
1030 {
1031   gboolean result = TRUE;
1032   GstRTSPClient *client = NULL;
1033   GstRTSPServerClass *klass;
1034   GError *error = NULL;
1035
1036   if (condition & G_IO_IN) {
1037     klass = GST_RTSP_SERVER_GET_CLASS (server);
1038
1039     if (klass->create_client)
1040       client = klass->create_client (server);
1041     if (client == NULL)
1042       goto client_failed;
1043
1044     /* a new client connected, create a client object to handle the client. */
1045     if (klass->accept_client)
1046       result = klass->accept_client (server, client, socket, &error);
1047     if (!result)
1048       goto accept_failed;
1049
1050     /* manage the client connection */
1051     manage_client (server, client);
1052
1053     g_signal_emit (server, gst_rtsp_server_signals[SIGNAL_CLIENT_CONNECTED], 0,
1054         client);
1055   } else {
1056     GST_WARNING_OBJECT (server, "received unknown event %08x", condition);
1057   }
1058   return TRUE;
1059
1060   /* ERRORS */
1061 client_failed:
1062   {
1063     GST_ERROR_OBJECT (server, "failed to create a client");
1064     return FALSE;
1065   }
1066 accept_failed:
1067   {
1068     GST_ERROR_OBJECT (server, "failed to accept client: %s", error->message);
1069     g_error_free (error);
1070     g_object_unref (client);
1071     return FALSE;
1072   }
1073 }
1074
1075 static void
1076 watch_destroyed (GstRTSPServer * server)
1077 {
1078   GST_DEBUG_OBJECT (server, "source destroyed");
1079   g_object_unref (server);
1080 }
1081
1082 /**
1083  * gst_rtsp_server_create_source:
1084  * @server: a #GstRTSPServer
1085  * @cancellable: a #GCancellable or %NULL.
1086  * @error: a #GError
1087  *
1088  * Create a #GSource for @server. The new source will have a default
1089  * #GSocketSourceFunc of gst_rtsp_server_io_func().
1090  *
1091  * @cancellable if not NULL can be used to cancel the source, which will cause
1092  * the source to trigger, reporting the current condition (which is likely 0
1093  * unless cancellation happened at the same time as a condition change). You can
1094  * check for this in the callback using g_cancellable_is_cancelled().
1095  *
1096  * Returns: the #GSource for @server or NULL when an error occured. Free with
1097  * g_source_unref ()
1098  */
1099 GSource *
1100 gst_rtsp_server_create_source (GstRTSPServer * server,
1101     GCancellable * cancellable, GError ** error)
1102 {
1103   GSocket *socket, *old;
1104   GSource *source;
1105
1106   g_return_val_if_fail (GST_IS_RTSP_SERVER (server), NULL);
1107
1108   socket = gst_rtsp_server_create_socket (server, NULL, error);
1109   if (socket == NULL)
1110     goto no_socket;
1111
1112   GST_RTSP_SERVER_LOCK (server);
1113   old = server->socket;
1114   server->socket = g_object_ref (socket);
1115   GST_RTSP_SERVER_UNLOCK (server);
1116
1117   if (old)
1118     g_object_unref (old);
1119
1120   /* create a watch for reads (new connections) and possible errors */
1121   source = g_socket_create_source (socket, G_IO_IN |
1122       G_IO_ERR | G_IO_HUP | G_IO_NVAL, cancellable);
1123   g_object_unref (socket);
1124
1125   /* configure the callback */
1126   g_source_set_callback (source,
1127       (GSourceFunc) gst_rtsp_server_io_func, g_object_ref (server),
1128       (GDestroyNotify) watch_destroyed);
1129
1130   return source;
1131
1132 no_socket:
1133   {
1134     GST_ERROR_OBJECT (server, "failed to create socket");
1135     return NULL;
1136   }
1137 }
1138
1139 /**
1140  * gst_rtsp_server_attach:
1141  * @server: a #GstRTSPServer
1142  * @context: (allow-none): a #GMainContext
1143  *
1144  * Attaches @server to @context. When the mainloop for @context is run, the
1145  * server will be dispatched. When @context is NULL, the default context will be
1146  * used).
1147  *
1148  * This function should be called when the server properties and urls are fully
1149  * configured and the server is ready to start.
1150  *
1151  * Returns: the ID (greater than 0) for the source within the GMainContext.
1152  */
1153 guint
1154 gst_rtsp_server_attach (GstRTSPServer * server, GMainContext * context)
1155 {
1156   guint res;
1157   GSource *source;
1158   GError *error = NULL;
1159
1160   g_return_val_if_fail (GST_IS_RTSP_SERVER (server), 0);
1161
1162   source = gst_rtsp_server_create_source (server, NULL, &error);
1163   if (source == NULL)
1164     goto no_source;
1165
1166   res = g_source_attach (source, context);
1167   g_source_unref (source);
1168
1169   return res;
1170
1171   /* ERRORS */
1172 no_source:
1173   {
1174     GST_ERROR_OBJECT (server, "failed to create watch: %s", error->message);
1175     g_error_free (error);
1176     return 0;
1177   }
1178 }