Whamcloud - gitweb
New tag 2.15.63
[fs/lustre-release.git] / lustre / utils / l_getidentity.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2016, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  */
31
32 #include <stdbool.h>
33 #include <stdlib.h>
34 #include <stdint.h>
35 #include <stdio.h>
36 #include <unistd.h>
37 #include <errno.h>
38 #include <string.h>
39 #include <pwd.h>
40 #include <grp.h>
41 #include <stdarg.h>
42 #include <stddef.h>
43 #include <libgen.h>
44 #include <syslog.h>
45 #include <sys/time.h>
46 #include <sys/types.h>
47 #include <sys/stat.h>
48 #include <fcntl.h>
49 #include <limits.h>
50 #include <ctype.h>
51 #include <nss.h>
52 #include <dlfcn.h>
53
54 #include <libcfs/util/param.h>
55 #include <linux/lnet/nidstr.h>
56 #include <linux/lustre/lustre_user.h>
57 #include <linux/lustre/lustre_idl.h>
58
59 #define PERM_PATHNAME "/etc/lustre/perm.conf"
60 #define LUSTRE_PASSWD "/etc/lustre/passwd"
61 #define LUSTRE_GROUP  "/etc/lustre/group"
62
63 #define L_GETIDENTITY_LOOKUP_CMD "lookup"
64 #define NSS_MODULES_MAX_NR 8
65 #define NSS_MODULE_NAME_SIZE 32
66 #define NSS_SYMBOL_NAME_LEN_MAX 256
67
68 static int nss_pw_buf_len;
69 static void *nss_pw_buf;
70 static int nss_grent_buf_len;
71 static void *nss_grent_buf;
72 static int g_n_nss_modules;
73 static int grent_mod_no = -1;
74
75 struct nss_module {
76         char name[NSS_MODULE_NAME_SIZE];
77         int (*getpwuid)(struct nss_module *mod, uid_t, struct passwd *pwd);
78         int (*getgrent)(struct nss_module *mod, struct group *result);
79         void (*endgrent)(struct nss_module *mod);
80         void (*fini)(struct nss_module *mod);
81
82         union {
83                 struct {
84                         void *l_ptr;
85                         int  (*l_getpwuid)(uid_t, struct passwd *pwd,
86                                            char *buffer, size_t buflen,
87                                            int *errnop);
88                         int  (*l_getgrent)(struct group *result, char *buffer,
89                                            size_t buflen, int *errnop);
90                         int  (*l_endgrent)(void);
91                 } lib;
92                 struct {
93                         FILE *f_passwd;
94                         FILE *f_group;
95                 } files;
96         } u;
97 };
98
99 static struct nss_module g_nss_modules[NSS_MODULES_MAX_NR];
100
101 #define NSS_LIB_NAME_PATTERN "libnss_%s.so.2"
102
103 /*
104  * permission file format is like this:
105  * {nid} {uid} {perms}
106  *
107  * '*' nid means any nid
108  * '*' uid means any uid
109  * the valid values for perms are:
110  * setuid/setgid/setgrp         -- enable corresponding perm
111  * nosetuid/nosetgid/nosetgrp   -- disable corresponding perm
112  * they can be listed together, separated by ',',
113  * when perm and noperm are in the same line (item), noperm is preferential,
114  * when they are in different lines (items), the latter is preferential,
115  * '*' nid is as default perm, and is not preferential.
116  */
117
118 static char *progname;
119
120 static void usage(void)
121 {
122         fprintf(stderr,
123                 "\nusage: %s {-d|mdtname} {uid}\n"
124                 "Normally invoked as an upcall from Lustre, set via:\n"
125                 "lctl set_param mdt.${mdtname}.identity_upcall={path to upcall}\n"
126                 "\t-d: debug, print values to stdout instead of Lustre\n"
127                 "\tNSS support enabled\n",
128                 progname);
129 }
130
131 static void errlog(const char *fmt, ...)
132 {
133         va_list args;
134
135         openlog(progname, LOG_PERROR | LOG_PID, LOG_AUTHPRIV);
136
137         va_start(args, fmt);
138         vsyslog(LOG_WARNING, fmt, args);
139         va_end(args);
140
141         closelog();
142 }
143
144 static int compare_gids(const void *v1, const void *v2)
145 {
146         return (*(gid_t *)v1 - *(gid_t *)v2);
147 }
148
149 /** getpwuid() replacement */
150 static struct passwd *getpwuid_nss(uid_t uid)
151 {
152         static struct passwd pw;
153         int i;
154
155         for (i = 0; i < g_n_nss_modules; i++) {
156                 struct nss_module *mod = g_nss_modules + i;
157
158                 if (mod->getpwuid(mod, uid, &pw) == 0)
159                         return &pw;
160         }
161         return NULL;
162 }
163
164 /**
165  * getgrent() replacement.
166  *  simulate getgrent(3) across nss modules
167  */
168 static struct group *getgrent_nss(void)
169 {
170         static struct group grp;
171
172         if (grent_mod_no < 0)
173                 grent_mod_no = 0;
174
175         while (grent_mod_no < g_n_nss_modules) {
176                 struct nss_module *mod = g_nss_modules + grent_mod_no;
177
178                 if (mod->getgrent(mod, &grp) == 0)
179                         return &grp;
180                 mod->endgrent(mod);
181                 grent_mod_no++;
182         }
183         return NULL;
184 }
185
186 /** endgrent() replacement */
187 static void endgrent_nss(void)
188 {
189         if (grent_mod_no < g_n_nss_modules
190                 && grent_mod_no >= 0) {
191                 struct nss_module *mod = g_nss_modules+grent_mod_no;
192
193                 mod->endgrent(mod);
194         }
195         grent_mod_no = -1;
196 }
197
198 /** lookup symbol in dynamically loaded nss module */
199 static void *get_nss_sym(struct nss_module *mod, const char *op)
200 {
201         void *res;
202         int bytes;
203         char symbuf[NSS_SYMBOL_NAME_LEN_MAX];
204
205         bytes = snprintf(symbuf, NSS_SYMBOL_NAME_LEN_MAX - 1, "_nss_%s_%s",
206                         mod->name, op);
207         if (bytes >= NSS_SYMBOL_NAME_LEN_MAX - 1) {
208                 errlog("symbol name too long\n");
209                 return NULL;
210         }
211         res = dlsym(mod->u.lib.l_ptr, symbuf);
212         if (res == NULL)
213                 errlog("cannot find symbol %s in nss module \"%s\": %s\n",
214                         symbuf, mod->name, dlerror());
215         return res;
216 }
217
218 /** allocate bigger buffer */
219 static void enlarge_nss_buffer(void **buf, int *bufsize)
220 {
221         free(*buf);
222         *bufsize = *bufsize * 2;
223         *buf = malloc(*bufsize);
224         if (*buf == NULL) {
225                 errlog("no memory to allocate bigger buffer of %d bytes\n",
226                         *bufsize);
227                 exit(-1);
228         }
229 }
230
231 static int getpwuid_nss_lib(struct nss_module *nss, uid_t uid,
232                             struct passwd *pw)
233 {
234         int tmp_errno, err;
235
236         while (1) {
237                 err = nss->u.lib.l_getpwuid(uid, pw, nss_pw_buf,
238                                 nss_pw_buf_len, &tmp_errno);
239                 if (err == NSS_STATUS_TRYAGAIN) {
240                         if (tmp_errno == ERANGE) {
241                                 /* buffer too small */
242                                 enlarge_nss_buffer(&nss_pw_buf,
243                                                 &nss_pw_buf_len);
244                         }
245                         continue;
246                 }
247                 break;
248         }
249         if (err == NSS_STATUS_SUCCESS)
250                 return 0;
251         return -ENOENT;
252 }
253
254 static int getgrent_nss_lib(struct nss_module *nss, struct group *gr)
255 {
256         int tmp_errno, err;
257
258         while (1) {
259                 err = nss->u.lib.l_getgrent(gr, nss_grent_buf,
260                                 nss_grent_buf_len, &tmp_errno);
261                 if (err == NSS_STATUS_TRYAGAIN) {
262                         if (tmp_errno == ERANGE) {
263                                 /* buffer too small */
264                                 enlarge_nss_buffer(&nss_grent_buf,
265                                                 &nss_grent_buf_len);
266                         }
267                         continue;
268                 }
269                 break;
270         }
271         if (err == NSS_STATUS_SUCCESS)
272                 return 0;
273         return -ENOENT;
274 }
275
276 static void endgrent_nss_lib(struct nss_module *mod)
277 {
278         mod->u.lib.l_endgrent();
279 }
280
281 /** destroy a "shared lib" nss module */
282 static void fini_nss_lib_module(struct nss_module *mod)
283 {
284         if (mod->u.lib.l_ptr)
285                 dlclose(mod->u.lib.l_ptr);
286 }
287
288 /** load and initialize a "shared lib" nss module */
289 static int init_nss_lib_module(struct nss_module *mod, char *name)
290 {
291         char lib_file_name[sizeof(NSS_LIB_NAME_PATTERN) + sizeof(mod->name)];
292
293         if (strlen(name) >= sizeof(mod->name)) {
294                 errlog("module name (%s) too long\n", name);
295                 exit(1);
296         }
297
298         strncpy(mod->name, name, sizeof(mod->name));
299         mod->name[sizeof(mod->name) - 1] = '\0';
300
301         snprintf(lib_file_name, sizeof(lib_file_name), NSS_LIB_NAME_PATTERN,
302                  name);
303
304         mod->getpwuid = getpwuid_nss_lib;
305         mod->getgrent = getgrent_nss_lib;
306         mod->endgrent = endgrent_nss_lib;
307         mod->fini = fini_nss_lib_module;
308
309         mod->u.lib.l_ptr = dlopen(lib_file_name, RTLD_NOW);
310         if (mod->u.lib.l_ptr == NULL) {
311                 errlog("dl error %s\n", dlerror());
312                 exit(1);
313         }
314         mod->u.lib.l_getpwuid = get_nss_sym(mod, "getpwuid_r");
315         if (mod->getpwuid == NULL)
316                 exit(1);
317
318         mod->u.lib.l_getgrent = get_nss_sym(mod, "getgrent_r");
319         if (mod->getgrent == NULL)
320                 exit(1);
321
322         mod->u.lib.l_endgrent = get_nss_sym(mod, "endgrent");
323         if (mod->endgrent == NULL)
324                 exit(1);
325
326         return 0;
327 }
328
329 static void fini_lustre_nss_module(struct nss_module *mod)
330 {
331         if (mod->u.files.f_passwd)
332                 fclose(mod->u.files.f_passwd);
333         if (mod->u.files.f_group)
334                 fclose(mod->u.files.f_group);
335 }
336
337 static int getpwuid_lustre_nss(struct nss_module *mod, uid_t uid,
338                               struct passwd *pw)
339 {
340         struct passwd *pos;
341
342         while ((pos = fgetpwent(mod->u.files.f_passwd)) != NULL) {
343                 if (pos->pw_uid == uid) {
344                         *pw = *pos;
345                         return 0;
346                 }
347         }
348         return -1;
349 }
350
351 static int getgrent_lustre_nss(struct nss_module *mod, struct group *gr)
352 {
353         struct group *pos;
354
355         pos = fgetgrent(mod->u.files.f_group);
356         if (pos) {
357                 *gr = *pos;
358                 return 0;
359         }
360         return 1;
361 }
362
363 static void endgrent_lustre_nss(struct nss_module *mod)
364 {
365 }
366
367 /** initialize module to access local /etc/lustre/passwd,group files */
368 static int init_lustre_module(struct nss_module *mod)
369 {
370         mod->fini = fini_lustre_nss_module;
371         mod->getpwuid = getpwuid_lustre_nss;
372         mod->getgrent = getgrent_lustre_nss;
373         mod->endgrent = endgrent_lustre_nss;
374
375         mod->u.files.f_passwd = fopen(LUSTRE_PASSWD, "r");
376         if (mod->u.files.f_passwd == NULL)
377                 exit(1);
378
379         mod->u.files.f_group = fopen(LUSTRE_GROUP, "r");
380         if (mod->u.files.f_group == NULL)
381                 exit(1);
382
383         snprintf(mod->name, sizeof(mod->name), "lustre");
384         return 0;
385 }
386
387 /** load and initialize the "nss" system */
388 static void init_nss(void)
389 {
390         nss_pw_buf_len = sysconf(_SC_GETPW_R_SIZE_MAX);
391         if (nss_pw_buf_len == -1) {
392                 perror("sysconf");
393                 exit(1);
394         }
395         nss_pw_buf = malloc(nss_pw_buf_len);
396         if (nss_pw_buf == NULL) {
397                 perror("pw buffer allocation");
398                 exit(1);
399         }
400
401         nss_grent_buf_len = sysconf(_SC_GETGR_R_SIZE_MAX);
402         if (nss_grent_buf_len == -1) {
403                 perror("sysconf");
404                 exit(1);
405         }
406         nss_grent_buf = malloc(nss_grent_buf_len);
407         if (nss_grent_buf == NULL) {
408                 perror("grent buffer allocation");
409                 exit(1);
410         }
411 }
412
413 /** unload "nss" */
414 static void fini_nss(void)
415 {
416         int i;
417
418         for (i = 0; i < g_n_nss_modules; i++) {
419                 struct nss_module *mod = g_nss_modules + i;
420
421                 mod->fini(mod);
422         }
423
424         free(nss_pw_buf);
425         free(nss_grent_buf);
426 }
427
428 /** get supplementary group info and fill downcall data */
429 static int get_groups_nss(struct identity_downcall_data *data,
430                           unsigned int maxgroups)
431 {
432         struct passwd *pw;
433         struct group *gr;
434         gid_t *groups;
435         unsigned int ngroups = 0;
436         char *pw_name;
437         int i;
438
439         pw = getpwuid_nss(data->idd_uid);
440         if (pw == NULL) {
441                 data->idd_err = errno ? errno : EIDRM;
442                 errlog("no such user %u\n", data->idd_uid);
443                 return -1;
444         }
445
446         data->idd_gid = pw->pw_gid;
447         pw_name = strdup(pw->pw_name);
448         groups = data->idd_groups;
449
450         while ((gr = getgrent_nss()) != NULL && ngroups < maxgroups) {
451                 if (gr->gr_gid == pw->pw_gid)
452                         continue;
453                 if (!gr->gr_mem)
454                         continue;
455                 for (i = 0; gr->gr_mem[i]; i++) {
456                         if (!strcmp(gr->gr_mem[i], pw_name)) {
457                                 groups[ngroups++] = gr->gr_gid;
458                                 break;
459                         }
460                 }
461         }
462
463         endgrent_nss();
464
465         if (ngroups > 0)
466                 qsort(groups, ngroups, sizeof(*groups), compare_gids);
467         data->idd_ngroups = ngroups;
468
469         free(pw_name);
470         return 0;
471 }
472
473 int get_groups_local(struct identity_downcall_data *data,
474                      unsigned int maxgroups)
475 {
476         gid_t *groups, *groups_tmp = NULL;
477         unsigned int ngroups = 0;
478         int ngroups_tmp;
479         struct passwd *pw;
480         int i;
481
482         pw = getpwuid(data->idd_uid);
483         if (!pw) {
484                 errlog("no such user %u\n", data->idd_uid);
485                 data->idd_err = errno ? errno : EIDRM;
486                 return -1;
487         }
488
489         data->idd_gid = pw->pw_gid;
490
491         groups = data->idd_groups;
492
493         /*
494          * Allocate array of size maxgroups instead of handling two
495          * consecutive and potentially racy getgrouplist() calls.
496          */
497         groups_tmp = malloc(maxgroups * sizeof(gid_t));
498         if (!groups_tmp) {
499                 data->idd_err = errno ? errno : ENOMEM;
500                 errlog("malloc error=%u\n", data->idd_err);
501                 return -1;
502         }
503
504         ngroups_tmp = maxgroups;
505         if (getgrouplist(pw->pw_name, pw->pw_gid, groups_tmp, &ngroups_tmp) <
506             0) {
507                 free(groups_tmp);
508                 data->idd_err = errno ? errno : EIDRM;
509                 errlog("getgrouplist() error for uid %u: error=%u\n",
510                        data->idd_uid, data->idd_err);
511                 return -1;
512         }
513
514         /* Do not place user's group ID in to the resulting groups list */
515         for (i = 0; i < ngroups_tmp; i++)
516                 if (pw->pw_gid != groups_tmp[i])
517                         groups[ngroups++] = groups_tmp[i];
518
519         if (ngroups > 0)
520                 qsort(groups, ngroups, sizeof(*groups), compare_gids);
521         data->idd_ngroups = ngroups;
522
523         free(groups_tmp);
524         return 0;
525 }
526
527 int get_groups_common(struct identity_downcall_data *data,
528                       unsigned int maxgroups)
529 {
530         if (g_n_nss_modules)
531                 return get_groups_nss(data, maxgroups);
532         return get_groups_local(data, maxgroups);
533 }
534
535 static inline int comment_line(char *line)
536 {
537         char *p = line;
538
539         while (*p && (*p == ' ' || *p == '\t'))
540                 p++;
541
542         if (!*p || *p == '\n' || *p == '#')
543                 return 1;
544         return 0;
545 }
546
547 static inline int match_uid(uid_t uid, const char *str)
548 {
549         char *end;
550         uid_t uid2;
551
552         if (!strcmp(str, "*"))
553                 return -1;
554
555         uid2 = strtoul(str, &end, 0);
556         if (*end)
557                 return 0;
558         return (uid == uid2);
559 }
560
561 struct perm_type {
562         char *name;
563         __u32 bit;
564 };
565
566 static struct perm_type perm_types[] = {
567         { "setuid", CFS_SETUID_PERM },
568         { "setgid", CFS_SETGID_PERM },
569         { "setgrp", CFS_SETGRP_PERM },
570         { "rmtacl", 0 },
571         { "rmtown", 0 },
572         { 0 }
573 };
574
575 static struct perm_type noperm_types[] = {
576         { "nosetuid", CFS_SETUID_PERM },
577         { "nosetgid", CFS_SETGID_PERM },
578         { "nosetgrp", CFS_SETGRP_PERM },
579         { "normtacl", 0 },
580         { "normtown", 0 },
581         { 0 }
582 };
583
584 int parse_perm(__u32 *perm, __u32 *noperm, char *str)
585 {
586         char *start, *end;
587         char name[64];
588         struct perm_type *pt;
589
590         *perm = 0;
591         *noperm = 0;
592         start = str;
593         while (1) {
594                 size_t len;
595
596                 memset(name, 0, sizeof(name));
597                 end = strchr(start, ',');
598                 if (!end)
599                         end = str + strlen(str);
600                 if (start >= end)
601                         break;
602                 len = end - start;
603                 if (len >= sizeof(name))
604                         return -E2BIG;
605                 strncpy(name, start, len);
606                 name[len] = '\0';
607                 for (pt = perm_types; pt->name; pt++) {
608                         if (!strcasecmp(name, pt->name)) {
609                                 *perm |= pt->bit;
610                                 break;
611                         }
612                 }
613
614                 if (!pt->name) {
615                         for (pt = noperm_types; pt->name; pt++) {
616                                 if (!strcasecmp(name, pt->name)) {
617                                         *noperm |= pt->bit;
618                                         break;
619                                 }
620                         }
621
622                         if (!pt->name) {
623                                 printf("unkown type: %s\n", name);
624                                 return -1;
625                         }
626                 }
627
628                 start = end + 1;
629         }
630         return 0;
631 }
632
633 static int
634 parse_perm_line(struct identity_downcall_data *data, char *line, size_t size)
635 {
636         char uid_str[size];
637         char nid_str[size];
638         char perm_str[size];
639         lnet_nid_t nid;
640         __u32 perm, noperm;
641         int rc, i;
642
643         if (data->idd_nperms >= N_PERMS_MAX) {
644                 errlog("permission count %d > max %d\n",
645                        data->idd_nperms, N_PERMS_MAX);
646                 return -1;
647         }
648
649         rc = sscanf(line, "%s %s %s", nid_str, uid_str, perm_str);
650         if (rc != 3) {
651                 errlog("can't parse line %s\n", line);
652                 return -1;
653         }
654
655         if (!match_uid(data->idd_uid, uid_str))
656                 return 0;
657
658         if (!strcmp(nid_str, "*")) {
659                 nid = LNET_NID_ANY;
660         } else {
661                 nid = libcfs_str2nid(nid_str);
662                 if (nid == LNET_NID_ANY) {
663                         errlog("can't parse nid %s\n", nid_str);
664                         return -1;
665                 }
666         }
667
668         if (parse_perm(&perm, &noperm, perm_str)) {
669                 errlog("invalid perm %s\n", perm_str);
670                 return -1;
671         }
672
673         /*
674          * merge the perms with the same nid.
675          *
676          * If there is LNET_NID_ANY in data->idd_perms[i].pdd_nid,
677          * it must be data->idd_perms[0].pdd_nid, and act as default perm.
678          */
679         if (nid != LNET_NID_ANY) {
680                 int found = 0;
681
682                 /* search for the same nid */
683                 for (i = data->idd_nperms - 1; i >= 0; i--) {
684                         if (data->idd_perms[i].pdd_nid == nid) {
685                                 data->idd_perms[i].pdd_perm =
686                                         (data->idd_perms[i].pdd_perm | perm) &
687                                         ~noperm;
688                                 found = 1;
689                                 break;
690                         }
691                 }
692
693                 /* NOT found, add to tail */
694                 if (!found) {
695                         data->idd_perms[data->idd_nperms].pdd_nid = nid;
696                         data->idd_perms[data->idd_nperms].pdd_perm =
697                                 perm & ~noperm;
698                         data->idd_nperms++;
699                 }
700         } else {
701                 if (data->idd_nperms > 0) {
702                         /* the first one isn't LNET_NID_ANY, need exchange */
703                         if (data->idd_perms[0].pdd_nid != LNET_NID_ANY) {
704                                 data->idd_perms[data->idd_nperms].pdd_nid =
705                                         data->idd_perms[0].pdd_nid;
706                                 data->idd_perms[data->idd_nperms].pdd_perm =
707                                         data->idd_perms[0].pdd_perm;
708                                 data->idd_perms[0].pdd_nid = LNET_NID_ANY;
709                                 data->idd_perms[0].pdd_perm = perm & ~noperm;
710                                 data->idd_nperms++;
711                         } else {
712                                 /* only fix LNET_NID_ANY item */
713                                 data->idd_perms[0].pdd_perm =
714                                         (data->idd_perms[0].pdd_perm | perm) &
715                                         ~noperm;
716                         }
717                 } else {
718                         /* it is the first one, only add to head */
719                         data->idd_perms[0].pdd_nid = LNET_NID_ANY;
720                         data->idd_perms[0].pdd_perm = perm & ~noperm;
721                         data->idd_nperms = 1;
722                 }
723         }
724
725         return 0;
726 }
727
728 static char *striml(char *s)
729 {
730         while (isspace(*s))
731                 s++;
732         return s;
733 }
734
735 static void check_new_nss_module(struct nss_module *mod)
736 {
737         int i;
738
739         for (i = 0; i < g_n_nss_modules; i++) {
740                 struct nss_module *pos = g_nss_modules + i;
741
742                 if (!strcmp(mod->name, pos->name)) {
743                         errlog("attempt to initialize \"%s\" module twice\n",
744                                 pos->name);
745                         exit(-1);
746                 }
747         }
748 }
749
750 #define ONE_DAY (24 * 60 * 60)
751
752 static void do_warn_interval(struct timeval *now)
753 {
754         bool write_warning = false;
755         bool show_warning = false;
756         const char *perm_warning = PERM_PATHNAME "-warning";
757         struct stat sbuf;
758         const char msg[] =
759                 "Use 'lookup lustre'. The 'files' alias is deprecated.\n";
760
761         if (stat(perm_warning, &sbuf)) {
762                 if (errno == ENOENT)
763                         write_warning = true;
764         } else {
765                 show_warning = (now->tv_sec - sbuf.st_mtim.tv_sec) > ONE_DAY;
766                 write_warning = sbuf.st_size == 0; /* file still empty? */
767         }
768
769         if (write_warning || show_warning) {
770                 const struct timespec times[] = {
771                         {.tv_sec = UTIME_NOW},
772                         {.tv_sec = UTIME_NOW},
773                 };
774                 mode_t mode = 0640;
775                 int oflags = O_RDWR | O_CREAT;
776                 int fd = open(perm_warning, oflags, mode);
777
778                 /* if we cannot rate-limit ... better to be quiet */
779                 if (fd == -1)
780                         return;
781                 if (write_warning) {
782                         ssize_t written = write(fd, msg, sizeof(msg));
783
784                         /* unlikely, but rate-limiting may be broken */
785                         if (written <= 0)
786                                 goto out_close;
787                 }
788                 errlog("WARNING: %s", msg);
789
790                 /* rate limiting is working */
791                 if (show_warning)
792                         if (futimens(fd, times) < 0)
793                                 errlog("Change Timestamp failed: %s\n",
794                                        strerror(errno));
795 out_close:
796                 close(fd);
797         }
798 }
799
800 /** initialize module to access local /etc/lustre/passwd,group files */
801 static int init_lustre_files_module(struct nss_module *mod,
802                                     struct timeval *start)
803 {
804         do_warn_interval(start);
805         return init_lustre_module(mod);
806 }
807
808 /**
809  * Check and parse lookup db config line.
810  * File should start with 'lookup' followed by the modules
811  * to be loaded, for example:
812  *
813  *  [/etc/lustre/perm.conf]
814  *  lookup lustre ldap
815  *
816  * Should search, in order, first found wins:
817  *    lustre [/etc/lustre/passwd and /etc/lustre/group]
818  *    ldap
819  *
820  * Other common nss modules: nis sss db files
821  * Since historically 'files' has been used exclusively
822  *  to mean 'lustre auth files' and disabled using local auth
823  *  via libnss_files users must select 'nss_files' to explicitly
824  *  enable libnss_files, which is an uncommon configuration.
825  */
826 static int lookup_db_line_nss(char *line, struct timeval *start)
827 {
828         char *p, *tok;
829         int ret = 0;
830
831         p = striml(line);
832         if (strncmp(p, L_GETIDENTITY_LOOKUP_CMD,
833             sizeof(L_GETIDENTITY_LOOKUP_CMD) - 1))
834                 return -EAGAIN;
835
836         tok = strtok(p, " \t");
837         if (tok == NULL || strcmp(tok, L_GETIDENTITY_LOOKUP_CMD))
838                 return -EIO;
839
840         while ((tok = strtok(NULL, " \t\n")) != NULL) {
841                 struct nss_module *newmod = NULL;
842
843                 if (g_n_nss_modules < NSS_MODULES_MAX_NR)
844                         newmod = &g_nss_modules[g_n_nss_modules];
845                 else
846                         return -ERANGE;
847
848                 if (!strcmp(tok, "files"))
849                         ret = init_lustre_files_module(newmod, start);
850                 else if (!strcmp(tok, "lustre"))
851                         ret = init_lustre_module(newmod);
852                 else if (!strcmp(tok, "nss_files"))
853                         ret = init_nss_lib_module(newmod, "files");
854                 else
855                         ret = init_nss_lib_module(newmod, tok);
856
857                 if (ret)
858                         break;
859                 check_new_nss_module(newmod);
860                 g_n_nss_modules++;
861         }
862
863         return ret;
864 }
865
866 int get_perms(struct identity_downcall_data *data, struct timeval *start)
867 {
868         FILE *fp;
869         char line[PATH_MAX];
870         int ret;
871
872         fp = fopen(PERM_PATHNAME, "r");
873         if (!fp) {
874                 if (errno == ENOENT)
875                         return 0;
876                 errlog("open %s failed: %s\n",
877                        PERM_PATHNAME, strerror(errno));
878                 data->idd_err = errno;
879                 return -1;
880         }
881
882         while (fgets(line, sizeof(line), fp)) {
883                 if (comment_line(line))
884                         continue;
885                 ret = lookup_db_line_nss(line, start); /* lookup parsed */
886                 if (ret == 0)
887                         continue;
888                 if (parse_perm_line(data, line, sizeof(line))) {
889                         errlog("parse line %s failed!\n", line);
890                         data->idd_err = EINVAL;
891                         fclose(fp);
892                         return -1;
893                 }
894         }
895
896         fclose(fp);
897         return 0;
898 }
899
900 static void show_result(struct identity_downcall_data *data)
901 {
902         int i;
903
904         if (data->idd_err) {
905                 errlog("failed to get identity for uid %d: %s\n",
906                        data->idd_uid, strerror(data->idd_err));
907                 return;
908         }
909
910         printf("uid=%d gid=%d", data->idd_uid, data->idd_gid);
911         for (i = 0; i < data->idd_ngroups; i++)
912                 printf(",%u", data->idd_groups[i]);
913         printf("\n");
914         printf("permissions:\n"
915                "  nid\t\t\tperm\n");
916         for (i = 0; i < data->idd_nperms; i++) {
917                 struct perm_downcall_data *pdd;
918
919                 pdd = &data->idd_perms[i];
920
921                 printf("  %#jx\t0x%x\n", (uintmax_t)pdd->pdd_nid,
922                        pdd->pdd_perm);
923         }
924         printf("\n");
925 }
926
927 #define difftime(a, b)                                  \
928         ((a).tv_sec - (b).tv_sec +                      \
929          ((a).tv_usec - (b).tv_usec) / 1000000.0)
930
931 int main(int argc, char **argv)
932 {
933         char *end;
934         struct identity_downcall_data *data = NULL;
935         glob_t path;
936         unsigned long uid;
937         struct timeval start, idgot, fini;
938         int fd, rc = -EINVAL, size, maxgroups;
939         bool alreadyfailed = false;
940
941         progname = basename(argv[0]);
942         if (argc != 3) {
943                 usage();
944                 goto out_no_nss;
945         }
946
947         errno = 0;
948         uid = strtoul(argv[2], &end, 0);
949         if (*end != '\0' || end == argv[2] || errno != 0) {
950                 errlog("%s: invalid uid '%s'\n", progname, argv[2]);
951                 goto out_no_nss;
952         }
953         gettimeofday(&start, NULL);
954
955         maxgroups = sysconf(_SC_NGROUPS_MAX);
956         if (maxgroups > NGROUPS_MAX)
957                 maxgroups = NGROUPS_MAX;
958         if (maxgroups == -1) {
959                 rc = -EINVAL;
960                 goto out_no_nss;
961         }
962
963 retry:
964         size = offsetof(struct identity_downcall_data, idd_groups[maxgroups]);
965         data = malloc(size);
966         if (!data) {
967                 errlog("malloc identity downcall data(%d) failed!\n", size);
968                 if (!alreadyfailed) {
969                         alreadyfailed = true;
970                         goto retry;
971                 }
972                 rc = -ENOMEM;
973                 goto out_no_nss;
974         }
975
976         memset(data, 0, size);
977         data->idd_magic = IDENTITY_DOWNCALL_MAGIC;
978         data->idd_uid = uid;
979
980         init_nss();
981
982         /* read permission database and/or load nss modules
983          * rc is -1 only when file exists and is not readable or
984          * content has format / syntax errors
985          */
986         rc = get_perms(data, &start);
987         if (rc)
988                 goto downcall;
989
990         /* get groups for uid */
991         rc = get_groups_common(data, maxgroups);
992         if (rc)
993                 goto downcall;
994
995         size = offsetof(struct identity_downcall_data,
996                         idd_groups[data->idd_ngroups]);
997
998         gettimeofday(&idgot, NULL);
999 downcall:
1000         if (strcmp(argv[1], "-d") == 0 || getenv("L_GETIDENTITY_TEST")) {
1001                 show_result(data);
1002                 rc = 0;
1003                 goto out;
1004         }
1005
1006         rc = cfs_get_param_paths(&path, "mdt/%s/identity_info", argv[1]);
1007         if (rc != 0) {
1008                 rc = -errno;
1009                 goto out;
1010         }
1011
1012         fd = open(path.gl_pathv[0], O_WRONLY);
1013         if (fd < 0) {
1014                 errlog("can't open file '%s':%s\n", path.gl_pathv[0],
1015                        strerror(errno));
1016                 rc = -errno;
1017                 goto out_params;
1018         }
1019
1020         rc = write(fd, data, size);
1021         gettimeofday(&fini, NULL);
1022         close(fd);
1023         if (rc != size) {
1024                 errlog("partial write ret %d: %s\n", rc, strerror(errno));
1025                 if (!alreadyfailed) {
1026                         alreadyfailed = true;
1027                         cfs_free_param_data(&path);
1028                         if (data)
1029                                 free(data);
1030                         goto retry;
1031                 }
1032                 rc = -1;
1033         } else {
1034                 rc = 0;
1035         }
1036         /* log if it takes more than 20 second to avoid rate limite */
1037         if (rc || difftime(fini, start) > 20)
1038                 errlog("get identity for uid %lu start time %ld.%06ld got time %ld.%06ld end time %ld.%06ld: rc = %d\n",
1039                        uid, start.tv_sec, start.tv_usec, idgot.tv_sec,
1040                        idgot.tv_usec, fini.tv_sec, fini.tv_usec, rc);
1041
1042 out_params:
1043         cfs_free_param_data(&path);
1044 out:
1045         fini_nss();
1046 out_no_nss:
1047         if (data)
1048                 free(data);
1049         return rc;
1050 }