forked from lattera/glibc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnections.c
2538 lines (2217 loc) · 67.6 KB
/
connections.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Inner loops of cache daemon.
Copyright (C) 1998-2018 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Ulrich Drepper <[email protected]>, 1998.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation; version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see <http://www.gnu.org/licenses/>. */
#include <alloca.h>
#include <assert.h>
#include <atomic.h>
#include <error.h>
#include <errno.h>
#include <fcntl.h>
#include <grp.h>
#include <ifaddrs.h>
#include <libintl.h>
#include <pthread.h>
#include <pwd.h>
#include <resolv.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>
#include <arpa/inet.h>
#ifdef HAVE_NETLINK
# include <linux/netlink.h>
# include <linux/rtnetlink.h>
#endif
#ifdef HAVE_EPOLL
# include <sys/epoll.h>
#endif
#ifdef HAVE_INOTIFY
# include <sys/inotify.h>
#endif
#include <sys/mman.h>
#include <sys/param.h>
#include <sys/poll.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include "nscd.h"
#include "dbg_log.h"
#include "selinux.h"
#include <resolv/resolv.h>
#include <kernel-features.h>
#include <libc-diag.h>
/* Support to run nscd as an unprivileged user */
const char *server_user;
static uid_t server_uid;
static gid_t server_gid;
const char *stat_user;
uid_t stat_uid;
static gid_t *server_groups;
#ifndef NGROUPS
# define NGROUPS 32
#endif
static int server_ngroups;
static pthread_attr_t attr;
static void begin_drop_privileges (void);
static void finish_drop_privileges (void);
/* Map request type to a string. */
const char *const serv2str[LASTREQ] =
{
[GETPWBYNAME] = "GETPWBYNAME",
[GETPWBYUID] = "GETPWBYUID",
[GETGRBYNAME] = "GETGRBYNAME",
[GETGRBYGID] = "GETGRBYGID",
[GETHOSTBYNAME] = "GETHOSTBYNAME",
[GETHOSTBYNAMEv6] = "GETHOSTBYNAMEv6",
[GETHOSTBYADDR] = "GETHOSTBYADDR",
[GETHOSTBYADDRv6] = "GETHOSTBYADDRv6",
[SHUTDOWN] = "SHUTDOWN",
[GETSTAT] = "GETSTAT",
[INVALIDATE] = "INVALIDATE",
[GETFDPW] = "GETFDPW",
[GETFDGR] = "GETFDGR",
[GETFDHST] = "GETFDHST",
[GETAI] = "GETAI",
[INITGROUPS] = "INITGROUPS",
[GETSERVBYNAME] = "GETSERVBYNAME",
[GETSERVBYPORT] = "GETSERVBYPORT",
[GETFDSERV] = "GETFDSERV",
[GETNETGRENT] = "GETNETGRENT",
[INNETGR] = "INNETGR",
[GETFDNETGR] = "GETFDNETGR"
};
#ifdef PTHREAD_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP
# define RWLOCK_INITIALIZER PTHREAD_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP
#else
# define RWLOCK_INITIALIZER PTHREAD_RWLOCK_INITIALIZER
#endif
/* The control data structures for the services. */
struct database_dyn dbs[lastdb] =
{
[pwddb] = {
.lock = RWLOCK_INITIALIZER,
.prune_lock = PTHREAD_MUTEX_INITIALIZER,
.prune_run_lock = PTHREAD_MUTEX_INITIALIZER,
.enabled = 0,
.check_file = 1,
.persistent = 0,
.propagate = 1,
.shared = 0,
.max_db_size = DEFAULT_MAX_DB_SIZE,
.suggested_module = DEFAULT_SUGGESTED_MODULE,
.db_filename = _PATH_NSCD_PASSWD_DB,
.disabled_iov = &pwd_iov_disabled,
.postimeout = 3600,
.negtimeout = 20,
.wr_fd = -1,
.ro_fd = -1,
.mmap_used = false
},
[grpdb] = {
.lock = RWLOCK_INITIALIZER,
.prune_lock = PTHREAD_MUTEX_INITIALIZER,
.prune_run_lock = PTHREAD_MUTEX_INITIALIZER,
.enabled = 0,
.check_file = 1,
.persistent = 0,
.propagate = 1,
.shared = 0,
.max_db_size = DEFAULT_MAX_DB_SIZE,
.suggested_module = DEFAULT_SUGGESTED_MODULE,
.db_filename = _PATH_NSCD_GROUP_DB,
.disabled_iov = &grp_iov_disabled,
.postimeout = 3600,
.negtimeout = 60,
.wr_fd = -1,
.ro_fd = -1,
.mmap_used = false
},
[hstdb] = {
.lock = RWLOCK_INITIALIZER,
.prune_lock = PTHREAD_MUTEX_INITIALIZER,
.prune_run_lock = PTHREAD_MUTEX_INITIALIZER,
.enabled = 0,
.check_file = 1,
.persistent = 0,
.propagate = 0, /* Not used. */
.shared = 0,
.max_db_size = DEFAULT_MAX_DB_SIZE,
.suggested_module = DEFAULT_SUGGESTED_MODULE,
.db_filename = _PATH_NSCD_HOSTS_DB,
.disabled_iov = &hst_iov_disabled,
.postimeout = 3600,
.negtimeout = 20,
.wr_fd = -1,
.ro_fd = -1,
.mmap_used = false
},
[servdb] = {
.lock = RWLOCK_INITIALIZER,
.prune_lock = PTHREAD_MUTEX_INITIALIZER,
.prune_run_lock = PTHREAD_MUTEX_INITIALIZER,
.enabled = 0,
.check_file = 1,
.persistent = 0,
.propagate = 0, /* Not used. */
.shared = 0,
.max_db_size = DEFAULT_MAX_DB_SIZE,
.suggested_module = DEFAULT_SUGGESTED_MODULE,
.db_filename = _PATH_NSCD_SERVICES_DB,
.disabled_iov = &serv_iov_disabled,
.postimeout = 28800,
.negtimeout = 20,
.wr_fd = -1,
.ro_fd = -1,
.mmap_used = false
},
[netgrdb] = {
.lock = RWLOCK_INITIALIZER,
.prune_lock = PTHREAD_MUTEX_INITIALIZER,
.prune_run_lock = PTHREAD_MUTEX_INITIALIZER,
.enabled = 0,
.check_file = 1,
.persistent = 0,
.propagate = 0, /* Not used. */
.shared = 0,
.max_db_size = DEFAULT_MAX_DB_SIZE,
.suggested_module = DEFAULT_SUGGESTED_MODULE,
.db_filename = _PATH_NSCD_NETGROUP_DB,
.disabled_iov = &netgroup_iov_disabled,
.postimeout = 28800,
.negtimeout = 20,
.wr_fd = -1,
.ro_fd = -1,
.mmap_used = false
}
};
/* Mapping of request type to database. */
static struct
{
bool data_request;
struct database_dyn *db;
} const reqinfo[LASTREQ] =
{
[GETPWBYNAME] = { true, &dbs[pwddb] },
[GETPWBYUID] = { true, &dbs[pwddb] },
[GETGRBYNAME] = { true, &dbs[grpdb] },
[GETGRBYGID] = { true, &dbs[grpdb] },
[GETHOSTBYNAME] = { true, &dbs[hstdb] },
[GETHOSTBYNAMEv6] = { true, &dbs[hstdb] },
[GETHOSTBYADDR] = { true, &dbs[hstdb] },
[GETHOSTBYADDRv6] = { true, &dbs[hstdb] },
[SHUTDOWN] = { false, NULL },
[GETSTAT] = { false, NULL },
[SHUTDOWN] = { false, NULL },
[GETFDPW] = { false, &dbs[pwddb] },
[GETFDGR] = { false, &dbs[grpdb] },
[GETFDHST] = { false, &dbs[hstdb] },
[GETAI] = { true, &dbs[hstdb] },
[INITGROUPS] = { true, &dbs[grpdb] },
[GETSERVBYNAME] = { true, &dbs[servdb] },
[GETSERVBYPORT] = { true, &dbs[servdb] },
[GETFDSERV] = { false, &dbs[servdb] },
[GETNETGRENT] = { true, &dbs[netgrdb] },
[INNETGR] = { true, &dbs[netgrdb] },
[GETFDNETGR] = { false, &dbs[netgrdb] }
};
/* Initial number of threads to use. */
int nthreads = -1;
/* Maximum number of threads to use. */
int max_nthreads = 32;
/* Socket for incoming connections. */
static int sock;
#ifdef HAVE_INOTIFY
/* Inotify descriptor. */
int inotify_fd = -1;
#endif
#ifdef HAVE_NETLINK
/* Descriptor for netlink status updates. */
static int nl_status_fd = -1;
#endif
/* Number of times clients had to wait. */
unsigned long int client_queued;
ssize_t
writeall (int fd, const void *buf, size_t len)
{
size_t n = len;
ssize_t ret;
do
{
ret = TEMP_FAILURE_RETRY (send (fd, buf, n, MSG_NOSIGNAL));
if (ret <= 0)
break;
buf = (const char *) buf + ret;
n -= ret;
}
while (n > 0);
return ret < 0 ? ret : len - n;
}
enum usekey
{
use_not = 0,
/* The following three are not really used, they are symbolic constants. */
use_first = 16,
use_begin = 32,
use_end = 64,
use_he = 1,
use_he_begin = use_he | use_begin,
use_he_end = use_he | use_end,
use_data = 3,
use_data_begin = use_data | use_begin,
use_data_end = use_data | use_end,
use_data_first = use_data_begin | use_first
};
static int
check_use (const char *data, nscd_ssize_t first_free, uint8_t *usemap,
enum usekey use, ref_t start, size_t len)
{
assert (len >= 2);
if (start > first_free || start + len > first_free
|| (start & BLOCK_ALIGN_M1))
return 0;
if (usemap[start] == use_not)
{
/* Add the start marker. */
usemap[start] = use | use_begin;
use &= ~use_first;
while (--len > 0)
if (usemap[++start] != use_not)
return 0;
else
usemap[start] = use;
/* Add the end marker. */
usemap[start] = use | use_end;
}
else if ((usemap[start] & ~use_first) == ((use | use_begin) & ~use_first))
{
/* Hash entries can't be shared. */
if (use == use_he)
return 0;
usemap[start] |= (use & use_first);
use &= ~use_first;
while (--len > 1)
if (usemap[++start] != use)
return 0;
if (usemap[++start] != (use | use_end))
return 0;
}
else
/* Points to a wrong object or somewhere in the middle. */
return 0;
return 1;
}
/* Verify data in persistent database. */
static int
verify_persistent_db (void *mem, struct database_pers_head *readhead, int dbnr)
{
assert (dbnr == pwddb || dbnr == grpdb || dbnr == hstdb || dbnr == servdb
|| dbnr == netgrdb);
time_t now = time (NULL);
struct database_pers_head *head = mem;
struct database_pers_head head_copy = *head;
/* Check that the header that was read matches the head in the database. */
if (memcmp (head, readhead, sizeof (*head)) != 0)
return 0;
/* First some easy tests: make sure the database header is sane. */
if (head->version != DB_VERSION
|| head->header_size != sizeof (*head)
/* We allow a timestamp to be one hour ahead of the current time.
This should cover daylight saving time changes. */
|| head->timestamp > now + 60 * 60 + 60
|| (head->gc_cycle & 1)
|| head->module == 0
|| (size_t) head->module > INT32_MAX / sizeof (ref_t)
|| (size_t) head->data_size > INT32_MAX - head->module * sizeof (ref_t)
|| head->first_free < 0
|| head->first_free > head->data_size
|| (head->first_free & BLOCK_ALIGN_M1) != 0
|| head->maxnentries < 0
|| head->maxnsearched < 0)
return 0;
uint8_t *usemap = calloc (head->first_free, 1);
if (usemap == NULL)
return 0;
const char *data = (char *) &head->array[roundup (head->module,
ALIGN / sizeof (ref_t))];
nscd_ssize_t he_cnt = 0;
for (nscd_ssize_t cnt = 0; cnt < head->module; ++cnt)
{
ref_t trail = head->array[cnt];
ref_t work = trail;
int tick = 0;
while (work != ENDREF)
{
if (! check_use (data, head->first_free, usemap, use_he, work,
sizeof (struct hashentry)))
goto fail;
/* Now we know we can dereference the record. */
struct hashentry *here = (struct hashentry *) (data + work);
++he_cnt;
/* Make sure the record is for this type of service. */
if (here->type >= LASTREQ
|| reqinfo[here->type].db != &dbs[dbnr])
goto fail;
/* Validate boolean field value. */
if (here->first != false && here->first != true)
goto fail;
if (here->len < 0)
goto fail;
/* Now the data. */
if (here->packet < 0
|| here->packet > head->first_free
|| here->packet + sizeof (struct datahead) > head->first_free)
goto fail;
struct datahead *dh = (struct datahead *) (data + here->packet);
if (! check_use (data, head->first_free, usemap,
use_data | (here->first ? use_first : 0),
here->packet, dh->allocsize))
goto fail;
if (dh->allocsize < sizeof (struct datahead)
|| dh->recsize > dh->allocsize
|| (dh->notfound != false && dh->notfound != true)
|| (dh->usable != false && dh->usable != true))
goto fail;
if (here->key < here->packet + sizeof (struct datahead)
|| here->key > here->packet + dh->allocsize
|| here->key + here->len > here->packet + dh->allocsize)
goto fail;
work = here->next;
if (work == trail)
/* A circular list, this must not happen. */
goto fail;
if (tick)
trail = ((struct hashentry *) (data + trail))->next;
tick = 1 - tick;
}
}
if (he_cnt != head->nentries)
goto fail;
/* See if all data and keys had at least one reference from
he->first == true hashentry. */
for (ref_t idx = 0; idx < head->first_free; ++idx)
{
if (usemap[idx] == use_data_begin)
goto fail;
}
/* Finally, make sure the database hasn't changed since the first test. */
if (memcmp (mem, &head_copy, sizeof (*head)) != 0)
goto fail;
free (usemap);
return 1;
fail:
free (usemap);
return 0;
}
/* Initialize database information structures. */
void
nscd_init (void)
{
/* Look up unprivileged uid/gid/groups before we start listening on the
socket */
if (server_user != NULL)
begin_drop_privileges ();
if (nthreads == -1)
/* No configuration for this value, assume a default. */
nthreads = 4;
for (size_t cnt = 0; cnt < lastdb; ++cnt)
if (dbs[cnt].enabled)
{
pthread_rwlock_init (&dbs[cnt].lock, NULL);
pthread_mutex_init (&dbs[cnt].memlock, NULL);
if (dbs[cnt].persistent)
{
/* Try to open the appropriate file on disk. */
int fd = open (dbs[cnt].db_filename, O_RDWR | O_CLOEXEC);
if (fd != -1)
{
char *msg = NULL;
struct stat64 st;
void *mem;
size_t total;
struct database_pers_head head;
ssize_t n = TEMP_FAILURE_RETRY (read (fd, &head,
sizeof (head)));
if (n != sizeof (head) || fstat64 (fd, &st) != 0)
{
fail_db_errno:
/* The code is single-threaded at this point so
using strerror is just fine. */
msg = strerror (errno);
fail_db:
dbg_log (_("invalid persistent database file \"%s\": %s"),
dbs[cnt].db_filename, msg);
unlink (dbs[cnt].db_filename);
}
else if (head.module == 0 && head.data_size == 0)
{
/* The file has been created, but the head has not
been initialized yet. */
msg = _("uninitialized header");
goto fail_db;
}
else if (head.header_size != (int) sizeof (head))
{
msg = _("header size does not match");
goto fail_db;
}
else if ((total = (sizeof (head)
+ roundup (head.module * sizeof (ref_t),
ALIGN)
+ head.data_size))
> st.st_size
|| total < sizeof (head))
{
msg = _("file size does not match");
goto fail_db;
}
/* Note we map with the maximum size allowed for the
database. This is likely much larger than the
actual file size. This is OK on most OSes since
extensions of the underlying file will
automatically translate more pages available for
memory access. */
else if ((mem = mmap (NULL, dbs[cnt].max_db_size,
PROT_READ | PROT_WRITE,
MAP_SHARED, fd, 0))
== MAP_FAILED)
goto fail_db_errno;
else if (!verify_persistent_db (mem, &head, cnt))
{
munmap (mem, total);
msg = _("verification failed");
goto fail_db;
}
else
{
/* Success. We have the database. */
dbs[cnt].head = mem;
dbs[cnt].memsize = total;
dbs[cnt].data = (char *)
&dbs[cnt].head->array[roundup (dbs[cnt].head->module,
ALIGN / sizeof (ref_t))];
dbs[cnt].mmap_used = true;
if (dbs[cnt].suggested_module > head.module)
dbg_log (_("suggested size of table for database %s larger than the persistent database's table"),
dbnames[cnt]);
dbs[cnt].wr_fd = fd;
fd = -1;
/* We also need a read-only descriptor. */
if (dbs[cnt].shared)
{
dbs[cnt].ro_fd = open (dbs[cnt].db_filename,
O_RDONLY | O_CLOEXEC);
if (dbs[cnt].ro_fd == -1)
dbg_log (_("\
cannot create read-only descriptor for \"%s\"; no mmap"),
dbs[cnt].db_filename);
}
// XXX Shall we test whether the descriptors actually
// XXX point to the same file?
}
/* Close the file descriptors in case something went
wrong in which case the variable have not been
assigned -1. */
if (fd != -1)
close (fd);
}
else if (errno == EACCES)
do_exit (EXIT_FAILURE, 0, _("cannot access '%s'"),
dbs[cnt].db_filename);
}
if (dbs[cnt].head == NULL)
{
/* No database loaded. Allocate the data structure,
possibly on disk. */
struct database_pers_head head;
size_t total = (sizeof (head)
+ roundup (dbs[cnt].suggested_module
* sizeof (ref_t), ALIGN)
+ (dbs[cnt].suggested_module
* DEFAULT_DATASIZE_PER_BUCKET));
/* Try to create the database. If we do not need a
persistent database create a temporary file. */
int fd;
int ro_fd = -1;
if (dbs[cnt].persistent)
{
fd = open (dbs[cnt].db_filename,
O_RDWR | O_CREAT | O_EXCL | O_TRUNC | O_CLOEXEC,
S_IRUSR | S_IWUSR);
if (fd != -1 && dbs[cnt].shared)
ro_fd = open (dbs[cnt].db_filename,
O_RDONLY | O_CLOEXEC);
}
else
{
char fname[] = _PATH_NSCD_XYZ_DB_TMP;
fd = mkostemp (fname, O_CLOEXEC);
/* We do not need the file name anymore after we
opened another file descriptor in read-only mode. */
if (fd != -1)
{
if (dbs[cnt].shared)
ro_fd = open (fname, O_RDONLY | O_CLOEXEC);
unlink (fname);
}
}
if (fd == -1)
{
if (errno == EEXIST)
{
dbg_log (_("database for %s corrupted or simultaneously used; remove %s manually if necessary and restart"),
dbnames[cnt], dbs[cnt].db_filename);
do_exit (1, 0, NULL);
}
if (dbs[cnt].persistent)
dbg_log (_("cannot create %s; no persistent database used"),
dbs[cnt].db_filename);
else
dbg_log (_("cannot create %s; no sharing possible"),
dbs[cnt].db_filename);
dbs[cnt].persistent = 0;
// XXX remember: no mmap
}
else
{
/* Tell the user if we could not create the read-only
descriptor. */
if (ro_fd == -1 && dbs[cnt].shared)
dbg_log (_("\
cannot create read-only descriptor for \"%s\"; no mmap"),
dbs[cnt].db_filename);
/* Before we create the header, initialize the hash
table. That way if we get interrupted while writing
the header we can recognize a partially initialized
database. */
size_t ps = sysconf (_SC_PAGESIZE);
char tmpbuf[ps];
assert (~ENDREF == 0);
memset (tmpbuf, '\xff', ps);
size_t remaining = dbs[cnt].suggested_module * sizeof (ref_t);
off_t offset = sizeof (head);
size_t towrite;
if (offset % ps != 0)
{
towrite = MIN (remaining, ps - (offset % ps));
if (pwrite (fd, tmpbuf, towrite, offset) != towrite)
goto write_fail;
offset += towrite;
remaining -= towrite;
}
while (remaining > ps)
{
if (pwrite (fd, tmpbuf, ps, offset) == -1)
goto write_fail;
offset += ps;
remaining -= ps;
}
if (remaining > 0
&& pwrite (fd, tmpbuf, remaining, offset) != remaining)
goto write_fail;
/* Create the header of the file. */
struct database_pers_head head =
{
.version = DB_VERSION,
.header_size = sizeof (head),
.module = dbs[cnt].suggested_module,
.data_size = (dbs[cnt].suggested_module
* DEFAULT_DATASIZE_PER_BUCKET),
.first_free = 0
};
void *mem;
if ((TEMP_FAILURE_RETRY (write (fd, &head, sizeof (head)))
!= sizeof (head))
|| (TEMP_FAILURE_RETRY_VAL (posix_fallocate (fd, 0, total))
!= 0)
|| (mem = mmap (NULL, dbs[cnt].max_db_size,
PROT_READ | PROT_WRITE,
MAP_SHARED, fd, 0)) == MAP_FAILED)
{
write_fail:
unlink (dbs[cnt].db_filename);
dbg_log (_("cannot write to database file %s: %s"),
dbs[cnt].db_filename, strerror (errno));
dbs[cnt].persistent = 0;
}
else
{
/* Success. */
dbs[cnt].head = mem;
dbs[cnt].data = (char *)
&dbs[cnt].head->array[roundup (dbs[cnt].head->module,
ALIGN / sizeof (ref_t))];
dbs[cnt].memsize = total;
dbs[cnt].mmap_used = true;
/* Remember the descriptors. */
dbs[cnt].wr_fd = fd;
dbs[cnt].ro_fd = ro_fd;
fd = -1;
ro_fd = -1;
}
if (fd != -1)
close (fd);
if (ro_fd != -1)
close (ro_fd);
}
}
if (dbs[cnt].head == NULL)
{
/* We do not use the persistent database. Just
create an in-memory data structure. */
assert (! dbs[cnt].persistent);
dbs[cnt].head = xmalloc (sizeof (struct database_pers_head)
+ (dbs[cnt].suggested_module
* sizeof (ref_t)));
memset (dbs[cnt].head, '\0', sizeof (struct database_pers_head));
assert (~ENDREF == 0);
memset (dbs[cnt].head->array, '\xff',
dbs[cnt].suggested_module * sizeof (ref_t));
dbs[cnt].head->module = dbs[cnt].suggested_module;
dbs[cnt].head->data_size = (DEFAULT_DATASIZE_PER_BUCKET
* dbs[cnt].head->module);
dbs[cnt].data = xmalloc (dbs[cnt].head->data_size);
dbs[cnt].head->first_free = 0;
dbs[cnt].shared = 0;
assert (dbs[cnt].ro_fd == -1);
}
}
/* Create the socket. */
sock = socket (AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0);
if (sock < 0)
{
dbg_log (_("cannot open socket: %s"), strerror (errno));
do_exit (errno == EACCES ? 4 : 1, 0, NULL);
}
/* Bind a name to the socket. */
struct sockaddr_un sock_addr;
sock_addr.sun_family = AF_UNIX;
strcpy (sock_addr.sun_path, _PATH_NSCDSOCKET);
if (bind (sock, (struct sockaddr *) &sock_addr, sizeof (sock_addr)) < 0)
{
dbg_log ("%s: %s", _PATH_NSCDSOCKET, strerror (errno));
do_exit (errno == EACCES ? 4 : 1, 0, NULL);
}
/* Set permissions for the socket. */
chmod (_PATH_NSCDSOCKET, DEFFILEMODE);
/* Set the socket up to accept connections. */
if (listen (sock, SOMAXCONN) < 0)
{
dbg_log (_("cannot enable socket to accept connections: %s"),
strerror (errno));
do_exit (1, 0, NULL);
}
#ifdef HAVE_NETLINK
if (dbs[hstdb].enabled)
{
/* Try to open netlink socket to monitor network setting changes. */
nl_status_fd = socket (AF_NETLINK,
SOCK_RAW | SOCK_CLOEXEC | SOCK_NONBLOCK,
NETLINK_ROUTE);
if (nl_status_fd != -1)
{
struct sockaddr_nl snl;
memset (&snl, '\0', sizeof (snl));
snl.nl_family = AF_NETLINK;
/* XXX Is this the best set to use? */
snl.nl_groups = (RTMGRP_IPV4_IFADDR | RTMGRP_TC | RTMGRP_IPV4_MROUTE
| RTMGRP_IPV4_ROUTE | RTMGRP_IPV4_RULE
| RTMGRP_IPV6_IFADDR | RTMGRP_IPV6_MROUTE
| RTMGRP_IPV6_ROUTE | RTMGRP_IPV6_IFINFO
| RTMGRP_IPV6_PREFIX);
if (bind (nl_status_fd, (struct sockaddr *) &snl, sizeof (snl)) != 0)
{
close (nl_status_fd);
nl_status_fd = -1;
}
else
{
/* Start the timestamp process. */
dbs[hstdb].head->extra_data[NSCD_HST_IDX_CONF_TIMESTAMP]
= __bump_nl_timestamp ();
}
}
}
#endif
/* Change to unprivileged uid/gid/groups if specified in config file */
if (server_user != NULL)
finish_drop_privileges ();
}
#ifdef HAVE_INOTIFY
#define TRACED_FILE_MASK (IN_DELETE_SELF | IN_CLOSE_WRITE | IN_MOVE_SELF)
#define TRACED_DIR_MASK (IN_DELETE_SELF | IN_CREATE | IN_MOVED_TO | IN_MOVE_SELF)
void
install_watches (struct traced_file *finfo)
{
/* Use inotify support if we have it. */
if (finfo->inotify_descr[TRACED_FILE] < 0)
finfo->inotify_descr[TRACED_FILE] = inotify_add_watch (inotify_fd,
finfo->fname,
TRACED_FILE_MASK);
if (finfo->inotify_descr[TRACED_FILE] < 0)
{
dbg_log (_("disabled inotify-based monitoring for file `%s': %s"),
finfo->fname, strerror (errno));
return;
}
dbg_log (_("monitoring file `%s` (%d)"),
finfo->fname, finfo->inotify_descr[TRACED_FILE]);
/* Additionally listen for events in the file's parent directory.
We do this because the file to be watched might be
deleted and then added back again. When it is added back again
we must re-add the watch. We must also cover IN_MOVED_TO to
detect a file being moved into the directory. */
if (finfo->inotify_descr[TRACED_DIR] < 0)
finfo->inotify_descr[TRACED_DIR] = inotify_add_watch (inotify_fd,
finfo->dname,
TRACED_DIR_MASK);
if (finfo->inotify_descr[TRACED_DIR] < 0)
{
dbg_log (_("disabled inotify-based monitoring for directory `%s': %s"),
finfo->fname, strerror (errno));
return;
}
dbg_log (_("monitoring directory `%s` (%d)"),
finfo->dname, finfo->inotify_descr[TRACED_DIR]);
}
#endif
/* Register the file in FINFO as a traced file for the database DBS[DBIX].
We support registering multiple files per database. Each call to
register_traced_file adds to the list of registered files.
When we prune the database, either through timeout or a request to
invalidate, we will check to see if any of the registered files has changed.
When we accept new connections to handle a cache request we will also
check to see if any of the registered files has changed.
If we have inotify support then we install an inotify fd to notify us of
file deletion or modification, both of which will require we invalidate
the cache for the database. Without inotify support we stat the file and
store st_mtime to determine if the file has been modified. */
void
register_traced_file (size_t dbidx, struct traced_file *finfo)
{
/* If the database is disabled or file checking is disabled
then ignore the registration. */
if (! dbs[dbidx].enabled || ! dbs[dbidx].check_file)
return;
if (__glibc_unlikely (debug_level > 0))
dbg_log (_("monitoring file %s for database %s"),
finfo->fname, dbnames[dbidx]);
#ifdef HAVE_INOTIFY
install_watches (finfo);
#endif
struct stat64 st;
if (stat64 (finfo->fname, &st) < 0)
{
/* We cannot stat() the file. Set mtime to zero and try again later. */
dbg_log (_("stat failed for file `%s'; will try again later: %s"),
finfo->fname, strerror (errno));
finfo->mtime = 0;
}
else
finfo->mtime = st.st_mtime;
/* Queue up the file name. */
finfo->next = dbs[dbidx].traced_files;
dbs[dbidx].traced_files = finfo;
}
/* Close the connections. */
void
close_sockets (void)
{
close (sock);
}
static void
invalidate_cache (char *key, int fd)
{
dbtype number;
int32_t resp;
for (number = pwddb; number < lastdb; ++number)
if (strcmp (key, dbnames[number]) == 0)
{
struct traced_file *runp = dbs[number].traced_files;
while (runp != NULL)
{
/* Make sure we reload from file when checking mtime. */
runp->mtime = 0;
#ifdef HAVE_INOTIFY
/* During an invalidation we try to reload the traced
file watches. This allows the user to re-sync if
inotify events were lost. Similar to what we do during
pruning. */
install_watches (runp);
#endif
if (runp->call_res_init)
{
res_init ();
break;
}
runp = runp->next;
}
break;
}
if (number == lastdb)
{
resp = EINVAL;
writeall (fd, &resp, sizeof (resp));
return;
}
if (dbs[number].enabled)
{
pthread_mutex_lock (&dbs[number].prune_run_lock);
prune_cache (&dbs[number], LONG_MAX, fd);
pthread_mutex_unlock (&dbs[number].prune_run_lock);
}
else
{
resp = 0;
writeall (fd, &resp, sizeof (resp));
}
}
#ifdef SCM_RIGHTS
static void
send_ro_fd (struct database_dyn *db, char *key, int fd)
{
/* If we do not have an read-only file descriptor do nothing. */
if (db->ro_fd == -1)
return;