added dbus support
[monky] / src / 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  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           _dbus_fd_set_close_on_exec (client_fd);         
199
200           if (!handle_new_client_fd_and_unlock (server, client_fd))
201             _dbus_verbose ("Rejected client connection due to lack of memory\n");
202         }
203     }
204
205   if (flags & DBUS_WATCH_ERROR)
206     _dbus_verbose ("Error on server listening socket\n");
207
208   if (flags & DBUS_WATCH_HANGUP)
209     _dbus_verbose ("Hangup on server listening socket\n");
210
211   return TRUE;
212 }
213   
214 static void
215 socket_disconnect (DBusServer *server)
216 {
217   DBusServerSocket *socket_server = (DBusServerSocket*) server;
218   int i;
219
220   HAVE_LOCK_CHECK (server);
221   
222   for (i = 0 ; i < socket_server->n_fds ; i++)
223     {
224       if (socket_server->watch[i])
225         {
226           _dbus_server_remove_watch (server,
227                                      socket_server->watch[i]);
228           _dbus_watch_unref (socket_server->watch[i]);
229           socket_server->watch[i] = NULL;
230         }
231
232       _dbus_close_socket (socket_server->fds[i], NULL);
233       socket_server->fds[i] = -1;
234     }
235
236   if (socket_server->socket_name != NULL)
237     {
238       DBusString tmp;
239       _dbus_string_init_const (&tmp, socket_server->socket_name);
240       _dbus_delete_file (&tmp, NULL);
241     }
242
243   HAVE_LOCK_CHECK (server);
244 }
245
246 static const DBusServerVTable socket_vtable = {
247   socket_finalize,
248   socket_disconnect
249 };
250
251 /**
252  * Creates a new server listening on the given file descriptor.  The
253  * file descriptor should be nonblocking (use
254  * _dbus_set_fd_nonblocking() to make it so). The file descriptor
255  * should be listening for connections, that is, listen() should have
256  * been successfully invoked on it. The server will use accept() to
257  * accept new client connections.
258  *
259  * @param fds list of file descriptors.
260  * @param n_fds number of file descriptors
261  * @param address the server's address
262  * @returns the new server, or #NULL if no memory.
263  * 
264  */
265 DBusServer*
266 _dbus_server_new_for_socket (int              *fds,
267                              int               n_fds,
268                              const DBusString *address)
269 {
270   DBusServerSocket *socket_server;
271   DBusServer *server;
272   int i;
273   
274   socket_server = dbus_new0 (DBusServerSocket, 1);
275   if (socket_server == NULL)
276     return NULL;
277
278   socket_server->fds = dbus_new (int, n_fds);
279   if (!socket_server->fds)
280     goto failed_0;
281
282   socket_server->watch = dbus_new0 (DBusWatch *, n_fds);
283   if (!socket_server->watch)
284     goto failed_1;
285
286   for (i = 0 ; i < n_fds ; i++)
287     {
288       DBusWatch *watch;
289
290       watch = _dbus_watch_new (fds[i],
291                                DBUS_WATCH_READABLE,
292                                TRUE,
293                                socket_handle_watch, socket_server,
294                                NULL);
295       if (watch == NULL)
296         goto failed_2;
297
298       socket_server->n_fds++;
299       socket_server->fds[i] = fds[i];
300       socket_server->watch[i] = watch;
301     }
302
303   if (!_dbus_server_init_base (&socket_server->base,
304                                &socket_vtable, address))
305     goto failed_2;
306
307   server = (DBusServer*)socket_server;
308
309   SERVER_LOCK (server);
310   
311   for (i = 0 ; i < n_fds ; i++)
312     {
313       if (!_dbus_server_add_watch (&socket_server->base,
314                                    socket_server->watch[i]))
315         {
316           int j;
317           for (j = 0 ; j < i ; j++)
318             _dbus_server_remove_watch (server,
319                                        socket_server->watch[j]);
320
321           SERVER_UNLOCK (server);
322           _dbus_server_finalize_base (&socket_server->base);
323           goto failed_2;
324         }
325     }
326
327   SERVER_UNLOCK (server);
328   
329   return (DBusServer*) socket_server;
330
331  failed_2:
332   for (i = 0 ; i < n_fds ; i++)
333     {
334       if (socket_server->watch[i] != NULL)
335         {
336           _dbus_watch_unref (socket_server->watch[i]);
337           socket_server->watch[i] = NULL;
338         }
339     }
340   dbus_free (socket_server->watch);
341
342  failed_1:
343   dbus_free (socket_server->fds);
344
345  failed_0:
346   dbus_free (socket_server);
347   return NULL;
348 }
349
350 /**
351  * Creates a new server listening on TCP.
352  * If host is NULL, it will default to localhost.
353  * If bind is NULL, it will default to the value for the host
354  * parameter, and if that is NULL, then localhost
355  * If bind is a hostname, it will be resolved and will listen
356  * on all returned addresses.
357  * If family is NULL, hostname resolution will try all address
358  * families, otherwise it can be ipv4 or ipv6 to restrict the
359  * addresses considered.
360  *
361  * @param host the hostname to report for the listen address
362  * @param bind the hostname to listen on
363  * @param port the port to listen on or 0 to let the OS choose
364  * @param family 
365  * @param error location to store reason for failure.
366  * @returns the new server, or #NULL on failure.
367  */
368 DBusServer*
369 _dbus_server_new_for_tcp_socket (const char     *host,
370                                  const char     *bind,
371                                  const char     *port,
372                                  const char     *family,
373                                  DBusError      *error)
374 {
375   DBusServer *server;
376   int *listen_fds = NULL;
377   int nlisten_fds = 0, i;
378   DBusString address;
379   DBusString host_str;
380   DBusString port_str;
381   
382   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
383
384   if (!_dbus_string_init (&address))
385     {
386       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
387       return NULL;
388     }
389
390   if (!_dbus_string_init (&port_str))
391     {
392       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
393       goto failed_0;
394     }
395
396   if (host == NULL)
397     host = "localhost";
398
399   if (port == NULL)
400     port = "0";
401
402   if (bind == NULL)
403     bind = host;
404   else if (strcmp (bind, "*") == 0)
405     bind = NULL;
406
407   nlisten_fds =_dbus_listen_tcp_socket (bind, port, family,
408                                         &port_str,
409                                         &listen_fds, error);
410   if (nlisten_fds <= 0)
411     {
412       _DBUS_ASSERT_ERROR_IS_SET(error);
413       goto failed_1;
414     }
415
416   for (i = 0 ; i < nlisten_fds ; i++)
417     _dbus_fd_set_close_on_exec (listen_fds[i]);
418
419   _dbus_string_init_const (&host_str, host);
420   if (!_dbus_string_append (&address, "tcp:host=") ||
421       !_dbus_address_append_escaped (&address, &host_str) ||
422       !_dbus_string_append (&address, ",port=") ||
423       !_dbus_string_append (&address, _dbus_string_get_const_data(&port_str)))
424     {
425       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
426       goto failed_2;
427     }
428   if (family &&
429       (!_dbus_string_append (&address, ",family=") ||
430        !_dbus_string_append (&address, family)))
431     {
432       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
433       goto failed_2;
434     }
435   
436   server = _dbus_server_new_for_socket (listen_fds, nlisten_fds, &address);
437   if (server == NULL)
438     {
439       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
440       goto failed_2;
441     }
442
443   _dbus_string_free (&port_str);
444   _dbus_string_free (&address);
445   dbus_free(listen_fds);
446
447   return server;
448
449  failed_2:
450   for (i = 0 ; i < nlisten_fds ; i++)
451     _dbus_close_socket (listen_fds[i], NULL);
452   dbus_free(listen_fds);
453
454  failed_1:
455   _dbus_string_free (&port_str);
456
457  failed_0:
458   _dbus_string_free (&address);
459
460   return NULL;
461 }
462
463 /**
464  * Tries to interpret the address entry for various socket-related
465  * addresses (well, currently only tcp).
466  * 
467  * Sets error if the result is not OK.
468  * 
469  * @param entry an address entry
470  * @param server_p a new DBusServer, or #NULL on failure.
471  * @param error location to store rationale for failure on bad address
472  * @returns the outcome
473  * 
474  */
475 DBusServerListenResult
476 _dbus_server_listen_socket (DBusAddressEntry *entry,
477                             DBusServer      **server_p,
478                             DBusError        *error)
479 {
480   const char *method;
481
482   *server_p = NULL;
483   
484   method = dbus_address_entry_get_method (entry);
485   
486   if (strcmp (method, "tcp") == 0)
487     {
488       const char *host;
489       const char *port;
490       const char *bind;
491       const char *family;
492
493       host = dbus_address_entry_get_value (entry, "host");
494       bind = dbus_address_entry_get_value (entry, "bind");
495       port = dbus_address_entry_get_value (entry, "port");
496       family = dbus_address_entry_get_value (entry, "family");
497
498       *server_p = _dbus_server_new_for_tcp_socket (host, bind, port,
499                                                    family, error);
500
501       if (*server_p)
502         {
503           _DBUS_ASSERT_ERROR_IS_CLEAR(error);
504           return DBUS_SERVER_LISTEN_OK;
505         }
506       else
507         {
508           _DBUS_ASSERT_ERROR_IS_SET(error);
509           return DBUS_SERVER_LISTEN_DID_NOT_CONNECT;
510         }
511     }
512   else
513     {
514       _DBUS_ASSERT_ERROR_IS_CLEAR(error);
515       return DBUS_SERVER_LISTEN_NOT_HANDLED;
516     }
517 }
518
519 /**
520  * This is a bad hack since it's really unix domain socket
521  * specific. Also, the function weirdly adopts ownership
522  * of the passed-in string.
523  * 
524  * @param server a socket server
525  * @param filename socket filename to report/delete
526  * 
527  */
528 void
529 _dbus_server_socket_own_filename (DBusServer *server,
530                                   char       *filename)
531 {
532   DBusServerSocket *socket_server = (DBusServerSocket*) server;
533
534   socket_server->socket_name = filename;
535 }
536
537
538 /** @} */
539