Update.
[platform/upstream/glibc.git] / nscd / connections.c
1 /* Inner loops of cache daemon.
2    Copyright (C) 1998, 1999 Free Software Foundation, Inc.
3    This file is part of the GNU C Library.
4    Contributed by Ulrich Drepper <drepper@cygnus.com>, 1998.
5
6    The GNU C Library is free software; you can redistribute it and/or
7    modify it under the terms of the GNU Library General Public License as
8    published by the Free Software Foundation; either version 2 of the
9    License, or (at your option) any later version.
10
11    The GNU C Library is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14    Library General Public License for more details.
15
16    You should have received a copy of the GNU Library General Public
17    License along with the GNU C Library; see the file COPYING.LIB.  If not,
18    write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19    Boston, MA 02111-1307, USA.  */
20
21 #include <assert.h>
22 #include <error.h>
23 #include <errno.h>
24 #include <pthread.h>
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <libintl.h>
28 #include <arpa/inet.h>
29 #include <sys/param.h>
30 #include <sys/poll.h>
31 #include <sys/socket.h>
32 #include <sys/stat.h>
33 #include <sys/un.h>
34
35 #include "nscd.h"
36 #include "dbg_log.h"
37
38
39 /* Mapping of request type to database.  */
40 static const dbtype serv2db[LASTDBREQ + 1] =
41 {
42   [GETPWBYNAME] = pwddb,
43   [GETPWBYUID] = pwddb,
44   [GETGRBYNAME] = grpdb,
45   [GETGRBYGID] = grpdb,
46   [GETHOSTBYNAME] = hstdb,
47   [GETHOSTBYNAMEv6] = hstdb,
48   [GETHOSTBYADDR] = hstdb,
49   [GETHOSTBYADDRv6] = hstdb,
50 };
51
52 /* Map request type to a string.  */
53 const char *serv2str[LASTREQ] =
54 {
55   [GETPWBYNAME] = "GETPWBYNAME",
56   [GETPWBYUID] = "GETPWBYUID",
57   [GETGRBYNAME] = "GETGRBYNAME",
58   [GETGRBYGID] = "GETGRBYGID",
59   [GETHOSTBYNAME] = "GETHOSTBYNAME",
60   [GETHOSTBYNAMEv6] = "GETHOSTBYNAMEv6",
61   [GETHOSTBYADDR] = "GETHOSTBYADDR",
62   [GETHOSTBYADDRv6] = "GETHOSTBYADDRv6",
63   [SHUTDOWN] = "SHUTDOWN",
64   [GETSTAT] = "GETSTAT",
65   [INVALIDATE] = "INVALIDATE"
66 };
67
68 /* The control data structures for the services.  */
69 static struct database dbs[lastdb] =
70 {
71   [pwddb] = {
72     lock: PTHREAD_RWLOCK_INITIALIZER,
73     enabled: 0,
74     check_file: 1,
75     filename: "/etc/passwd",
76     module: 211,
77     disabled_iov: &pwd_iov_disabled,
78     postimeout: 3600,
79     negtimeout: 20
80   },
81   [grpdb] = {
82     lock: PTHREAD_RWLOCK_INITIALIZER,
83     enabled: 0,
84     check_file: 1,
85     filename: "/etc/group",
86     module: 211,
87     disabled_iov: &grp_iov_disabled,
88     postimeout: 3600,
89     negtimeout: 60
90   },
91   [hstdb] = {
92     lock: PTHREAD_RWLOCK_INITIALIZER,
93     enabled: 0,
94     check_file: 1,
95     filename: "/etc/hosts",
96     module: 211,
97     disabled_iov: &hst_iov_disabled,
98     postimeout: 3600,
99     negtimeout: 20
100   }
101 };
102
103 /* Number of seconds between two cache pruning runs.  */
104 #define CACHE_PRUNE_INTERVAL    15
105
106 /* Number of threads to use.  */
107 int nthreads = -1;
108
109 /* Socket for incoming connections.  */
110 static int sock;
111
112
113 /* Initialize database information structures.  */
114 void
115 nscd_init (const char *conffile)
116 {
117   struct sockaddr_un sock_addr;
118   size_t cnt;
119
120   /* Read the configuration file.  */
121   if (nscd_parse_file (conffile, dbs) != 0)
122     {
123       /* We couldn't read the configuration file.  Disable all services
124          by shutting down the srever.  */
125       dbg_log (_("cannot read configuration file; this is fatal"));
126       exit (1);
127     }
128   if (nthreads == -1)
129     /* No configuration for this value, assume a default.  */
130     nthreads = 2 * lastdb;
131
132   for (cnt = 0; cnt < lastdb; ++cnt)
133     if (dbs[cnt].enabled)
134       {
135         pthread_rwlock_init (&dbs[cnt].lock, NULL);
136
137         dbs[cnt].array = (struct hashentry **)
138           calloc (dbs[cnt].module, sizeof (struct hashentry *));
139         if (dbs[cnt].array == NULL)
140           error (EXIT_FAILURE, errno, "while allocating cache");
141
142         if (dbs[cnt].check_file)
143           {
144             /* We need the modification date of the file.  */
145             struct stat st;
146
147             if (stat (dbs[cnt].filename, &st) < 0)
148               {
149                 char buf[128];
150                 /* We cannot stat() the file, disable file checking.  */
151                 dbg_log (_("cannot stat() file `%s': %s"),
152                          dbs[cnt].filename,
153                          strerror_r (errno, buf, sizeof (buf)));
154                 dbs[cnt].check_file = 0;
155               }
156             else
157               dbs[cnt].file_mtime = st.st_mtime;
158           }
159       }
160
161   /* Create the socket.  */
162   sock = socket (AF_UNIX, SOCK_STREAM, 0);
163   if (sock < 0)
164     {
165       dbg_log (_("cannot open socket: %s"), strerror (errno));
166       exit (1);
167     }
168   /* Bind a name to the socket.  */
169   sock_addr.sun_family = AF_UNIX;
170   strcpy (sock_addr.sun_path, _PATH_NSCDSOCKET);
171   if (bind (sock, (struct sockaddr *) &sock_addr, sizeof (sock_addr)) < 0)
172     {
173       dbg_log ("%s: %s", _PATH_NSCDSOCKET, strerror (errno));
174       exit (1);
175     }
176
177   /* Set permissions for the socket.  */
178   chmod (_PATH_NSCDSOCKET, 0666);
179
180   /* Set the socket up to accept connections.  */
181   if (listen (sock, SOMAXCONN) < 0)
182     {
183       dbg_log (_("cannot enable socket to accept connections: %s"),
184                strerror (errno));
185       exit (1);
186     }
187 }
188
189
190 /* Close the connections.  */
191 void
192 close_sockets (void)
193 {
194   close (sock);
195 }
196
197 static void
198 invalidate_cache (void *key)
199 {
200   dbtype number;
201
202   if (strcmp (key, "passwd") == 0)
203     number = pwddb;
204   else if (strcmp (key, "group") == 0)
205     number = grpdb;
206   else if (strcmp (key, "hosts") == 0)
207     number = hstdb;
208   else return;
209
210   prune_cache (&dbs[number], LONG_MAX);
211 }
212
213
214 /* Handle new request.  */
215 static void
216 handle_request (int fd, request_header *req, void *key, uid_t uid)
217 {
218   if (debug_level > 0)
219     dbg_log (_("handle_request: request received (Version = %d)"),
220              req->version);
221
222   if (req->version != NSCD_VERSION)
223     {
224       dbg_log (_("\
225 cannot handle old request version %d; current version is %d"),
226                req->version, NSCD_VERSION);
227       return;
228     }
229
230   if (req->type >= GETPWBYNAME && req->type <= LASTDBREQ)
231     {
232       struct hashentry *cached;
233       struct database *db = &dbs[serv2db[req->type]];
234
235       if (debug_level > 0)
236         {
237           if (req->type == GETHOSTBYADDR || req->type == GETHOSTBYADDRv6)
238             {
239               char buf[INET6_ADDRSTRLEN];
240
241               dbg_log ("\t%s (%s)", serv2str[req->type],
242                        inet_ntop (req->type == GETHOSTBYADDR
243                                   ? AF_INET : AF_INET6,
244                                   key, buf, sizeof (buf)));
245             }
246           else
247             dbg_log ("\t%s (%s)", serv2str[req->type], key);
248         }
249
250       /* Is this service enabled?  */
251       if (!db->enabled)
252         {
253           /* No, sent the prepared record.  */
254           if (TEMP_FAILURE_RETRY (write (fd, db->disabled_iov->iov_base,
255                                          db->disabled_iov->iov_len))
256               != db->disabled_iov->iov_len)
257             {
258               /* We have problems sending the result.  */
259               char buf[256];
260               dbg_log (_("cannot write result: %s"),
261                        strerror_r (errno, buf, sizeof (buf)));
262             }
263
264           return;
265         }
266
267       /* Be sure we can read the data.  */
268       pthread_rwlock_rdlock (&db->lock);
269
270       /* See whether we can handle it from the cache.  */
271       cached = (struct hashentry *) cache_search (req->type, key, req->key_len,
272                                                   db, uid);
273       if (cached != NULL)
274         {
275           /* Hurray it's in the cache.  */
276           if (TEMP_FAILURE_RETRY (write (fd, cached->packet, cached->total))
277               != cached->total)
278             {
279               /* We have problems sending the result.  */
280               char buf[256];
281               dbg_log (_("cannot write result: %s"),
282                        strerror_r (errno, buf, sizeof (buf)));
283             }
284
285           pthread_rwlock_unlock (&db->lock);
286
287           return;
288         }
289
290       pthread_rwlock_unlock (&db->lock);
291     }
292   else if (debug_level > 0)
293     {
294       if (req->type == INVALIDATE)
295         dbg_log ("\t%s (%s)", serv2str[req->type], key);
296       else
297         dbg_log ("\t%s", serv2str[req->type]);
298     }
299
300   /* Handle the request.  */
301   switch (req->type)
302     {
303     case GETPWBYNAME:
304       addpwbyname (&dbs[serv2db[req->type]], fd, req, key, uid);
305       break;
306
307     case GETPWBYUID:
308       addpwbyuid (&dbs[serv2db[req->type]], fd, req, key, uid);
309       break;
310
311     case GETGRBYNAME:
312       addgrbyname (&dbs[serv2db[req->type]], fd, req, key, uid);
313       break;
314
315     case GETGRBYGID:
316       addgrbygid (&dbs[serv2db[req->type]], fd, req, key, uid);
317       break;
318
319     case GETHOSTBYNAME:
320       addhstbyname (&dbs[serv2db[req->type]], fd, req, key, uid);
321       break;
322
323     case GETHOSTBYNAMEv6:
324       addhstbynamev6 (&dbs[serv2db[req->type]], fd, req, key, uid);
325       break;
326
327     case GETHOSTBYADDR:
328       addhstbyaddr (&dbs[serv2db[req->type]], fd, req, key, uid);
329       break;
330
331     case GETHOSTBYADDRv6:
332       addhstbyaddrv6 (&dbs[serv2db[req->type]], fd, req, key, uid);
333       break;
334
335     case GETSTAT:
336     case SHUTDOWN:
337     case INVALIDATE:
338       /* Accept shutdown, getstat and invalidate only from root */
339       if (secure_in_use && uid == 0)
340         {
341           if (req->type == GETSTAT)
342             send_stats (fd, dbs);
343           else if (req->type == INVALIDATE)
344             invalidate_cache (key);
345           else
346             termination_handler (0);
347         }
348       else
349         {
350           struct ucred caller;
351           socklen_t optlen = sizeof (caller);
352
353           if (getsockopt (fd, SOL_SOCKET, SO_PEERCRED, &caller, &optlen) < 0)
354             {
355               char buf[256];
356
357               dbg_log (_("error getting callers id: %s"),
358                        strerror_r (errno, buf, sizeof (buf)));
359             }
360           else
361             if (caller.uid == 0)
362               {
363                 if (req->type == GETSTAT)
364                   send_stats (fd, dbs);
365                 else if (req->type == INVALIDATE)
366                   invalidate_cache (key);
367                 else
368                   termination_handler (0);
369               }
370         }
371       break;
372
373     default:
374       abort ();
375     }
376 }
377
378
379 /* This is the main loop.  It is replicated in different threads but the
380    `poll' call makes sure only one thread handles an incoming connection.  */
381 static void *
382 __attribute__ ((__noreturn__))
383 nscd_run (void *p)
384 {
385   int my_number = (int) p;
386   struct pollfd conn;
387   int run_prune = my_number < lastdb && dbs[my_number].enabled;
388   time_t now = time (NULL);
389   time_t next_prune = now + CACHE_PRUNE_INTERVAL;
390   int timeout = run_prune ? 1000 * (next_prune - now) : -1;
391
392   conn.fd = sock;
393   conn.events = POLLRDNORM;
394
395   while (1)
396     {
397       int nr = poll (&conn, 1, timeout);
398
399       if (nr == 0)
400         {
401           /* The `poll' call timed out.  It's time to clean up the cache.  */
402           assert (my_number < lastdb);
403           now = time (NULL);
404           prune_cache (&dbs[my_number], now);
405           next_prune = now + CACHE_PRUNE_INTERVAL;
406           timeout = 1000 * (next_prune - now);
407           continue;
408         }
409
410       /* We have a new incoming connection.  */
411       if (conn.revents & (POLLRDNORM|POLLERR|POLLHUP|POLLNVAL))
412         {
413           /* Accept the connection.  */
414           int fd = accept (conn.fd, NULL, NULL);
415           request_header req;
416           char buf[256];
417           uid_t uid = 0;
418
419           if (fd < 0)
420             {
421               dbg_log (_("while accepting connection: %s"),
422                        strerror_r (errno, buf, sizeof (buf)));
423               continue;
424             }
425
426           /* Now read the request.  */
427           if (TEMP_FAILURE_RETRY (read (fd, &req, sizeof (req)))
428               != sizeof (req))
429             {
430               dbg_log (_("short read while reading request: %s"),
431                        strerror_r (errno, buf, sizeof (buf)));
432               close (fd);
433               continue;
434             }
435
436           if (secure_in_use)
437             {
438               struct ucred caller;
439               socklen_t optlen = sizeof (caller);
440
441               if (getsockopt (fd, SOL_SOCKET, SO_PEERCRED,
442                               &caller, &optlen) < 0)
443                 {
444                   dbg_log (_("error getting callers id: %s"),
445                            strerror_r (errno, buf, sizeof (buf)));
446                   close (fd);
447                   continue;
448                 }
449
450               if (req.type < GETPWBYNAME || req.type > LASTDBREQ
451                   || secure[serv2db[req.type]])
452                 uid = caller.uid;
453             }
454
455           /* It should not be possible to crash the nscd with a silly
456              request (i.e., a terribly large key.  We limit the size
457              to 1kb.  */
458           if (req.key_len < 0 || req.key_len > 1024)
459             {
460               dbg_log (_("key length in request too long: %Zd"), req.key_len);
461               close (fd);
462               continue;
463             }
464           else
465             {
466               /* Get the key.  */
467               char keybuf[req.key_len];
468
469               if (TEMP_FAILURE_RETRY (read (fd, keybuf, req.key_len))
470                   != req.key_len)
471                 {
472                   dbg_log (_("short read while reading request key: %s"),
473                            strerror_r (errno, buf, sizeof (buf)));
474                   close (fd);
475                   continue;
476                 }
477
478               /* Phew, we got all the data, now process it.  */
479               handle_request (fd, &req, keybuf, uid);
480
481               /* We are done.  */
482               close (fd);
483             }
484         }
485
486       if (run_prune)
487         {
488           now = time (NULL);
489           timeout = now < next_prune ? 1000 * (next_prune - now) : 0;
490         }
491     }
492 }
493
494
495 /* Start all the threads we want.  The initial process is thread no. 1.  */
496 void
497 start_threads (void)
498 {
499   int i;
500   pthread_attr_t attr;
501   pthread_t th;
502
503   pthread_attr_init (&attr);
504   pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
505
506   /* We allow less than LASTDB threads only for debugging.  */
507   if (debug_level == 0)
508     nthreads = MAX (nthreads, lastdb);
509
510   for (i = 1; i < nthreads; ++i)
511     pthread_create (&th, &attr, nscd_run, (void *) i);
512
513   pthread_attr_destroy (&attr);
514
515   nscd_run ((void *) 0);
516 }