bus: Assign a serial number for messages from the driver
[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 <config.h>
25 #include "dbus-internals.h"
26 #include "dbus-server-socket.h"
27 #include "dbus-transport-socket.h"
28 #include "dbus-connection-internal.h"
29 #include "dbus-memory.h"
30 #include "dbus-nonce.h"
31 #include "dbus-string.h"
32
33 /**
34  * @defgroup DBusServerSocket DBusServer implementations for SOCKET
35  * @ingroup  DBusInternals
36  * @brief Implementation details of DBusServer on SOCKET
37  *
38  * @{
39  */
40 /**
41  *
42  * Opaque object representing a Socket server implementation.
43  */
44 typedef struct DBusServerSocket DBusServerSocket;
45
46 /**
47  * Implementation details of DBusServerSocket. All members
48  * are private.
49  */
50 struct DBusServerSocket
51 {
52   DBusServer base;   /**< Parent class members. */
53   int n_fds;         /**< Number of active file handles */
54   DBusSocket *fds;   /**< File descriptor or DBUS_SOCKET_INVALID if disconnected. */
55   DBusWatch **watch; /**< File descriptor watch. */
56   char *socket_name; /**< Name of domain socket, to unlink if appropriate */
57   DBusNonceFile *noncefile; /**< Nonce file used to authenticate clients */
58 };
59
60 static void
61 socket_finalize (DBusServer *server)
62 {
63   DBusServerSocket *socket_server = (DBusServerSocket*) server;
64   int i;
65
66   _dbus_server_finalize_base (server);
67
68   for (i = 0 ; i < socket_server->n_fds ; i++)
69     if (socket_server->watch[i])
70       {
71         _dbus_watch_unref (socket_server->watch[i]);
72         socket_server->watch[i] = NULL;
73       }
74
75   dbus_free (socket_server->fds);
76   dbus_free (socket_server->watch);
77   dbus_free (socket_server->socket_name);
78   if (socket_server->noncefile)
79         _dbus_noncefile_delete (socket_server->noncefile, NULL);
80   dbus_free (socket_server->noncefile);
81   dbus_free (server);
82 }
83
84 /* Return value is just for memory, not other failures. */
85 static dbus_bool_t
86 handle_new_client_fd_and_unlock (DBusServer *server,
87                                  DBusSocket  client_fd)
88 {
89   DBusConnection *connection;
90   DBusTransport *transport;
91   DBusNewConnectionFunction new_connection_function;
92   void *new_connection_data;
93
94   _dbus_verbose ("Creating new client connection with fd %" DBUS_SOCKET_FORMAT "\n",
95                  _dbus_socket_printable (client_fd));
96
97   HAVE_LOCK_CHECK (server);
98
99   if (!_dbus_set_socket_nonblocking (client_fd, NULL))
100     {
101       SERVER_UNLOCK (server);
102       return TRUE;
103     }
104
105   transport = _dbus_transport_new_for_socket (client_fd, &server->guid_hex, NULL);
106   if (transport == NULL)
107     {
108       _dbus_close_socket (client_fd, NULL);
109       SERVER_UNLOCK (server);
110       return FALSE;
111     }
112
113   if (!_dbus_transport_set_auth_mechanisms (transport,
114                                             (const char **) server->auth_mechanisms))
115     {
116       _dbus_transport_unref (transport);
117       SERVER_UNLOCK (server);
118       return FALSE;
119     }
120
121   /* note that client_fd is now owned by the transport, and will be
122    * closed on transport disconnection/finalization
123    */
124
125   connection = _dbus_connection_new_for_transport (transport);
126   _dbus_transport_unref (transport);
127   transport = NULL; /* now under the connection lock */
128
129   if (connection == NULL)
130     {
131       SERVER_UNLOCK (server);
132       return FALSE;
133     }
134
135   /* See if someone wants to handle this new connection, self-referencing
136    * for paranoia.
137    */
138   new_connection_function = server->new_connection_function;
139   new_connection_data = server->new_connection_data;
140
141   _dbus_server_ref_unlocked (server);
142   SERVER_UNLOCK (server);
143
144   if (new_connection_function)
145     {
146       (* new_connection_function) (server, connection,
147                                    new_connection_data);
148     }
149   dbus_server_unref (server);
150
151   /* If no one grabbed a reference, the connection will die. */
152   _dbus_connection_close_if_only_one_ref (connection);
153   dbus_connection_unref (connection);
154
155   return TRUE;
156 }
157
158 static dbus_bool_t
159 socket_handle_watch (DBusWatch    *watch,
160                    unsigned int  flags,
161                    void         *data)
162 {
163   DBusServer *server = data;
164   DBusServerSocket *socket_server = data;
165
166 #ifndef DBUS_DISABLE_ASSERT
167   int i;
168   dbus_bool_t found = FALSE;
169 #endif
170
171   SERVER_LOCK (server);
172
173 #ifndef DBUS_DISABLE_ASSERT
174   for (i = 0 ; i < socket_server->n_fds ; i++)
175     {
176       if (socket_server->watch[i] == watch)
177         found = TRUE;
178     }
179   _dbus_assert (found);
180 #endif
181
182   _dbus_verbose ("Handling client connection, flags 0x%x\n", flags);
183
184   if (flags & DBUS_WATCH_READABLE)
185     {
186       DBusSocket client_fd;
187       DBusSocket listen_fd;
188       int saved_errno;
189
190       listen_fd = _dbus_watch_get_socket (watch);
191
192       if (socket_server->noncefile)
193           client_fd = _dbus_accept_with_noncefile (listen_fd, socket_server->noncefile);
194       else 
195           client_fd = _dbus_accept (listen_fd);
196
197       saved_errno = _dbus_save_socket_errno ();
198
199       if (!_dbus_socket_is_valid (client_fd))
200         {
201           /* EINTR handled for us */
202
203           if (_dbus_get_is_errno_eagain_or_ewouldblock (saved_errno))
204             _dbus_verbose ("No client available to accept after all\n");
205           else
206             _dbus_verbose ("Failed to accept a client connection: %s\n",
207                            _dbus_strerror (saved_errno));
208
209           SERVER_UNLOCK (server);
210         }
211       else
212         {
213           if (!handle_new_client_fd_and_unlock (server, client_fd))
214             _dbus_verbose ("Rejected client connection due to lack of memory\n");
215         }
216     }
217
218   if (flags & DBUS_WATCH_ERROR)
219     _dbus_verbose ("Error on server listening socket\n");
220
221   if (flags & DBUS_WATCH_HANGUP)
222     _dbus_verbose ("Hangup on server listening socket\n");
223
224   return TRUE;
225 }
226
227 static void
228 socket_disconnect (DBusServer *server)
229 {
230   DBusServerSocket *socket_server = (DBusServerSocket*) server;
231   int i;
232
233   HAVE_LOCK_CHECK (server);
234
235   for (i = 0 ; i < socket_server->n_fds ; i++)
236     {
237       if (socket_server->watch[i])
238         {
239           _dbus_server_remove_watch (server,
240                                      socket_server->watch[i]);
241           _dbus_watch_invalidate (socket_server->watch[i]);
242           _dbus_watch_unref (socket_server->watch[i]);
243           socket_server->watch[i] = NULL;
244         }
245
246       if (_dbus_socket_is_valid (socket_server->fds[i]))
247         {
248           _dbus_close_socket (socket_server->fds[i], NULL);
249           _dbus_socket_invalidate (&socket_server->fds[i]);
250         }
251     }
252
253   if (socket_server->socket_name != NULL)
254     {
255       DBusString tmp;
256       _dbus_string_init_const (&tmp, socket_server->socket_name);
257       _dbus_delete_file (&tmp, NULL);
258     }
259
260   if (server->published_address)
261       _dbus_daemon_unpublish_session_bus_address();
262
263   HAVE_LOCK_CHECK (server);
264 }
265
266 static const DBusServerVTable socket_vtable = {
267   socket_finalize,
268   socket_disconnect
269 };
270
271 /**
272  * Creates a new server listening on the given file descriptor.  The
273  * file descriptor should be nonblocking (use
274  * _dbus_set_fd_nonblocking() to make it so). The file descriptor
275  * should be listening for connections, that is, listen() should have
276  * been successfully invoked on it. The server will use accept() to
277  * accept new client connections.
278  *
279  * @param fds list of file descriptors.
280  * @param n_fds number of file descriptors
281  * @param address the server's address
282  * @param noncefile to be used for authentication (NULL if not needed)
283  * @param error location to store reason for failure
284  * @returns the new server, or #NULL on OOM or other error.
285  *
286  */
287 DBusServer*
288 _dbus_server_new_for_socket (DBusSocket       *fds,
289                              int               n_fds,
290                              const DBusString *address,
291                              DBusNonceFile    *noncefile,
292                              DBusError        *error)
293 {
294   DBusServerSocket *socket_server;
295   DBusServer *server;
296   int i;
297
298   socket_server = dbus_new0 (DBusServerSocket, 1);
299   if (socket_server == NULL)
300     goto failed_0;
301
302   socket_server->noncefile = noncefile;
303
304   socket_server->fds = dbus_new (DBusSocket, n_fds);
305   if (!socket_server->fds)
306     goto failed_0;
307
308   socket_server->watch = dbus_new0 (DBusWatch *, n_fds);
309   if (!socket_server->watch)
310     goto failed_1;
311
312   for (i = 0 ; i < n_fds ; i++)
313     {
314       DBusWatch *watch;
315
316       watch = _dbus_watch_new (_dbus_socket_get_pollable (fds[i]),
317                                DBUS_WATCH_READABLE,
318                                TRUE,
319                                socket_handle_watch, socket_server,
320                                NULL);
321       if (watch == NULL)
322         goto failed_2;
323
324       socket_server->n_fds++;
325       socket_server->fds[i] = fds[i];
326       socket_server->watch[i] = watch;
327     }
328
329   if (!_dbus_server_init_base (&socket_server->base,
330                                &socket_vtable, address,
331                                error))
332     goto failed_2;
333
334   server = (DBusServer*)socket_server;
335
336   SERVER_LOCK (server);
337
338   for (i = 0 ; i < n_fds ; i++)
339     {
340       if (!_dbus_server_add_watch (&socket_server->base,
341                                    socket_server->watch[i]))
342         {
343           int j;
344
345           /* The caller is still responsible for closing the fds until
346            * we return successfully, so don't let socket_disconnect()
347            * close them */
348           for (j = 0; j < n_fds; j++)
349             _dbus_socket_invalidate (&socket_server->fds[j]);
350
351           /* socket_disconnect() will try to remove all the watches;
352            * make sure it doesn't see the ones that weren't even added
353            * yet */
354           for (j = i; j < n_fds; j++)
355             {
356               _dbus_watch_invalidate (socket_server->watch[j]);
357               _dbus_watch_unref (socket_server->watch[j]);
358               socket_server->watch[j] = NULL;
359             }
360
361           _dbus_server_disconnect_unlocked (server);
362           SERVER_UNLOCK (server);
363           _dbus_server_finalize_base (&socket_server->base);
364           goto failed_2;
365         }
366     }
367
368   SERVER_UNLOCK (server);
369
370   _dbus_server_trace_ref (&socket_server->base, 0, 1, "new_for_socket");
371   return (DBusServer*) socket_server;
372
373  failed_2:
374   for (i = 0 ; i < n_fds ; i++)
375     {
376       if (socket_server->watch[i] != NULL)
377         {
378           _dbus_watch_invalidate (socket_server->watch[i]);
379           _dbus_watch_unref (socket_server->watch[i]);
380           socket_server->watch[i] = NULL;
381         }
382     }
383   dbus_free (socket_server->watch);
384
385  failed_1:
386   dbus_free (socket_server->fds);
387
388  failed_0:
389   dbus_free (socket_server);
390
391   if (error != NULL && !dbus_error_is_set (error))
392     _DBUS_SET_OOM (error);
393
394   return NULL;
395 }
396
397 /**
398  * Creates a new server listening on TCP.
399  * If host is NULL, it will default to localhost.
400  * If bind is NULL, it will default to the value for the host
401  * parameter, and if that is NULL, then localhost
402  * If bind is a hostname, it will be resolved and will listen
403  * on all returned addresses.
404  * If family is NULL, hostname resolution will try all address
405  * families, otherwise it can be ipv4 or ipv6 to restrict the
406  * addresses considered.
407  *
408  * @param host the hostname to report for the listen address
409  * @param bind the hostname to listen on
410  * @param port the port to listen on or 0 to let the OS choose
411  * @param family
412  * @param error location to store reason for failure.
413  * @param use_nonce whether to use a nonce for low-level authentication (nonce-tcp transport) or not (tcp transport)
414  * @returns the new server, or #NULL on failure.
415  */
416 DBusServer*
417 _dbus_server_new_for_tcp_socket (const char     *host,
418                                  const char     *bind,
419                                  const char     *port,
420                                  const char     *family,
421                                  DBusError      *error,
422                                  dbus_bool_t    use_nonce)
423 {
424   DBusServer *server;
425   DBusSocket *listen_fds = NULL;
426   int nlisten_fds = 0, i;
427   DBusString address;
428   DBusString host_str;
429   DBusString port_str;
430   DBusNonceFile *noncefile;
431   
432   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
433
434   noncefile = NULL;
435
436   if (!_dbus_string_init (&address))
437     {
438       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
439       return NULL;
440     }
441
442   if (!_dbus_string_init (&port_str))
443     {
444       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
445       goto failed_0;
446     }
447
448   if (host == NULL)
449     host = "localhost";
450
451   if (port == NULL)
452     port = "0";
453
454   if (bind == NULL)
455     bind = host;
456   else if (strcmp (bind, "*") == 0)
457     bind = NULL;
458
459   nlisten_fds =_dbus_listen_tcp_socket (bind, port, family,
460                                         &port_str,
461                                         &listen_fds, error);
462   if (nlisten_fds <= 0)
463     {
464       _DBUS_ASSERT_ERROR_IS_SET(error);
465       goto failed_1;
466     }
467
468   _dbus_string_init_const (&host_str, host);
469   if (!_dbus_string_append (&address, use_nonce ? "nonce-tcp:host=" : "tcp:host=") ||
470       !_dbus_address_append_escaped (&address, &host_str) ||
471       !_dbus_string_append (&address, ",port=") ||
472       !_dbus_string_append (&address, _dbus_string_get_const_data(&port_str)))
473     {
474       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
475       goto failed_2;
476     }
477   if (family &&
478       (!_dbus_string_append (&address, ",family=") ||
479        !_dbus_string_append (&address, family)))
480     {
481       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
482       goto failed_2;
483     }
484
485   if (use_nonce)
486     {
487       noncefile = dbus_new0 (DBusNonceFile, 1);
488       if (noncefile == NULL)
489         {
490           dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
491           goto failed_2;
492         }
493
494       if (!_dbus_noncefile_create (noncefile, error))
495           goto failed_3;
496
497       if (!_dbus_string_append (&address, ",noncefile=") ||
498           !_dbus_address_append_escaped (&address, _dbus_noncefile_get_path (noncefile)))
499         {
500           dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
501           goto failed_4;
502         }
503
504     }
505
506   server = _dbus_server_new_for_socket (listen_fds, nlisten_fds, &address, noncefile, error);
507   if (server == NULL)
508     {
509       if (noncefile != NULL)
510         goto failed_4;
511       else
512         goto failed_2;
513     }
514
515   _dbus_string_free (&port_str);
516   _dbus_string_free (&address);
517   dbus_free(listen_fds);
518
519   return server;
520
521  failed_4:
522   _dbus_noncefile_delete (noncefile, NULL);
523
524  failed_3:
525   dbus_free (noncefile);
526
527  failed_2:
528   for (i = 0 ; i < nlisten_fds ; i++)
529     _dbus_close_socket (listen_fds[i], NULL);
530   dbus_free(listen_fds);
531
532  failed_1:
533   _dbus_string_free (&port_str);
534
535  failed_0:
536   _dbus_string_free (&address);
537
538   return NULL;
539 }
540
541 /**
542  * Tries to interpret the address entry for various socket-related
543  * addresses (well, currently only tcp and nonce-tcp).
544  *
545  * Sets error if the result is not OK.
546  *
547  * @param entry an address entry
548  * @param server_p a new DBusServer, or #NULL on failure.
549  * @param error location to store rationale for failure on bad address
550  * @returns the outcome
551  *
552  */
553 DBusServerListenResult
554 _dbus_server_listen_socket (DBusAddressEntry *entry,
555                             DBusServer      **server_p,
556                             DBusError        *error)
557 {
558   const char *method;
559
560   *server_p = NULL;
561
562   method = dbus_address_entry_get_method (entry);
563
564   if (strcmp (method, "tcp") == 0 || strcmp (method, "nonce-tcp") == 0)
565     {
566       const char *host;
567       const char *port;
568       const char *bind;
569       const char *family;
570
571       host = dbus_address_entry_get_value (entry, "host");
572       bind = dbus_address_entry_get_value (entry, "bind");
573       port = dbus_address_entry_get_value (entry, "port");
574       family = dbus_address_entry_get_value (entry, "family");
575
576       *server_p = _dbus_server_new_for_tcp_socket (host, bind, port,
577                                                    family, error, strcmp (method, "nonce-tcp") == 0 ? TRUE : FALSE);
578
579       if (*server_p)
580         {
581           _DBUS_ASSERT_ERROR_IS_CLEAR(error);
582           return DBUS_SERVER_LISTEN_OK;
583         }
584       else
585         {
586           _DBUS_ASSERT_ERROR_IS_SET(error);
587           return DBUS_SERVER_LISTEN_DID_NOT_CONNECT;
588         }
589     }
590   else
591     {
592       _DBUS_ASSERT_ERROR_IS_CLEAR(error);
593       return DBUS_SERVER_LISTEN_NOT_HANDLED;
594     }
595 }
596
597 /**
598  * This is a bad hack since it's really unix domain socket
599  * specific. Also, the function weirdly adopts ownership
600  * of the passed-in string.
601  *
602  * @param server a socket server
603  * @param filename socket filename to report/delete
604  *
605  */
606 void
607 _dbus_server_socket_own_filename (DBusServer *server,
608                                   char       *filename)
609 {
610   DBusServerSocket *socket_server = (DBusServerSocket*) server;
611
612   socket_server->socket_name = filename;
613 }
614
615
616 /** @} */
617