server: free old socket
[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 }
196
197 static void
198 gst_rtsp_server_finalize (GObject * object)
199 {
200   GstRTSPServer *server = GST_RTSP_SERVER (object);
201
202   GST_DEBUG_OBJECT (server, "finalize server");
203
204   g_free (server->address);
205   g_free (server->service);
206   if (server->socket)
207     g_object_unref (server->socket);
208
209   g_object_unref (server->session_pool);
210   g_object_unref (server->media_mapping);
211
212   if (server->auth)
213     g_object_unref (server->auth);
214
215   g_mutex_clear (&server->lock);
216
217   G_OBJECT_CLASS (gst_rtsp_server_parent_class)->finalize (object);
218 }
219
220 /**
221  * gst_rtsp_server_new:
222  *
223  * Create a new #GstRTSPServer instance.
224  */
225 GstRTSPServer *
226 gst_rtsp_server_new (void)
227 {
228   GstRTSPServer *result;
229
230   result = g_object_new (GST_TYPE_RTSP_SERVER, NULL);
231
232   return result;
233 }
234
235 /**
236  * gst_rtsp_server_set_address:
237  * @server: a #GstRTSPServer
238  * @address: the address
239  *
240  * Configure @server to accept connections on the given address.
241  *
242  * This function must be called before the server is bound.
243  */
244 void
245 gst_rtsp_server_set_address (GstRTSPServer * server, const gchar * address)
246 {
247   g_return_if_fail (GST_IS_RTSP_SERVER (server));
248   g_return_if_fail (address != NULL);
249
250   GST_RTSP_SERVER_LOCK (server);
251   g_free (server->address);
252   server->address = g_strdup (address);
253   GST_RTSP_SERVER_UNLOCK (server);
254 }
255
256 /**
257  * gst_rtsp_server_get_address:
258  * @server: a #GstRTSPServer
259  *
260  * Get the address on which the server will accept connections.
261  *
262  * Returns: the server address. g_free() after usage.
263  */
264 gchar *
265 gst_rtsp_server_get_address (GstRTSPServer * server)
266 {
267   gchar *result;
268   g_return_val_if_fail (GST_IS_RTSP_SERVER (server), NULL);
269
270   GST_RTSP_SERVER_LOCK (server);
271   result = g_strdup (server->address);
272   GST_RTSP_SERVER_UNLOCK (server);
273
274   return result;
275 }
276
277 /**
278  * gst_rtsp_server_get_bound_port:
279  * @server: a #GstRTSPServer
280  *
281  * Get the port number where the server was bound to.
282  *
283  * Returns: the port number
284  */
285 int
286 gst_rtsp_server_get_bound_port (GstRTSPServer * server)
287 {
288   GSocketAddress *address;
289   int result = -1;
290
291   g_return_val_if_fail (GST_IS_RTSP_SERVER (server), result);
292
293   GST_RTSP_SERVER_LOCK (server);
294   if (server->socket == NULL)
295     goto out;
296
297   address = g_socket_get_local_address (server->socket, NULL);
298   result = g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (address));
299   g_object_unref (address);
300
301 out:
302   GST_RTSP_SERVER_UNLOCK (server);
303
304   return result;
305 }
306
307 /**
308  * gst_rtsp_server_set_service:
309  * @server: a #GstRTSPServer
310  * @service: the service
311  *
312  * Configure @server to accept connections on the given service.
313  * @service should be a string containing the service name (see services(5)) or
314  * a string containing a port number between 1 and 65535.
315  *
316  * This function must be called before the server is bound.
317  */
318 void
319 gst_rtsp_server_set_service (GstRTSPServer * server, const gchar * service)
320 {
321   g_return_if_fail (GST_IS_RTSP_SERVER (server));
322   g_return_if_fail (service != NULL);
323
324   GST_RTSP_SERVER_LOCK (server);
325   g_free (server->service);
326   server->service = g_strdup (service);
327   GST_RTSP_SERVER_UNLOCK (server);
328 }
329
330 /**
331  * gst_rtsp_server_get_service:
332  * @server: a #GstRTSPServer
333  *
334  * Get the service on which the server will accept connections.
335  *
336  * Returns: the service. use g_free() after usage.
337  */
338 gchar *
339 gst_rtsp_server_get_service (GstRTSPServer * server)
340 {
341   gchar *result;
342
343   g_return_val_if_fail (GST_IS_RTSP_SERVER (server), NULL);
344
345   GST_RTSP_SERVER_LOCK (server);
346   result = g_strdup (server->service);
347   GST_RTSP_SERVER_UNLOCK (server);
348
349   return result;
350 }
351
352 /**
353  * gst_rtsp_server_set_backlog:
354  * @server: a #GstRTSPServer
355  * @backlog: the backlog
356  *
357  * configure the maximum amount of requests that may be queued for the
358  * server.
359  *
360  * This function must be called before the server is bound.
361  */
362 void
363 gst_rtsp_server_set_backlog (GstRTSPServer * server, gint backlog)
364 {
365   g_return_if_fail (GST_IS_RTSP_SERVER (server));
366
367   GST_RTSP_SERVER_LOCK (server);
368   server->backlog = backlog;
369   GST_RTSP_SERVER_UNLOCK (server);
370 }
371
372 /**
373  * gst_rtsp_server_get_backlog:
374  * @server: a #GstRTSPServer
375  *
376  * The maximum amount of queued requests for the server.
377  *
378  * Returns: the server backlog.
379  */
380 gint
381 gst_rtsp_server_get_backlog (GstRTSPServer * server)
382 {
383   gint result;
384
385   g_return_val_if_fail (GST_IS_RTSP_SERVER (server), -1);
386
387   GST_RTSP_SERVER_LOCK (server);
388   result = server->backlog;
389   GST_RTSP_SERVER_UNLOCK (server);
390
391   return result;
392 }
393
394 /**
395  * gst_rtsp_server_set_session_pool:
396  * @server: a #GstRTSPServer
397  * @pool: a #GstRTSPSessionPool
398  *
399  * configure @pool to be used as the session pool of @server.
400  */
401 void
402 gst_rtsp_server_set_session_pool (GstRTSPServer * server,
403     GstRTSPSessionPool * pool)
404 {
405   GstRTSPSessionPool *old;
406
407   g_return_if_fail (GST_IS_RTSP_SERVER (server));
408
409   if (pool)
410     g_object_ref (pool);
411
412   GST_RTSP_SERVER_LOCK (server);
413   old = server->session_pool;
414   server->session_pool = pool;
415   GST_RTSP_SERVER_UNLOCK (server);
416
417   if (old)
418     g_object_unref (old);
419 }
420
421 /**
422  * gst_rtsp_server_get_session_pool:
423  * @server: a #GstRTSPServer
424  *
425  * Get the #GstRTSPSessionPool used as the session pool of @server.
426  *
427  * Returns: (transfer full): the #GstRTSPSessionPool used for sessions. g_object_unref() after
428  * usage.
429  */
430 GstRTSPSessionPool *
431 gst_rtsp_server_get_session_pool (GstRTSPServer * server)
432 {
433   GstRTSPSessionPool *result;
434
435   g_return_val_if_fail (GST_IS_RTSP_SERVER (server), NULL);
436
437   GST_RTSP_SERVER_LOCK (server);
438   if ((result = server->session_pool))
439     g_object_ref (result);
440   GST_RTSP_SERVER_UNLOCK (server);
441
442   return result;
443 }
444
445 /**
446  * gst_rtsp_server_set_media_mapping:
447  * @server: a #GstRTSPServer
448  * @mapping: a #GstRTSPMediaMapping
449  *
450  * configure @mapping to be used as the media mapping of @server.
451  */
452 void
453 gst_rtsp_server_set_media_mapping (GstRTSPServer * server,
454     GstRTSPMediaMapping * mapping)
455 {
456   GstRTSPMediaMapping *old;
457
458   g_return_if_fail (GST_IS_RTSP_SERVER (server));
459
460   if (mapping)
461     g_object_ref (mapping);
462
463   GST_RTSP_SERVER_LOCK (server);
464   old = server->media_mapping;
465   server->media_mapping = mapping;
466   GST_RTSP_SERVER_UNLOCK (server);
467
468   if (old)
469     g_object_unref (old);
470 }
471
472
473 /**
474  * gst_rtsp_server_get_media_mapping:
475  * @server: a #GstRTSPServer
476  *
477  * Get the #GstRTSPMediaMapping used as the media mapping of @server.
478  *
479  * Returns: (transfer full): the #GstRTSPMediaMapping of @server. g_object_unref() after
480  * usage.
481  */
482 GstRTSPMediaMapping *
483 gst_rtsp_server_get_media_mapping (GstRTSPServer * server)
484 {
485   GstRTSPMediaMapping *result;
486
487   g_return_val_if_fail (GST_IS_RTSP_SERVER (server), NULL);
488
489   GST_RTSP_SERVER_LOCK (server);
490   if ((result = server->media_mapping))
491     g_object_ref (result);
492   GST_RTSP_SERVER_UNLOCK (server);
493
494   return result;
495 }
496
497 /**
498  * gst_rtsp_server_set_auth:
499  * @server: a #GstRTSPServer
500  * @auth: a #GstRTSPAuth
501  *
502  * configure @auth to be used as the authentication manager of @server.
503  */
504 void
505 gst_rtsp_server_set_auth (GstRTSPServer * server, GstRTSPAuth * auth)
506 {
507   GstRTSPAuth *old;
508
509   g_return_if_fail (GST_IS_RTSP_SERVER (server));
510
511   if (auth)
512     g_object_ref (auth);
513
514   GST_RTSP_SERVER_LOCK (server);
515   old = server->auth;
516   server->auth = auth;
517   GST_RTSP_SERVER_UNLOCK (server);
518
519   if (old)
520     g_object_unref (old);
521 }
522
523
524 /**
525  * gst_rtsp_server_get_auth:
526  * @server: a #GstRTSPServer
527  *
528  * Get the #GstRTSPAuth used as the authentication manager of @server.
529  *
530  * Returns: (transfer full): the #GstRTSPAuth of @server. g_object_unref() after
531  * usage.
532  */
533 GstRTSPAuth *
534 gst_rtsp_server_get_auth (GstRTSPServer * server)
535 {
536   GstRTSPAuth *result;
537
538   g_return_val_if_fail (GST_IS_RTSP_SERVER (server), NULL);
539
540   GST_RTSP_SERVER_LOCK (server);
541   if ((result = server->auth))
542     g_object_ref (result);
543   GST_RTSP_SERVER_UNLOCK (server);
544
545   return result;
546 }
547
548 /**
549  * gst_rtsp_server_set_max_threads:
550  * @server: a #GstRTSPServer
551  * @max_threads: maximum threads
552  *
553  * Set the maximum threads used by the server to handle client requests.
554  * A value of 0 will use the server mainloop, a value of -1 will use an
555  * unlimited number of threads.
556  */
557 void
558 gst_rtsp_server_set_max_threads (GstRTSPServer * server, gint max_threads)
559 {
560   g_return_if_fail (GST_IS_RTSP_SERVER (server));
561
562   GST_RTSP_SERVER_LOCK (server);
563   server->max_threads = max_threads;
564   GST_RTSP_SERVER_UNLOCK (server);
565 }
566
567 /**
568  * gst_rtsp_server_get_max_threads:
569  * @server: a #GstRTSPServer
570  *
571  * Get the maximum number of threads used for client connections.
572  * See gst_rtsp_server_set_max_threads().
573  *
574  * Returns: the maximum number of threads.
575  */
576 gint
577 gst_rtsp_server_get_max_threads (GstRTSPServer * server)
578 {
579   gint res;
580
581   g_return_val_if_fail (GST_IS_RTSP_SERVER (server), -1);
582
583   GST_RTSP_SERVER_LOCK (server);
584   res = server->max_threads;
585   GST_RTSP_SERVER_UNLOCK (server);
586
587   return res;
588 }
589
590
591 static void
592 gst_rtsp_server_get_property (GObject * object, guint propid,
593     GValue * value, GParamSpec * pspec)
594 {
595   GstRTSPServer *server = GST_RTSP_SERVER (object);
596
597   switch (propid) {
598     case PROP_ADDRESS:
599       g_value_take_string (value, gst_rtsp_server_get_address (server));
600       break;
601     case PROP_SERVICE:
602       g_value_take_string (value, gst_rtsp_server_get_service (server));
603       break;
604     case PROP_BOUND_PORT:
605       g_value_set_int (value, gst_rtsp_server_get_bound_port (server));
606       break;
607     case PROP_BACKLOG:
608       g_value_set_int (value, gst_rtsp_server_get_backlog (server));
609       break;
610     case PROP_SESSION_POOL:
611       g_value_take_object (value, gst_rtsp_server_get_session_pool (server));
612       break;
613     case PROP_MEDIA_MAPPING:
614       g_value_take_object (value, gst_rtsp_server_get_media_mapping (server));
615       break;
616     case PROP_MAX_THREADS:
617       g_value_set_int (value, gst_rtsp_server_get_max_threads (server));
618       break;
619     default:
620       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, propid, pspec);
621   }
622 }
623
624 static void
625 gst_rtsp_server_set_property (GObject * object, guint propid,
626     const GValue * value, GParamSpec * pspec)
627 {
628   GstRTSPServer *server = GST_RTSP_SERVER (object);
629
630   switch (propid) {
631     case PROP_ADDRESS:
632       gst_rtsp_server_set_address (server, g_value_get_string (value));
633       break;
634     case PROP_SERVICE:
635       gst_rtsp_server_set_service (server, g_value_get_string (value));
636       break;
637     case PROP_BACKLOG:
638       gst_rtsp_server_set_backlog (server, g_value_get_int (value));
639       break;
640     case PROP_SESSION_POOL:
641       gst_rtsp_server_set_session_pool (server, g_value_get_object (value));
642       break;
643     case PROP_MEDIA_MAPPING:
644       gst_rtsp_server_set_media_mapping (server, g_value_get_object (value));
645       break;
646     case PROP_MAX_THREADS:
647       gst_rtsp_server_set_max_threads (server, g_value_get_int (value));
648       break;
649     default:
650       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, propid, pspec);
651   }
652 }
653
654 /**
655  * gst_rtsp_server_create_socket:
656  * @server: a #GstRTSPServer
657  * @cancellable: a #GCancellable
658  * @error: a #GError
659  *
660  * Create a #GSocket for @server. The socket will listen on the
661  * configured service.
662  *
663  * Returns: (transfer full): the #GSocket for @server or NULL when an error occured.
664  */
665 GSocket *
666 gst_rtsp_server_create_socket (GstRTSPServer * server,
667     GCancellable * cancellable, GError ** error)
668 {
669   GSocketConnectable *conn;
670   GSocketAddressEnumerator *enumerator;
671   GSocket *socket = NULL;
672 #ifdef USE_SOLINGER
673   struct linger linger;
674 #endif
675   GError *sock_error = NULL;
676   GError *bind_error = NULL;
677   guint16 port;
678
679   g_return_val_if_fail (GST_IS_RTSP_SERVER (server), NULL);
680
681   GST_RTSP_SERVER_LOCK (server);
682   GST_DEBUG_OBJECT (server, "getting address info of %s/%s", server->address,
683       server->service);
684
685   /* resolve the server IP address */
686   port = atoi (server->service);
687   if (port != 0 || !strcmp (server->service, "0"))
688     conn = g_network_address_new (server->address, port);
689   else
690     conn = g_network_service_new (server->service, "tcp", server->address);
691
692   enumerator = g_socket_connectable_enumerate (conn);
693   g_object_unref (conn);
694
695   /* create server socket, we loop through all the addresses until we manage to
696    * create a socket and bind. */
697   while (TRUE) {
698     GSocketAddress *sockaddr;
699
700     sockaddr =
701         g_socket_address_enumerator_next (enumerator, cancellable, error);
702     if (!sockaddr) {
703       if (!*error)
704         GST_DEBUG_OBJECT (server, "no more addresses %s",
705             *error ? (*error)->message : "");
706       else
707         GST_DEBUG_OBJECT (server, "failed to retrieve next address %s",
708             (*error)->message);
709       break;
710     }
711
712     /* only keep the first error */
713     socket = g_socket_new (g_socket_address_get_family (sockaddr),
714         G_SOCKET_TYPE_STREAM, G_SOCKET_PROTOCOL_TCP,
715         sock_error ? NULL : &sock_error);
716
717     if (socket == NULL) {
718       GST_DEBUG_OBJECT (server, "failed to make socket (%s), try next",
719           sock_error->message);
720       continue;
721     }
722
723     if (g_socket_bind (socket, sockaddr, TRUE, bind_error ? NULL : &bind_error)) {
724       g_object_unref (sockaddr);
725       break;
726     }
727
728     GST_DEBUG_OBJECT (server, "failed to bind socket (%s), try next",
729         bind_error->message);
730     g_object_unref (sockaddr);
731     g_object_unref (socket);
732     socket = NULL;
733   }
734   g_object_unref (enumerator);
735
736   if (socket == NULL)
737     goto no_socket;
738
739   g_clear_error (&sock_error);
740   g_clear_error (&bind_error);
741
742   GST_DEBUG_OBJECT (server, "opened sending server socket");
743
744   /* keep connection alive; avoids SIGPIPE during write */
745   g_socket_set_keepalive (socket, TRUE);
746
747 #if 0
748 #ifdef USE_SOLINGER
749   /* make sure socket is reset 5 seconds after close. This ensure that we can
750    * reuse the socket quickly while still having a chance to send data to the
751    * client. */
752   linger.l_onoff = 1;
753   linger.l_linger = 5;
754   if (setsockopt (sockfd, SOL_SOCKET, SO_LINGER,
755           (void *) &linger, sizeof (linger)) < 0)
756     goto linger_failed;
757 #endif
758 #endif
759
760   /* set the server socket to nonblocking */
761   g_socket_set_blocking (socket, FALSE);
762
763   /* set listen backlog */
764   g_socket_set_listen_backlog (socket, server->backlog);
765
766   if (!g_socket_listen (socket, error))
767     goto listen_failed;
768
769   GST_DEBUG_OBJECT (server, "listening on server socket %p with queue of %d",
770       socket, server->backlog);
771
772   GST_RTSP_SERVER_UNLOCK (server);
773
774   return socket;
775
776   /* ERRORS */
777 no_socket:
778   {
779     GST_ERROR_OBJECT (server, "failed to create socket");
780     goto close_error;
781   }
782 #if 0
783 #ifdef USE_SOLINGER
784 linger_failed:
785   {
786     GST_ERROR_OBJECT (server, "failed to no linger socket: %s",
787         g_strerror (errno));
788     goto close_error;
789   }
790 #endif
791 #endif
792 listen_failed:
793   {
794     GST_ERROR_OBJECT (server, "failed to listen on socket: %s",
795         (*error)->message);
796     goto close_error;
797   }
798 close_error:
799   {
800     if (socket)
801       g_object_unref (socket);
802
803     if (sock_error) {
804       if (error == NULL)
805         g_propagate_error (error, sock_error);
806       else
807         g_error_free (sock_error);
808     }
809     if (bind_error) {
810       if ((error == NULL) || (*error == NULL))
811         g_propagate_error (error, bind_error);
812       else
813         g_error_free (bind_error);
814     }
815     GST_RTSP_SERVER_UNLOCK (server);
816     return NULL;
817   }
818 }
819
820 struct _ClientContext
821 {
822   GstRTSPServer *server;
823   GMainLoop *loop;
824   GMainContext *context;
825   GstRTSPClient *client;
826 };
827
828 static void
829 free_client_context (ClientContext * ctx)
830 {
831   g_main_context_unref (ctx->context);
832   if (ctx->loop)
833     g_main_loop_unref (ctx->loop);
834   g_object_unref (ctx->client);
835   g_slice_free (ClientContext, ctx);
836 }
837
838 static gpointer
839 do_loop (ClientContext * ctx)
840 {
841   GST_INFO ("enter mainloop");
842   g_main_loop_run (ctx->loop);
843   GST_INFO ("exit mainloop");
844
845   free_client_context (ctx);
846
847   return NULL;
848 }
849
850 static void
851 unmanage_client (GstRTSPClient * client, ClientContext * ctx)
852 {
853   GstRTSPServer *server = ctx->server;
854
855   GST_DEBUG_OBJECT (server, "unmanage client %p", client);
856
857   g_object_ref (server);
858   gst_rtsp_client_set_server (client, NULL);
859
860   GST_RTSP_SERVER_LOCK (server);
861   server->clients = g_list_remove (server->clients, ctx);
862   GST_RTSP_SERVER_UNLOCK (server);
863
864   if (ctx->loop)
865     g_main_loop_quit (ctx->loop);
866   else
867     free_client_context (ctx);
868
869   g_object_unref (server);
870 }
871
872 /* add the client context to the active list of clients, takes ownership
873  * of client */
874 static void
875 manage_client (GstRTSPServer * server, GstRTSPClient * client)
876 {
877   ClientContext *ctx;
878
879   GST_DEBUG_OBJECT (server, "manage client %p", client);
880   gst_rtsp_client_set_server (client, server);
881
882   ctx = g_slice_new0 (ClientContext);
883   ctx->server = server;
884   ctx->client = client;
885   if (server->max_threads == 0) {
886     GSource *source;
887
888     /* find the context to add the watch */
889     if ((source = g_main_current_source ()))
890       ctx->context = g_main_context_ref (g_source_get_context (source));
891     else
892       ctx->context = NULL;
893   } else {
894     ctx->context = g_main_context_new ();
895     ctx->loop = g_main_loop_new (ctx->context, TRUE);
896   }
897   gst_rtsp_client_attach (client, ctx->context);
898
899   GST_RTSP_SERVER_LOCK (server);
900   g_signal_connect (client, "closed", (GCallback) unmanage_client, ctx);
901   server->clients = g_list_prepend (server->clients, ctx);
902   GST_RTSP_SERVER_UNLOCK (server);
903
904   if (ctx->loop) {
905     GstRTSPServerClass *klass = GST_RTSP_SERVER_GET_CLASS (server);
906
907     g_thread_pool_push (klass->pool, ctx, NULL);
908   }
909 }
910
911 static GstRTSPClient *
912 default_create_client (GstRTSPServer * server)
913 {
914   GstRTSPClient *client;
915
916   /* a new client connected, create a session to handle the client. */
917   client = gst_rtsp_client_new ();
918
919   /* set the session pool that this client should use */
920   GST_RTSP_SERVER_LOCK (server);
921   gst_rtsp_client_set_session_pool (client, server->session_pool);
922   /* set the media mapping that this client should use */
923   gst_rtsp_client_set_media_mapping (client, server->media_mapping);
924   /* set authentication manager */
925   gst_rtsp_client_set_auth (client, server->auth);
926   GST_RTSP_SERVER_UNLOCK (server);
927
928   return client;
929 }
930
931 /* default method for creating a new client object in the server to accept and
932  * handle a client connection on this server */
933 static gboolean
934 default_accept_client (GstRTSPServer * server, GstRTSPClient * client,
935     GSocket * socket, GError ** error)
936 {
937   /* accept connections for that client, this function returns after accepting
938    * the connection and will run the remainder of the communication with the
939    * client asyncronously. */
940   if (!gst_rtsp_client_accept (client, socket, NULL, error))
941     goto accept_failed;
942
943   return TRUE;
944
945   /* ERRORS */
946 accept_failed:
947   {
948     GST_ERROR_OBJECT (server,
949         "Could not accept client on server : %s", (*error)->message);
950     return FALSE;
951   }
952 }
953
954 /**
955  * gst_rtsp_server_transfer_connection:
956  * @server: a #GstRTSPServer
957  * @socket: a network socket
958  * @ip: the IP address of the remote client
959  * @port: the port used by the other end
960  * @initial_buffer: any initial data that was already read from the socket
961  *
962  * Take an existing network socket and use it for an RTSP connection. This
963  * is used when transferring a socket from an HTTP server which should be used
964  * as an RTSP over HTTP tunnel. The @initial_buffer contains any remaining data
965  * that the HTTP server read from the socket while parsing the HTTP header.
966  *
967  * Returns: TRUE if all was ok, FALSE if an error occured.
968  */
969 gboolean
970 gst_rtsp_server_transfer_connection (GstRTSPServer * server, GSocket * socket,
971     const gchar * ip, gint port, const gchar * initial_buffer)
972 {
973   GstRTSPClient *client = NULL;
974   GstRTSPServerClass *klass;
975   GError *error = NULL;
976
977   klass = GST_RTSP_SERVER_GET_CLASS (server);
978
979   if (klass->create_client)
980     client = klass->create_client (server);
981   if (client == NULL)
982     goto client_failed;
983
984   /* a new client connected, create a client object to handle the client. */
985   if (!gst_rtsp_client_use_socket (client, socket, ip,
986           port, initial_buffer, &error)) {
987     goto transfer_failed;
988   }
989
990   /* manage the client connection */
991   manage_client (server, client);
992
993   g_signal_emit (server, gst_rtsp_server_signals[SIGNAL_CLIENT_CONNECTED], 0,
994       client);
995
996   return TRUE;
997
998   /* ERRORS */
999 client_failed:
1000   {
1001     GST_ERROR_OBJECT (server, "failed to create a client");
1002     return FALSE;
1003   }
1004 transfer_failed:
1005   {
1006     GST_ERROR_OBJECT (server, "failed to accept client: %s", error->message);
1007     g_error_free (error);
1008     g_object_unref (client);
1009     return FALSE;
1010   }
1011 }
1012
1013 /**
1014  * gst_rtsp_server_io_func:
1015  * @socket: a #GSocket
1016  * @condition: the condition on @source
1017  * @server: a #GstRTSPServer
1018  *
1019  * A default #GSocketSourceFunc that creates a new #GstRTSPClient to accept and handle a
1020  * new connection on @socket or @server.
1021  *
1022  * Returns: TRUE if the source could be connected, FALSE if an error occured.
1023  */
1024 gboolean
1025 gst_rtsp_server_io_func (GSocket * socket, GIOCondition condition,
1026     GstRTSPServer * server)
1027 {
1028   gboolean result = TRUE;
1029   GstRTSPClient *client = NULL;
1030   GstRTSPServerClass *klass;
1031   GError *error = NULL;
1032
1033   if (condition & G_IO_IN) {
1034     klass = GST_RTSP_SERVER_GET_CLASS (server);
1035
1036     if (klass->create_client)
1037       client = klass->create_client (server);
1038     if (client == NULL)
1039       goto client_failed;
1040
1041     /* a new client connected, create a client object to handle the client. */
1042     if (klass->accept_client)
1043       result = klass->accept_client (server, client, socket, &error);
1044     if (!result)
1045       goto accept_failed;
1046
1047     /* manage the client connection */
1048     manage_client (server, client);
1049
1050     g_signal_emit (server, gst_rtsp_server_signals[SIGNAL_CLIENT_CONNECTED], 0,
1051         client);
1052   } else {
1053     GST_WARNING_OBJECT (server, "received unknown event %08x", condition);
1054   }
1055   return TRUE;
1056
1057   /* ERRORS */
1058 client_failed:
1059   {
1060     GST_ERROR_OBJECT (server, "failed to create a client");
1061     return FALSE;
1062   }
1063 accept_failed:
1064   {
1065     GST_ERROR_OBJECT (server, "failed to accept client: %s", error->message);
1066     g_error_free (error);
1067     g_object_unref (client);
1068     return FALSE;
1069   }
1070 }
1071
1072 static void
1073 watch_destroyed (GstRTSPServer * server)
1074 {
1075   GST_DEBUG_OBJECT (server, "source destroyed");
1076   g_object_unref (server);
1077 }
1078
1079 /**
1080  * gst_rtsp_server_create_source:
1081  * @server: a #GstRTSPServer
1082  * @cancellable: a #GCancellable or %NULL.
1083  * @error: a #GError
1084  *
1085  * Create a #GSource for @server. The new source will have a default
1086  * #GSocketSourceFunc of gst_rtsp_server_io_func().
1087  *
1088  * @cancellable if not NULL can be used to cancel the source, which will cause
1089  * the source to trigger, reporting the current condition (which is likely 0
1090  * unless cancellation happened at the same time as a condition change). You can
1091  * check for this in the callback using g_cancellable_is_cancelled().
1092  *
1093  * Returns: the #GSource for @server or NULL when an error occured. Free with
1094  * g_source_unref ()
1095  */
1096 GSource *
1097 gst_rtsp_server_create_source (GstRTSPServer * server,
1098     GCancellable * cancellable, GError ** error)
1099 {
1100   GSocket *socket, *old;
1101   GSource *source;
1102
1103   g_return_val_if_fail (GST_IS_RTSP_SERVER (server), NULL);
1104
1105   socket = gst_rtsp_server_create_socket (server, NULL, error);
1106   if (socket == NULL)
1107     goto no_socket;
1108
1109   GST_RTSP_SERVER_LOCK (server);
1110   old = server->socket;
1111   server->socket = g_object_ref (socket);
1112   GST_RTSP_SERVER_UNLOCK (server);
1113
1114   if (old)
1115     g_object_unref (old);
1116
1117   /* create a watch for reads (new connections) and possible errors */
1118   source = g_socket_create_source (socket, G_IO_IN |
1119       G_IO_ERR | G_IO_HUP | G_IO_NVAL, cancellable);
1120   g_object_unref (socket);
1121
1122   /* configure the callback */
1123   g_source_set_callback (source,
1124       (GSourceFunc) gst_rtsp_server_io_func, g_object_ref (server),
1125       (GDestroyNotify) watch_destroyed);
1126
1127   return source;
1128
1129 no_socket:
1130   {
1131     GST_ERROR_OBJECT (server, "failed to create socket");
1132     return NULL;
1133   }
1134 }
1135
1136 /**
1137  * gst_rtsp_server_attach:
1138  * @server: a #GstRTSPServer
1139  * @context: (allow-none): a #GMainContext
1140  *
1141  * Attaches @server to @context. When the mainloop for @context is run, the
1142  * server will be dispatched. When @context is NULL, the default context will be
1143  * used).
1144  *
1145  * This function should be called when the server properties and urls are fully
1146  * configured and the server is ready to start.
1147  *
1148  * Returns: the ID (greater than 0) for the source within the GMainContext.
1149  */
1150 guint
1151 gst_rtsp_server_attach (GstRTSPServer * server, GMainContext * context)
1152 {
1153   guint res;
1154   GSource *source;
1155   GError *error = NULL;
1156
1157   g_return_val_if_fail (GST_IS_RTSP_SERVER (server), 0);
1158
1159   source = gst_rtsp_server_create_source (server, NULL, &error);
1160   if (source == NULL)
1161     goto no_source;
1162
1163   res = g_source_attach (source, context);
1164   g_source_unref (source);
1165
1166   return res;
1167
1168   /* ERRORS */
1169 no_source:
1170   {
1171     GST_ERROR_OBJECT (server, "failed to create watch: %s", error->message);
1172     g_error_free (error);
1173     return 0;
1174   }
1175 }