This repository has been archived by the owner on Dec 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
nscd.c
2659 lines (2388 loc) · 71.4 KB
/
nscd.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
/* This file is part of unscd, a complete nscd replacement.
* Copyright (C) 2007-2012 Denys Vlasenko. Licensed under the GPL version 2.
*/
/* unscd 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.
*
* unscd 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 can download the GNU General Public License from the GNU website
* at http://www.gnu.org/ or write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */
/*
Build instructions:
gcc -Wall -Wunused-parameter -Os -o nscd nscd.c
gcc -fomit-frame-pointer -Wl,--sort-section -Wl,alignment -Wl,--sort-common
-Os -o nscd nscd.c
Description:
nscd problems are not exactly unheard of. Over the years, there were
quite a bit of bugs in it. This leads people to invent babysitters
which restart crashed/hung nscd. This is ugly.
After looking at nscd source in glibc I arrived to the conclusion
that its design is contributing to this significantly. Even if nscd's
code is 100.00% perfect and bug-free, it can still suffer from bugs
in libraries it calls.
As designed, it's a multithreaded program which calls NSS libraries.
These libraries are not part of libc, they may be provided
by third-party projects (samba, ldap, you name it).
Thus nscd cannot be sure that libraries it calls do not have memory
or file descriptor leaks and other bugs.
Since nscd is multithreaded program with single shared cache,
any resource leak in any NSS library has cumulative effect.
Even if a NSS library leaks a file descriptor 0.01% of the time,
this will make nscd crash or hang after some time.
Of course bugs in NSS .so modules should be fixed, but meanwhile
I do want nscd which does not crash or lock up.
So I went ahead and wrote a replacement.
It is a single-threaded server process which offloads all NSS
lookups to worker children (not threads, but fully independent
processes). Cache hits are handled by parent. Only cache misses
start worker children. This design is immune against
resource leaks and hangs in NSS libraries.
It is also many times smaller.
Currently (v0.36) it emulates glibc nscd pretty closely
(handles same command line flags and config file), and is moderately tested.
Please note that as of 2008-08 it is not in wide use (yet?).
If you have trouble compiling it, see an incompatibility with
"standard" one or experience hangs/crashes, please report it to
***********************************************************************/
/* Make struct ucred appear in sys/socket.h */
#define _GNU_SOURCE 1
/* For all good things */
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdarg.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <time.h>
#include <netdb.h>
#include <pwd.h>
#include <grp.h>
#include <getopt.h>
#include <syscall.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/poll.h>
#include <sys/un.h>
/* For INT_MAX */
#include <limits.h>
/* For inet_ntoa (for debug build only) */
#include <arpa/inet.h>
/*
* 0.21 add SEGV reporting to worker
* 0.22 don't do freeaddrinfo() in GETAI worker, it's crashy
* 0.23 add parameter parsing
* 0.24 add conf file parsing, not using results yet
* 0.25 used some of conf file settings (not tested)
* 0.26 almost all conf file settings are wired up
* 0.27 a bit more of almost all conf file settings are wired up
* 0.28 optimized cache aging
* 0.29 implemented invalidate and shutdown options
* 0.30 fixed buglet (sizeof(ptr) != sizeof(array))
* 0.31 reduced client_info by one member
* 0.32 fix nttl/size defaults; simpler check for worker child in main()
* 0.33 tweak includes so that it builds on my new machine (64-bit userspace);
* do not die on unknown service name, just warn
* ("services" is a new service we don't support)
* 0.34 create /var/run/nscd/nscd.pid pidfile like glibc nscd 2.8 does;
* delay setuid'ing itself to server-user after log and pidfile are open
* 0.35 readlink /proc/self/exe and use result if execing /proc/self/exe fails
* 0.36 excercise extreme paranoia handling server-user option;
* a little bit more verbose logging:
* L_DEBUG2 log level added, use debug-level 7 to get it
* 0.37 users reported over-zealous "detected change in /etc/passwd",
* apparently stat() returns random garbage in unused padding
* on some systems. Made the check less paranoid.
* 0.38 log POLLHUP better
* 0.39 log answers to client better, log getpwnam in the worker,
* pass debug level value down to worker.
* 0.40 fix handling of shutdown and invalidate requests;
* fix bug with answer written in several pieces
* 0.40.1 set hints.ai_socktype = SOCK_STREAM in GETAI request
* 0.41 eliminate double caching of two near-simultaneous identical requests -
* EXPERIMENTAL
* 0.42 execute /proc/self/exe by link name first (better comm field)
* 0.43 fix off-by-one error in setgroups
* 0.44 make -d[ddd] bump up debug - easier to explain to users
* how to produce detailed log (no nscd.conf tweaking)
* 0.45 Fix out-of-bounds array access and log/pid file permissions -
* thanks to Sebastian Krahmer (krahmer AT suse.de)
* 0.46 fix a case when we forgot to remove a future entry on worker failure
* 0.47 fix nscd without -d to not bump debug level
* 0.48 fix for changes in __nss_disable_nscd API in glibc-2.15
* 0.49 minor tweaks to messages
* 0.50 add more files to watch for changes
* 0.51 fix a case where we forget to refcount-- the cached entry
* 0.52 make free_refcounted_ureq() tolerant to pointers to NULLs
*/
#define PROGRAM_VERSION "0.52"
#define DEBUG_BUILD 1
/*
** Generic helpers
*/
#define ARRAY_SIZE(x) ((unsigned)(sizeof(x) / sizeof((x)[0])))
#define NORETURN __attribute__ ((__noreturn__))
#ifdef MY_CPU_HATES_CHARS
typedef int smallint;
#else
typedef signed char smallint;
#endif
enum {
L_INFO = (1 << 0),
L_DEBUG = ((1 << 1) * DEBUG_BUILD),
L_DEBUG2 = ((1 << 2) * DEBUG_BUILD),
L_DUMP = ((1 << 3) * DEBUG_BUILD),
L_ALL = 0xf,
D_DAEMON = (1 << 6),
D_STAMP = (1 << 5),
};
static smallint debug = D_DAEMON;
static void verror(const char *s, va_list p, const char *strerr)
{
char msgbuf[1024];
int sz, rem, strerr_len;
struct timeval tv;
sz = 0;
if (debug & D_STAMP) {
gettimeofday(&tv, NULL);
sz = sprintf(msgbuf, "%02u:%02u:%02u.%05u ",
(unsigned)((tv.tv_sec / (60*60)) % 24),
(unsigned)((tv.tv_sec / 60) % 60),
(unsigned)(tv.tv_sec % 60),
(unsigned)(tv.tv_usec / 10));
}
rem = sizeof(msgbuf) - sz;
sz += vsnprintf(msgbuf + sz, rem, s, p);
rem = sizeof(msgbuf) - sz; /* can be negative after this! */
if (strerr) {
strerr_len = strlen(strerr);
if (rem >= strerr_len + 4) { /* ": STRERR\n\0" */
msgbuf[sz++] = ':';
msgbuf[sz++] = ' ';
strcpy(msgbuf + sz, strerr);
sz += strerr_len;
}
}
if (rem >= 2) {
msgbuf[sz++] = '\n';
msgbuf[sz] = '\0';
}
fflush(NULL);
fputs(msgbuf, stderr);
}
static void error(const char *msg, ...)
{
va_list p;
va_start(p, msg);
verror(msg, p, NULL);
va_end(p);
}
static void error_and_die(const char *msg, ...) NORETURN;
static void error_and_die(const char *msg, ...)
{
va_list p;
va_start(p, msg);
verror(msg, p, NULL);
va_end(p);
_exit(1);
}
static void perror_and_die(const char *msg, ...) NORETURN;
static void perror_and_die(const char *msg, ...)
{
va_list p;
va_start(p, msg);
/* Guard against "<error message>: Success" */
verror(msg, p, errno ? strerror(errno) : NULL);
va_end(p);
_exit(1);
}
static void nscd_log(int mask, const char *msg, ...)
{
if (debug & mask) {
va_list p;
va_start(p, msg);
verror(msg, p, NULL);
va_end(p);
}
}
#define log(lvl, ...) do { if (lvl) nscd_log(lvl, __VA_ARGS__); } while (0)
#if DEBUG_BUILD
static void dump(const void *ptr, int len)
{
char text[18];
const unsigned char *buf;
char *p;
if (!(debug & L_DUMP))
return;
buf = ptr;
while (len > 0) {
int chunk = ((len >= 16) ? 16 : len);
fprintf(stderr,
"%02x %02x %02x %02x %02x %02x %02x %02x "
"%02x %02x %02x %02x %02x %02x %02x %02x " + (16-chunk) * 5,
buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7],
buf[8], buf[9],buf[10],buf[11],buf[12],buf[13],buf[14],buf[15]
);
fprintf(stderr, "%*s", (16-chunk) * 3, "");
len -= chunk;
p = text;
do {
unsigned char c = *buf++;
*p++ = (c >= 32 && c < 127 ? c : '.');
} while (--chunk);
*p++ = '\n';
*p = '\0';
fputs(text, stderr);
}
}
#else
void dump(const void *ptr, int len);
#endif
#define hex_dump(p,n) do { if (L_DUMP) dump(p,n); } while (0)
static int xopen3(const char *pathname, int flags, int mode)
{
int fd = open(pathname, flags, mode);
if (fd < 0)
perror_and_die("open");
return fd;
}
static void xpipe(int *fds)
{
if (pipe(fds) < 0)
perror_and_die("pipe");
}
static void xexecve(const char *filename, char **argv, char **envp) NORETURN;
static void xexecve(const char *filename, char **argv, char **envp)
{
execve(filename, argv, envp);
perror_and_die("cannot re-exec %s", filename);
}
static void ndelay_on(int fd)
{
int fl = fcntl(fd, F_GETFL);
if (fl < 0)
perror_and_die("F_GETFL");
if (fcntl(fd, F_SETFL, fl | O_NONBLOCK) < 0)
perror_and_die("setting O_NONBLOCK");
}
static void close_on_exec(int fd)
{
if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0)
perror_and_die("setting FD_CLOEXEC");
}
static unsigned monotonic_ms(void)
{
struct timespec ts;
if (syscall(__NR_clock_gettime, CLOCK_MONOTONIC, &ts))
perror_and_die("clock_gettime(MONOTONIC)");
return ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
}
static unsigned strsize(const char *str)
{
return strlen(str) + 1;
}
static unsigned strsize_aligned4(const char *str)
{
return (strlen(str) + 1 + 3) & (~3);
}
static ssize_t safe_read(int fd, void *buf, size_t count)
{
ssize_t n;
do {
n = read(fd, buf, count);
} while (n < 0 && errno == EINTR);
return n;
}
static ssize_t full_read(int fd, void *buf, size_t len)
{
ssize_t cc;
ssize_t total;
total = 0;
while (len) {
cc = safe_read(fd, buf, len);
if (cc < 0)
return cc; /* read() returns -1 on failure. */
if (cc == 0)
break;
buf = ((char *)buf) + cc;
total += cc;
len -= cc;
}
return total;
}
/* unused
static void xsafe_read(int fd, void *buf, size_t len)
{
if (len != safe_read(fd, buf, len))
perror_and_die("short read");
}
static void xfull_read(int fd, void *buf, size_t len)
{
if (len != full_read(fd, buf, len))
perror_and_die("short read");
}
*/
static ssize_t safe_write(int fd, const void *buf, size_t count)
{
ssize_t n;
do {
n = write(fd, buf, count);
} while (n < 0 && errno == EINTR);
return n;
}
static ssize_t full_write(int fd, const void *buf, size_t len)
{
ssize_t cc;
ssize_t total;
total = 0;
while (len) {
cc = safe_write(fd, buf, len);
if (cc < 0)
return cc; /* write() returns -1 on failure. */
total += cc;
buf = ((const char *)buf) + cc;
len -= cc;
}
return total;
}
static void xsafe_write(int fd, const void *buf, size_t count)
{
if (count != safe_write(fd, buf, count))
perror_and_die("short write of %ld bytes", (long)count);
}
static void xfull_write(int fd, const void *buf, size_t count)
{
if (count != full_write(fd, buf, count))
perror_and_die("short write of %ld bytes", (long)count);
}
static void xmovefd(int from_fd, int to_fd)
{
if (from_fd != to_fd) {
if (dup2(from_fd, to_fd) < 0)
perror_and_die("dup2");
close(from_fd);
}
}
static unsigned getnum(const char *str)
{
if (str[0] >= '0' && str[0] <= '9') {
char *p;
unsigned long l = strtoul(str, &p, 10);
/* must not overflow int even after x1000 */
if (!*p && l <= INT_MAX / 1000)
return l;
}
error_and_die("malformed or too big number '%s'", str);
};
static char *skip_whitespace(const char *s)
{
/* NB: isspace('\0') returns 0 */
while (isspace(*s)) ++s;
return (char *) s;
}
static char *skip_non_whitespace(const char *s)
{
while (*s && !isspace(*s)) ++s;
return (char *) s;
}
static void *xmalloc(unsigned sz)
{
void *p = malloc(sz);
if (!p)
error_and_die("out of memory");
return p;
}
static void *xzalloc(unsigned sz)
{
void *p = xmalloc(sz);
memset(p, 0, sz);
return p;
}
static void *xrealloc(void *p, unsigned size)
{
p = realloc(p, size);
if (!p)
error_and_die("out of memory");
return p;
}
static const char *xstrdup(const char *str)
{
const char *p = strdup(str);
if (!p)
error_and_die("out of memory");
return p;
}
/*
** Config data
*/
enum {
SRV_PASSWD,
SRV_GROUP,
SRV_HOSTS,
};
static const char srv_name[3][7] = {
"passwd",
"group",
"hosts"
};
static struct {
const char *logfile;
const char *user;
smallint srv_enable[3];
smallint check_files[3];
unsigned pttl[3];
unsigned nttl[3];
unsigned size[3];
} config = {
/* We try to closely mimic glibc nscd */
.logfile = NULL, /* default is to not have a log file */
.user = NULL,
.srv_enable = { 0, 0, 0 },
.check_files = { 1, 1, 1 },
.pttl = { 3600, 3600, 3600 },
.nttl = { 20, 60, 20 },
/* huh, what is the default cache size in glibc nscd? */
.size = { 256 * 8 / 3, 256 * 8 / 3, 256 * 8 / 3 },
};
static const char default_conffile[] = "/etc/nscd.conf";
static const char *self_exe_points_to = "/proc/self/exe";
/*
** Clients, workers machinery
*/
/* Header common to all requests */
#define USER_REQ_STRUCT \
uint32_t version; /* Version number of the daemon interface */ \
uint32_t type; /* Service requested */ \
uint32_t key_len; /* Key length */
typedef struct user_req_header {
USER_REQ_STRUCT
} user_req_header;
enum {
NSCD_VERSION = 2,
MAX_USER_REQ_SIZE = 1024,
USER_HDR_SIZE = sizeof(user_req_header),
/* DNS queries time out after 20 seconds,
* we will allow for a bit more */
WORKER_TIMEOUT_SEC = 30,
CLIENT_TIMEOUT_MS = 100,
SMALL_POLL_TIMEOUT_MS = 200,
};
typedef struct user_req {
union {
struct { /* as came from client */
USER_REQ_STRUCT
};
struct { /* when stored in cache, overlaps .version */
unsigned refcount:8;
/* (timestamp24 * 256) == timestamp in ms */
unsigned timestamp24:24;
};
};
char reqbuf[MAX_USER_REQ_SIZE - USER_HDR_SIZE];
} user_req;
/* Compile-time check for correct size */
struct BUG_wrong_user_req_size {
char BUG_wrong_user_req_size[sizeof(user_req) == MAX_USER_REQ_SIZE ? 1 : -1];
};
enum {
GETPWBYNAME,
GETPWBYUID,
GETGRBYNAME,
GETGRBYGID,
GETHOSTBYNAME,
GETHOSTBYNAMEv6,
GETHOSTBYADDR,
GETHOSTBYADDRv6,
SHUTDOWN, /* Shut the server down */
GETSTAT, /* Get the server statistic */
INVALIDATE, /* Invalidate one special cache */
GETFDPW,
GETFDGR,
GETFDHST,
GETAI,
INITGROUPS,
GETSERVBYNAME,
GETSERVBYPORT,
GETFDSERV,
LASTREQ
};
#if DEBUG_BUILD
static const char *const typestr[] = {
"GETPWBYNAME", /* done */
"GETPWBYUID", /* done */
"GETGRBYNAME", /* done */
"GETGRBYGID", /* done */
"GETHOSTBYNAME", /* done */
"GETHOSTBYNAMEv6", /* done */
"GETHOSTBYADDR", /* done */
"GETHOSTBYADDRv6", /* done */
"SHUTDOWN", /* done */
"GETSTAT", /* info? */
"INVALIDATE", /* done */
/* won't do: nscd passes a name of shmem segment
* which client can map and "see" the db */
"GETFDPW",
"GETFDGR", /* won't do */
"GETFDHST", /* won't do */
"GETAI", /* done */
"INITGROUPS", /* done */
"GETSERVBYNAME", /* prio 3 (no caching?) */
"GETSERVBYPORT", /* prio 3 (no caching?) */
"GETFDSERV" /* won't do */
};
#else
extern const char *const typestr[];
#endif
static const smallint type_to_srv[] = {
[GETPWBYNAME ] = SRV_PASSWD,
[GETPWBYUID ] = SRV_PASSWD,
[GETGRBYNAME ] = SRV_GROUP,
[GETGRBYGID ] = SRV_GROUP,
[GETHOSTBYNAME ] = SRV_HOSTS,
[GETHOSTBYNAMEv6 ] = SRV_HOSTS,
[GETHOSTBYADDR ] = SRV_HOSTS,
[GETHOSTBYADDRv6 ] = SRV_HOSTS,
[GETAI ] = SRV_HOSTS,
[INITGROUPS ] = SRV_GROUP,
};
static int unsupported_ureq_type(unsigned type)
{
if (type == GETAI) return 0;
if (type == INITGROUPS) return 0;
if (type == GETSTAT) return 1;
if (type > INVALIDATE) return 1;
return 0;
}
typedef struct client_info {
/* if client_fd != 0, we are waiting for the reply from worker
* on pfd[i].fd, and client_fd is saved client's fd
* (we need to put it back into pfd[i].fd later) */
int client_fd;
unsigned bytecnt; /* bytes read from client */
unsigned bufidx; /* buffer# in global client_buf[] */
unsigned started_ms;
unsigned respos; /* response */
user_req *resptr; /* response */
user_req **cache_pp; /* cache entry address */
user_req *ureq; /* request (points to client_buf[x]) */
} client_info;
static unsigned g_now_ms;
static int min_closed = INT_MAX;
static int cnt_closed = 0;
static int num_clients = 2; /* two listening sockets are "clients" too */
/* We read up to max_reqnum requests in parallel */
static unsigned max_reqnum = 14;
static int next_buf;
/* To be allocated at init to become client_buf[max_reqnum][MAX_USER_REQ_SIZE].
* Note: it is a pointer to [MAX_USER_REQ_SIZE] arrays,
* not [MAX_USER_REQ_SIZE] array of pointers.
*/
static char (*client_buf)[MAX_USER_REQ_SIZE];
static char *busy_cbuf;
static struct pollfd *pfd;
static client_info *cinfo;
/* Request, response and cache data structures:
*
* cache[] (defined later):
* cacheline_t cache[cache_size] array, or in other words,
* user_req* cache[cache_size][8] array.
* Every client request is hashed, hash value determines which cache[x]
* will have the response stored in one of its 8 elements.
* Cache entries have this format: request, then padding to 32 bits,
* then the response.
* Addresses in cache[x][y] may be NULL or:
* (&client_buf[z]) & 1: the cache miss is in progress ("future entry"):
* "the data is not in the cache (yet), wait for it to appear"
* (&client_buf[z]) & 3: the cache miss is in progress and other clients
* also want the same data ("shared future entry")
* else (non-NULL but low two bits are 0): cached data in malloc'ed block
*
* Each of these is a [max_reqnum] sized array:
* pfd[i] - given to poll() to wait for requests and replies.
* .fd: first two pfd[i]: listening Unix domain sockets, else
* .fd: open fd to a client, for reading client's request, or
* .fd: open fd to a worker, to send request and get response back
* cinfo[i] - auxiliary client data for pfd[i]
* .client_fd: open fd to a client, in case we already had read its
* request and got a cache miss, and created a worker or
* wait for another client's worker.
* Otherwise, it's 0 and client's fd is in pfd[i].fd
* .bufidx: index in client_buf[] we store client's request in
* .ureq: = client_buf[bufidx]
* .bytecnt: size of the request
* .started_ms: used to time out unresponsive clients
* .resptr: initially NULL. Later, same as cache[x][y] pointer to a cached
* response, or (a rare case) a "fake cache" entry:
* all cache[hash(request)][0..7] blocks were found busy,
* the result won't be cached.
* .respos: "write-out to client" offset
* .cache_pp: initially NULL. Later, &cache[x][y] where the response is,
* or will be stored. Remains NULL if "fake cache" entry is in use
*
* When a client has received its reply (or otherwise closed (timeout etc)),
* corresponding pfd[i] and cinfo[i] are removed by shifting [i+1], [i+2] etc
* elements down, so that both arrays never have free holes.
* [num_clients] is always the first free element.
*
* Each of these also is a [max_reqnum] sized array, but indexes
* do not correspond directly to pfd[i] and cinfo[i]:
* client_buf[n][MAX_USER_REQ_SIZE] - buffers we read client requests into
* busy_cbuf[n] - bool flags marking busy client_buf[]
*/
/* Possible reductions:
* fd, bufidx - uint8_t
* started_ms -> uint16_t started_s
* ureq - eliminate (derivable from bufidx?)
*/
/* Are special bits 0? is it a true cached entry? */
#define CACHED_ENTRY(p) ( ((long)(p) & 3) == 0 )
/* Are special bits 11? is it a shared future cache entry? */
#define CACHE_SHARED(p) ( ((long)(p) & 3) == 3 )
/* Return a ptr with special bits cleared (used for accessing data) */
#define CACHE_PTR(p) ( (void*) ((long)(p) & ~(long)3) )
/* Return a ptr with special bits set to x1: make future cache entry ptr */
#define MAKE_FUTURE_PTR(p) ( (void*) ((long)(p) | 1) )
/* Modify ptr, set special bits to 11: shared future cache entry */
#define MARK_PTR_SHARED(pp) ( *(long*)(pp) |= 3 )
static inline unsigned ureq_size(const user_req *ureq)
{
return sizeof(user_req_header) + ureq->key_len;
}
static unsigned cache_age(const user_req *ureq)
{
if (!CACHED_ENTRY(ureq))
return 0;
return (uint32_t) (g_now_ms - (ureq->timestamp24 << 8));
}
static void set_cache_timestamp(user_req *ureq)
{
ureq->timestamp24 = g_now_ms >> 8;
}
static int alloc_buf_no(void)
{
int n = next_buf;
do {
int cur = next_buf;
next_buf = (next_buf + 1) % max_reqnum;
if (!busy_cbuf[cur]) {
busy_cbuf[cur] = 1;
return cur;
}
} while (next_buf != n);
error_and_die("no free bufs?!");
}
static inline void *bufno2buf(int i)
{
return client_buf[i];
}
static void free_refcounted_ureq(user_req **ureqp);
static void close_client(unsigned i)
{
log(L_DEBUG, "closing client %u (fd %u,%u)", i, pfd[i].fd, cinfo[i].client_fd);
/* Paranoia. We had nasty bugs where client was closed twice. */
if (pfd[i].fd == 0)
return;
close(pfd[i].fd);
if (cinfo[i].client_fd && cinfo[i].client_fd != pfd[i].fd)
close(cinfo[i].client_fd);
pfd[i].fd = 0; /* flag as unused (coalescing needs this) */
busy_cbuf[cinfo[i].bufidx] = 0;
if (cinfo[i].cache_pp == NULL) {
user_req *resptr = cinfo[i].resptr;
if (resptr) {
log(L_DEBUG, "client %u: freeing fake cache entry %p", i, resptr);
free(resptr);
}
} else {
/* Most of the time, it is not freed here,
* only refcounted--. Freeing happens
* if it was deleted from cache[] but retained
* for writeout.
*/
free_refcounted_ureq(&cinfo[i].resptr);
}
cnt_closed++;
if (i < min_closed)
min_closed = i;
}
/*
** nscd API <-> C API conversion
*/
typedef struct response_header {
uint32_t version_or_size;
int32_t found;
char body[0];
} response_header;
typedef struct initgr_response_header {
uint32_t version_or_size;
int32_t found;
int32_t ngrps;
/* code assumes gid_t == int32, let's check that */
int32_t gid[sizeof(gid_t) == sizeof(int32_t) ? 0 : -1];
/* char user_str[as_needed]; */
} initgr_response_header;
static initgr_response_header *obtain_initgroups(const char *username)
{
struct initgr_response_header *resp;
struct passwd *pw;
enum { MAGIC_OFFSET = sizeof(*resp) / sizeof(int32_t) };
unsigned sz;
int ngroups;
pw = getpwnam(username);
if (!pw) {
resp = xzalloc(8);
resp->version_or_size = sizeof(*resp);
/*resp->found = 0;*/
/*resp->ngrps = 0;*/
goto ret;
}
/* getgrouplist may be very expensive, it's much better to allocate
* a bit more than to run getgrouplist twice */
ngroups = 128;
resp = NULL;
do {
sz = sizeof(*resp) + sizeof(resp->gid[0]) * ngroups;
resp = xrealloc(resp, sz);
} while (getgrouplist(username, pw->pw_gid, (gid_t*) &resp->gid, &ngroups) == -1);
log(L_DEBUG, "ngroups=%d", ngroups);
sz = sizeof(*resp) + sizeof(resp->gid[0]) * ngroups;
/* resp = xrealloc(resp, sz); - why bother */
resp->version_or_size = sz;
resp->found = 1;
resp->ngrps = ngroups;
ret:
return resp;
}
typedef struct pw_response_header {
uint32_t version_or_size;
int32_t found;
int32_t pw_name_len;
int32_t pw_passwd_len;
int32_t pw_uid;
int32_t pw_gid;
int32_t pw_gecos_len;
int32_t pw_dir_len;
int32_t pw_shell_len;
/* char pw_name[pw_name_len]; */
/* char pw_passwd[pw_passwd_len]; */
/* char pw_gecos[pw_gecos_len]; */
/* char pw_dir[pw_dir_len]; */
/* char pw_shell[pw_shell_len]; */
} pw_response_header;
static pw_response_header *marshal_passwd(struct passwd *pw)
{
char *p;
pw_response_header *resp;
unsigned pw_name_len;
unsigned pw_passwd_len;
unsigned pw_gecos_len;
unsigned pw_dir_len;
unsigned pw_shell_len;
unsigned sz = sizeof(*resp);
if (pw) {
sz += (pw_name_len = strsize(pw->pw_name));
sz += (pw_passwd_len = strsize(pw->pw_passwd));
sz += (pw_gecos_len = strsize(pw->pw_gecos));
sz += (pw_dir_len = strsize(pw->pw_dir));
sz += (pw_shell_len = strsize(pw->pw_shell));
}
resp = xzalloc(sz);
resp->version_or_size = sz;
if (!pw) {
/*resp->found = 0;*/
goto ret;
}
resp->found = 1;
resp->pw_name_len = pw_name_len;
resp->pw_passwd_len = pw_passwd_len;
resp->pw_uid = pw->pw_uid;
resp->pw_gid = pw->pw_gid;
resp->pw_gecos_len = pw_gecos_len;
resp->pw_dir_len = pw_dir_len;
resp->pw_shell_len = pw_shell_len;
p = (char*)(resp + 1);
strcpy(p, pw->pw_name); p += pw_name_len;
strcpy(p, pw->pw_passwd); p += pw_passwd_len;
strcpy(p, pw->pw_gecos); p += pw_gecos_len;
strcpy(p, pw->pw_dir); p += pw_dir_len;
strcpy(p, pw->pw_shell); p += pw_shell_len;
log(L_DEBUG, "sz:%u realsz:%u", sz, p - (char*)resp);
ret:
return resp;
}
typedef struct gr_response_header {
uint32_t version_or_size;
int32_t found;
int32_t gr_name_len; /* strlen(gr->gr_name) + 1; */
int32_t gr_passwd_len; /* strlen(gr->gr_passwd) + 1; */
int32_t gr_gid; /* gr->gr_gid */
int32_t gr_mem_cnt; /* while (gr->gr_mem[gr_mem_cnt]) ++gr_mem_cnt; */
/* int32_t gr_mem_len[gr_mem_cnt]; */
/* char gr_name[gr_name_len]; */
/* char gr_passwd[gr_passwd_len]; */
/* char gr_mem[gr_mem_cnt][gr_mem_len[i]]; */
/* char gr_gid_str[as_needed]; - huh? */
/* char orig_key[as_needed]; - needed?? I don't do this ATM... */
/*
glibc adds gr_gid_str, but client doesn't get/use it:
writev(3, [{"\2\0\0\0\2\0\0\0\5\0\0\0", 12}, {"root\0", 5}], 2) = 17
poll([{fd=3, events=POLLIN|POLLERR|POLLHUP, revents=POLLIN}], 1, 5000) = 1
read(3, "\2\0\0\0\1\0\0\0\10\0\0\0\4\0\0\0\0\0\0\0\0\0\0\0", 24) = 24
readv(3, [{"", 0}, {"root\0\0\0\0\0\0\0\0", 12}], 2) = 12
read(3, NULL, 0) = 0
*/
} gr_response_header;
static gr_response_header *marshal_group(struct group *gr)
{
char *p;
gr_response_header *resp;
unsigned gr_mem_cnt;
unsigned sz = sizeof(*resp);
if (gr) {
sz += strsize(gr->gr_name);
sz += strsize(gr->gr_passwd);
gr_mem_cnt = 0;
while (gr->gr_mem[gr_mem_cnt]) {
sz += strsize(gr->gr_mem[gr_mem_cnt]);
gr_mem_cnt++;
}
/* for int32_t gr_mem_len[gr_mem_cnt]; */
sz += gr_mem_cnt * sizeof(int32_t);
}
resp = xzalloc(sz);
resp->version_or_size = sz;
if (!gr) {
/*resp->found = 0;*/
goto ret;
}
resp->found = 1;
resp->gr_name_len = strsize(gr->gr_name);
resp->gr_passwd_len = strsize(gr->gr_passwd);
resp->gr_gid = gr->gr_gid;
resp->gr_mem_cnt = gr_mem_cnt;
p = (char*)(resp + 1);
/* int32_t gr_mem_len[gr_mem_cnt]; */
gr_mem_cnt = 0;
while (gr->gr_mem[gr_mem_cnt]) {
*(uint32_t*)p = strsize(gr->gr_mem[gr_mem_cnt]);
p += 4;
gr_mem_cnt++;
}
/* char gr_name[gr_name_len]; */
strcpy(p, gr->gr_name);
p += strsize(gr->gr_name);
/* char gr_passwd[gr_passwd_len]; */
strcpy(p, gr->gr_passwd);
p += strsize(gr->gr_passwd);
/* char gr_mem[gr_mem_cnt][gr_mem_len[i]]; */
gr_mem_cnt = 0;
while (gr->gr_mem[gr_mem_cnt]) {
strcpy(p, gr->gr_mem[gr_mem_cnt]);
p += strsize(gr->gr_mem[gr_mem_cnt]);