Merge branch 'fd-passing'
[platform/upstream/dbus.git] / dbus / dbus-server-socket.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-server-socket.c Server implementation for sockets
3  *
4  * Copyright (C) 2002, 2003, 2004, 2006  Red Hat Inc.
5  *
6  * Licensed under the Academic Free License version 2.1
7  * 
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  * 
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
21  *
22  */
23
24 #include "dbus-internals.h"
25 #include "dbus-server-socket.h"
26 #include "dbus-transport-socket.h"
27 #include "dbus-connection-internal.h"
28 #include "dbus-string.h"
29
30 /**
31  * @defgroup DBusServerSocket DBusServer implementations for SOCKET
32  * @ingroup  DBusInternals
33  * @brief Implementation details of DBusServer on SOCKET
34  *
35  * @{
36  */
37 /**
38  * 
39  * Opaque object representing a Socket server implementation.
40  */
41 typedef struct DBusServerSocket DBusServerSocket;
42
43 /**
44  * Implementation details of DBusServerSocket. All members
45  * are private.
46  */
47 struct DBusServerSocket
48 {
49   DBusServer base;   /**< Parent class members. */
50   int n_fds;         /**< Number of active file handles */
51   int *fds;          /**< File descriptor or -1 if disconnected. */
52   DBusWatch **watch; /**< File descriptor watch. */
53   char *socket_name; /**< Name of domain socket, to unlink if appropriate */
54 };
55
56 static void
57 socket_finalize (DBusServer *server)
58 {
59   DBusServerSocket *socket_server = (DBusServerSocket*) server;
60   int i;
61   
62   _dbus_server_finalize_base (server);
63
64   for (i = 0 ; i < socket_server->n_fds ; i++)
65     if (socket_server->watch[i])
66       {
67         _dbus_watch_unref (socket_server->watch[i]);
68         socket_server->watch[i] = NULL;
69       }
70   
71   dbus_free (socket_server->fds);
72   dbus_free (socket_server->watch);
73   dbus_free (socket_server->socket_name);
74   dbus_free (server);
75 }
76
77 /* Return value is just for memory, not other failures. */
78 static dbus_bool_t
79 handle_new_client_fd_and_unlock (DBusServer *server,
80                                  int         client_fd)
81 {
82   DBusConnection *connection;
83   DBusTransport *transport;
84   DBusNewConnectionFunction new_connection_function;
85   void *new_connection_data;
86   
87   _dbus_verbose ("Creating new client connection with fd %d\n", client_fd);
88
89   HAVE_LOCK_CHECK (server);
90   
91   if (!_dbus_set_fd_nonblocking (client_fd, NULL))
92     {
93       SERVER_UNLOCK (server);
94       return TRUE;
95     }
96   
97   transport = _dbus_transport_new_for_socket (client_fd, &server->guid_hex, NULL);
98   if (transport == NULL)
99     {
100       _dbus_close_socket (client_fd, NULL);
101       SERVER_UNLOCK (server);
102       return FALSE;
103     }
104
105   if (!_dbus_transport_set_auth_mechanisms (transport,
106                                             (const char **) server->auth_mechanisms))
107     {
108       _dbus_transport_unref (transport);
109       SERVER_UNLOCK (server);
110       return FALSE;
111     }
112   
113   /* note that client_fd is now owned by the transport, and will be
114    * closed on transport disconnection/finalization
115    */
116   
117   connection = _dbus_connection_new_for_transport (transport);
118   _dbus_transport_unref (transport);
119   transport = NULL; /* now under the connection lock */
120   
121   if (connection == NULL)
122     {
123       SERVER_UNLOCK (server);
124       return FALSE;
125     }
126   
127   /* See if someone wants to handle this new connection, self-referencing
128    * for paranoia.
129    */
130   new_connection_function = server->new_connection_function;
131   new_connection_data = server->new_connection_data;
132
133   _dbus_server_ref_unlocked (server);
134   SERVER_UNLOCK (server);
135   
136   if (new_connection_function)
137     {
138       (* new_connection_function) (server, connection,
139                                    new_connection_data);
140     }
141   dbus_server_unref (server);
142   
143   /* If no one grabbed a reference, the connection will die. */
144   _dbus_connection_close_if_only_one_ref (connection);
145   dbus_connection_unref (connection);
146
147   return TRUE;
148 }
149
150 static dbus_bool_t
151 socket_handle_watch (DBusWatch    *watch,
152                    unsigned int  flags,
153                    void         *data)
154 {
155   DBusServer *server = data;
156 #ifndef DBUS_DISABLE_ASSERT
157   DBusServerSocket *socket_server = data;
158   int i;
159   dbus_bool_t found = FALSE;
160 #endif
161
162   SERVER_LOCK (server);
163   
164 #ifndef DBUS_DISABLE_ASSERT
165   for (i = 0 ; i < socket_server->n_fds ; i++)
166     {
167       if (socket_server->watch[i] == watch)
168         found = TRUE;
169     }
170   _dbus_assert (found);
171 #endif
172
173   _dbus_verbose ("Handling client connection, flags 0x%x\n", flags);
174   
175   if (flags & DBUS_WATCH_READABLE)
176     {
177       int client_fd;
178       int listen_fd;
179       
180       listen_fd = dbus_watch_get_socket (watch);
181
182       client_fd = _dbus_accept (listen_fd);
183       
184       if (client_fd < 0)
185         {
186           /* EINTR handled for us */
187           
188           if (_dbus_get_is_errno_eagain_or_ewouldblock ())
189             _dbus_verbose ("No client available to accept after all\n");
190           else
191             _dbus_verbose ("Failed to accept a client connection: %s\n",
192                            _dbus_strerror_from_errno ());
193
194           SERVER_UNLOCK (server);
195         }
196       else
197         {
198           if (!handle_new_client_fd_and_unlock (server, client_fd))
199             _dbus_verbose ("Rejected client connection due to lack of memory\n");
200         }
201     }
202
203   if (flags & DBUS_WATCH_ERROR)
204     _dbus_verbose ("Error on server listening socket\n");
205
206   if (flags & DBUS_WATCH_HANGUP)
207     _dbus_verbose ("Hangup on server listening socket\n");
208
209   return TRUE;
210 }
211   
212 static void
213 socket_disconnect (DBusServer *server)
214 {
215   DBusServerSocket *socket_server = (DBusServerSocket*) server;
216   int i;
217
218   HAVE_LOCK_CHECK (server);
219   
220   for (i = 0 ; i < socket_server->n_fds ; i++)
221     {
222       if (socket_server->watch[i])
223         {
224           _dbus_server_remove_watch (server,
225                                      socket_server->watch[i]);
226           _dbus_watch_unref (socket_server->watch[i]);
227           socket_server->watch[i] = NULL;
228         }
229
230       _dbus_close_socket (socket_server->fds[i], NULL);
231       socket_server->fds[i] = -1;
232     }
233
234   if (socket_server->socket_name != NULL)
235     {
236       DBusString tmp;
237       _dbus_string_init_const (&tmp, socket_server->socket_name);
238       _dbus_delete_file (&tmp, NULL);
239     }
240
241   HAVE_LOCK_CHECK (server);
242 }
243
244 static const DBusServerVTable socket_vtable = {
245   socket_finalize,
246   socket_disconnect
247 };
248
249 /**
250  * Creates a new server listening on the given file descriptor.  The
251  * file descriptor should be nonblocking (use
252  * _dbus_set_fd_nonblocking() to make it so). The file descriptor
253  * should be listening for connections, that is, listen() should have
254  * been successfully invoked on it. The server will use accept() to
255  * accept new client connections.
256  *
257  * @param fds list of file descriptors.
258  * @param n_fds number of file descriptors
259  * @param address the server's address
260  * @returns the new server, or #NULL if no memory.
261  * 
262  */
263 DBusServer*
264 _dbus_server_new_for_socket (int              *fds,
265                              int               n_fds,
266                              const DBusString *address)
267 {
268   DBusServerSocket *socket_server;
269   DBusServer *server;
270   int i;
271   
272   socket_server = dbus_new0 (DBusServerSocket, 1);
273   if (socket_server == NULL)
274     return NULL;
275
276   socket_server->fds = dbus_new (int, n_fds);
277   if (!socket_server->fds)
278     goto failed_0;
279
280   socket_server->watch = dbus_new0 (DBusWatch *, n_fds);
281   if (!socket_server->watch)
282     goto failed_1;
283
284   for (i = 0 ; i < n_fds ; i++)
285     {
286       DBusWatch *watch;
287
288       watch = _dbus_watch_new (fds[i],
289                                DBUS_WATCH_READABLE,
290                                TRUE,
291                                socket_handle_watch, socket_server,
292                                NULL);
293       if (watch == NULL)
294         goto failed_2;
295
296       socket_server->n_fds++;
297       socket_server->fds[i] = fds[i];
298       socket_server->watch[i] = watch;
299     }
300
301   if (!_dbus_server_init_base (&socket_server->base,
302                                &socket_vtable, address))
303     goto failed_2;
304
305   server = (DBusServer*)socket_server;
306
307   SERVER_LOCK (server);
308   
309   for (i = 0 ; i < n_fds ; i++)
310     {
311       if (!_dbus_server_add_watch (&socket_server->base,
312                                    socket_server->watch[i]))
313         {
314           int j;
315           for (j = 0 ; j < i ; j++)
316             _dbus_server_remove_watch (server,
317                                        socket_server->watch[j]);
318
319           SERVER_UNLOCK (server);
320           _dbus_server_finalize_base (&socket_server->base);
321           goto failed_2;
322         }
323     }
324
325   SERVER_UNLOCK (server);
326   
327   return (DBusServer*) socket_server;
328
329  failed_2:
330   for (i = 0 ; i < n_fds ; i++)
331     {
332       if (socket_server->watch[i] != NULL)
333         {
334           _dbus_watch_unref (socket_server->watch[i]);
335           socket_server->watch[i] = NULL;
336         }
337     }
338   dbus_free (socket_server->watch);
339
340  failed_1:
341   dbus_free (socket_server->fds);
342
343  failed_0:
344   dbus_free (socket_server);
345   return NULL;
346 }
347
348 /**
349  * Creates a new server listening on TCP.
350  * If host is NULL, it will default to localhost.
351  * If bind is NULL, it will default to the value for the host
352  * parameter, and if that is NULL, then localhost
353  * If bind is a hostname, it will be resolved and will listen
354  * on all returned addresses.
355  * If family is NULL, hostname resolution will try all address
356  * families, otherwise it can be ipv4 or ipv6 to restrict the
357  * addresses considered.
358  *
359  * @param host the hostname to report for the listen address
360  * @param bind the hostname to listen on
361  * @param port the port to listen on or 0 to let the OS choose
362  * @param family 
363  * @param error location to store reason for failure.
364  * @returns the new server, or #NULL on failure.
365  */
366 DBusServer*
367 _dbus_server_new_for_tcp_socket (const char     *host,
368                                  const char     *bind,
369                                  const char     *port,
370                                  const char     *family,
371                                  DBusError      *error)
372 {
373   DBusServer *server;
374   int *listen_fds = NULL;
375   int nlisten_fds = 0, i;
376   DBusString address;
377   DBusString host_str;
378   DBusString port_str;
379   
380   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
381
382   if (!_dbus_string_init (&address))
383     {
384       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
385       return NULL;
386     }
387
388   if (!_dbus_string_init (&port_str))
389     {
390       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
391       goto failed_0;
392     }
393
394   if (host == NULL)
395     host = "localhost";
396
397   if (port == NULL)
398     port = "0";
399
400   if (bind == NULL)
401     bind = host;
402   else if (strcmp (bind, "*") == 0)
403     bind = NULL;
404
405   nlisten_fds =_dbus_listen_tcp_socket (bind, port, family,
406                                         &port_str,
407                                         &listen_fds, error);
408   if (nlisten_fds <= 0)
409     {
410       _DBUS_ASSERT_ERROR_IS_SET(error);
411       goto failed_1;
412     }
413
414   _dbus_string_init_const (&host_str, host);
415   if (!_dbus_string_append (&address, "tcp:host=") ||
416       !_dbus_address_append_escaped (&address, &host_str) ||
417       !_dbus_string_append (&address, ",port=") ||
418       !_dbus_string_append (&address, _dbus_string_get_const_data(&port_str)))
419     {
420       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
421       goto failed_2;
422     }
423   if (family &&
424       (!_dbus_string_append (&address, ",family=") ||
425        !_dbus_string_append (&address, family)))
426     {
427       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
428       goto failed_2;
429     }
430   
431   server = _dbus_server_new_for_socket (listen_fds, nlisten_fds, &address);
432   if (server == NULL)
433     {
434       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
435       goto failed_2;
436     }
437
438   _dbus_string_free (&port_str);
439   _dbus_string_free (&address);
440   dbus_free(listen_fds);
441
442   return server;
443
444  failed_2:
445   for (i = 0 ; i < nlisten_fds ; i++)
446     _dbus_close_socket (listen_fds[i], NULL);
447   dbus_free(listen_fds);
448
449  failed_1:
450   _dbus_string_free (&port_str);
451
452  failed_0:
453   _dbus_string_free (&address);
454
455   return NULL;
456 }
457
458 /**
459  * Tries to interpret the address entry for various socket-related
460  * addresses (well, currently only tcp).
461  * 
462  * Sets error if the result is not OK.
463  * 
464  * @param entry an address entry
465  * @param server_p a new DBusServer, or #NULL on failure.
466  * @param error location to store rationale for failure on bad address
467  * @returns the outcome
468  * 
469  */
470 DBusServerListenResult
471 _dbus_server_listen_socket (DBusAddressEntry *entry,
472                             DBusServer      **server_p,
473                             DBusError        *error)
474 {
475   const char *method;
476
477   *server_p = NULL;
478   
479   method = dbus_address_entry_get_method (entry);
480   
481   if (strcmp (method, "tcp") == 0)
482     {
483       const char *host;
484       const char *port;
485       const char *bind;
486       const char *family;
487
488       host = dbus_address_entry_get_value (entry, "host");
489       bind = dbus_address_entry_get_value (entry, "bind");
490       port = dbus_address_entry_get_value (entry, "port");
491       family = dbus_address_entry_get_value (entry, "family");
492
493       *server_p = _dbus_server_new_for_tcp_socket (host, bind, port,
494                                                    family, error);
495
496       if (*server_p)
497         {
498           _DBUS_ASSERT_ERROR_IS_CLEAR(error);
499           return DBUS_SERVER_LISTEN_OK;
500         }
501       else
502         {
503           _DBUS_ASSERT_ERROR_IS_SET(error);
504           return DBUS_SERVER_LISTEN_DID_NOT_CONNECT;
505         }
506     }
507   else
508     {
509       _DBUS_ASSERT_ERROR_IS_CLEAR(error);
510       return DBUS_SERVER_LISTEN_NOT_HANDLED;
511     }
512 }
513
514 /**
515  * This is a bad hack since it's really unix domain socket
516  * specific. Also, the function weirdly adopts ownership
517  * of the passed-in string.
518  * 
519  * @param server a socket server
520  * @param filename socket filename to report/delete
521  * 
522  */
523 void
524 _dbus_server_socket_own_filename (DBusServer *server,
525                                   char       *filename)
526 {
527   DBusServerSocket *socket_server = (DBusServerSocket*) server;
528
529   socket_server->socket_name = filename;
530 }
531
532
533 /** @} */
534