]> git.decadent.org.uk Git - nfs-utils.git/blob - support/nsm/file.c
rpc.idmapd: Sections in idmapd.conf are ignored.
[nfs-utils.git] / support / nsm / file.c
1 /*
2  * Copyright 2009 Oracle.  All rights reserved.
3  *
4  * This file is part of nfs-utils.
5  *
6  * nfs-utils is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * nfs-utils is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with nfs-utils.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 /*
21  * NSM for Linux.
22  *
23  * Callback information and NSM state is stored in files, usually
24  * under /var/lib/nfs.  A database of information contained in local
25  * files stores NLM callback data and what remote peers to notify of
26  * reboots.
27  *
28  * For each monitored remote peer, a text file is created under the
29  * directory specified by NSM_MONITOR_DIR.  The name of the file
30  * is a valid DNS hostname.  The hostname string must be a valid
31  * ASCII DNS name, and must not contain slash characters, white space,
32  * or '\0' (ie. anything that might have some special meaning in a
33  * path name).
34  *
35  * The contents of each file include seven blank-separated fields of
36  * text, finished with '\n'.  The first field contains the network
37  * address of the NLM service to call back.  The current implementation
38  * supports using only IPv4 addresses, so the only contents of this
39  * field are a network order IPv4 address expressed in 8 hexadecimal
40  * characters.
41  *
42  * The next four fields are text strings of hexadecimal characters,
43  * representing:
44  *
45  * 2. A 4 byte RPC program number of the NLM service to call back
46  * 3. A 4 byte RPC version number of the NLM service to call back
47  * 4. A 4 byte RPC procedure number of the NLM service to call back
48  * 5. A 16 byte opaque cookie that the NLM service uses to identify
49  *    the monitored host
50  *
51  * The sixth field is the monitored host's mon_name, passed to statd
52  * via an SM_MON request.
53  *
54  * The seventh field is the my_name for this peer, which is the
55  * hostname of the local NLM (currently on Linux, the result of
56  * `uname -n`).  This can be used as the source address/hostname
57  * when sending SM_NOTIFY requests.
58  *
59  * The NSM protocol does not limit the contents of these strings
60  * in any way except that they must fit into 1024 bytes.  Our
61  * implementation requires that these strings not contain
62  * white space or '\0'.
63  */
64
65 #ifdef HAVE_CONFIG_H
66 #include <config.h>
67 #endif
68
69 #include <sys/types.h>
70 #ifdef HAVE_SYS_CAPABILITY_H
71 #include <sys/capability.h>
72 #endif
73 #include <sys/prctl.h>
74 #include <sys/stat.h>
75
76 #include <ctype.h>
77 #include <string.h>
78 #include <stdint.h>
79 #ifndef S_SPLINT_S
80 #include <unistd.h>
81 #endif
82 #include <libgen.h>
83 #include <stdio.h>
84 #include <errno.h>
85 #include <fcntl.h>
86 #include <dirent.h>
87 #include <grp.h>
88
89 #include "xlog.h"
90 #include "nsm.h"
91
92 #define RPCARGSLEN      (4 * (8 + 1))
93 #define LINELEN         (RPCARGSLEN + SM_PRIV_SIZE * 2 + 1)
94
95 #define NSM_KERNEL_STATE_FILE   "/proc/sys/fs/nfs/nsm_local_state"
96
97 static char nsm_base_dirname[PATH_MAX] = NSM_DEFAULT_STATEDIR;
98
99 #define NSM_MONITOR_DIR "sm"
100 #define NSM_NOTIFY_DIR  "sm.bak"
101 #define NSM_STATE_FILE  "state"
102
103
104 static _Bool
105 error_check(const int len, const size_t buflen)
106 {
107         return (len < 0) || ((size_t)len >= buflen);
108 }
109
110 static _Bool
111 exact_error_check(const ssize_t len, const size_t buflen)
112 {
113         return (len < 0) || ((size_t)len != buflen);
114 }
115
116 /*
117  * Returns a dynamically allocated, '\0'-terminated buffer
118  * containing an appropriate pathname, or NULL if an error
119  * occurs.  Caller must free the returned result with free(3).
120  */
121 __attribute__((__malloc__))
122 static char *
123 nsm_make_record_pathname(const char *directory, const char *hostname)
124 {
125         const char *c;
126         size_t size;
127         char *path;
128         int len;
129
130         /*
131          * Block hostnames that contain characters that have
132          * meaning to the file system (like '/'), or that can
133          * be confusing on visual inspection (like ' ').
134          */
135         for (c = hostname; *c != '\0'; c++)
136                 if (*c == '/' || isspace((int)*c) != 0) {
137                         xlog(D_GENERAL, "Hostname contains invalid characters");
138                         return NULL;
139                 }
140
141         size = strlen(nsm_base_dirname) + strlen(directory) + strlen(hostname) + 3;
142         if (size > PATH_MAX) {
143                 xlog(D_GENERAL, "Hostname results in pathname that is too long");
144                 return NULL;
145         }
146
147         path = malloc(size);
148         if (path == NULL) {
149                 xlog(D_GENERAL, "Failed to allocate memory for pathname");
150                 return NULL;
151         }
152
153         len = snprintf(path, size, "%s/%s/%s",
154                         nsm_base_dirname, directory, hostname);
155         if (error_check(len, size)) {
156                 xlog(D_GENERAL, "Pathname did not fit in specified buffer");
157                 free(path);
158                 return NULL;
159         }
160
161         return path;
162 }
163
164 /*
165  * Returns a dynamically allocated, '\0'-terminated buffer
166  * containing an appropriate pathname, or NULL if an error
167  * occurs.  Caller must free the returned result with free(3).
168  */
169 __attribute__((__malloc__))
170 static char *
171 nsm_make_pathname(const char *directory)
172 {
173         size_t size;
174         char *path;
175         int len;
176
177         size = strlen(nsm_base_dirname) + strlen(directory) + 2;
178         if (size > PATH_MAX)
179                 return NULL;
180
181         path = malloc(size);
182         if (path == NULL)
183                 return NULL;
184
185         len = snprintf(path, size, "%s/%s", nsm_base_dirname, directory);
186         if (error_check(len, size)) {
187                 free(path);
188                 return NULL;
189         }
190
191         return path;
192 }
193
194 /*
195  * Returns a dynamically allocated, '\0'-terminated buffer
196  * containing an appropriate pathname, or NULL if an error
197  * occurs.  Caller must free the returned result with free(3).
198  */
199 __attribute__((__malloc__))
200 static char *
201 nsm_make_temp_pathname(const char *pathname)
202 {
203         size_t size;
204         char *path;
205         int len;
206
207         size = strlen(pathname) + sizeof(".new") + 2;
208         if (size > PATH_MAX)
209                 return NULL;
210
211         path = malloc(size);
212         if (path == NULL)
213                 return NULL;
214
215         len = snprintf(path, size, "%s.new", pathname);
216         if (error_check(len, size)) {
217                 free(path);
218                 return NULL;
219         }
220
221         return path;
222 }
223
224 /*
225  * Use "mktemp, write, rename" to update the contents of a file atomically.
226  *
227  * Returns true if completely successful, or false if some error occurred.
228  */
229 static _Bool
230 nsm_atomic_write(const char *path, const void *buf, const size_t buflen)
231 {
232         _Bool result = false;
233         ssize_t len;
234         char *temp;
235         int fd;
236
237         temp = nsm_make_temp_pathname(path);
238         if (temp == NULL) {
239                 xlog(L_ERROR, "Failed to create new path for %s", path);
240                 goto out;
241         }
242
243         fd = open(temp, O_CREAT | O_TRUNC | O_SYNC | O_WRONLY, 0644);
244         if (fd == -1) {
245                 xlog(L_ERROR, "Failed to create %s: %m", temp);
246                 goto out;
247         }
248
249         len = write(fd, buf, buflen);
250         if (exact_error_check(len, buflen)) {
251                 xlog(L_ERROR, "Failed to write %s: %m", temp);
252                 (void)close(fd);
253                 (void)unlink(temp);
254                 goto out;
255         }
256
257         if (close(fd) == -1) {
258                 xlog(L_ERROR, "Failed to close %s: %m", temp);
259                 (void)unlink(temp);
260                 goto out;
261         }
262
263         if (rename(temp, path) == -1) {
264                 xlog(L_ERROR, "Failed to rename %s -> %s: %m",
265                                 temp, path);
266                 (void)unlink(temp);
267                 goto out;
268         }
269
270         /* Ostensibly, a sync(2) is not needed here because
271          * open(O_CREAT), write(O_SYNC), and rename(2) are
272          * already synchronous with persistent storage, for
273          * any file system we care about. */
274
275         result = true;
276
277 out:
278         free(temp);
279         return result;
280 }
281
282 /**
283  * nsm_setup_pathnames - set up pathname
284  * @progname: C string containing name of program, for error messages
285  * @parentdir: C string containing pathname to on-disk state, or NULL
286  *
287  * This runs before logging is set up, so error messages are directed
288  * to stderr.
289  *
290  * Returns true and sets up our pathnames, if @parentdir was valid
291  * and usable; otherwise false is returned.
292  */
293 _Bool
294 nsm_setup_pathnames(const char *progname, const char *parentdir)
295 {
296         static char buf[PATH_MAX];
297         struct stat st;
298         char *path;
299
300         /* First: test length of name and whether it exists */
301         if (lstat(parentdir, &st) == -1) {
302                 (void)fprintf(stderr, "%s: Failed to stat %s: %s",
303                                 progname, parentdir, strerror(errno));
304                 return false;
305         }
306
307         /* Ensure we have a clean directory pathname */
308         strncpy(buf, parentdir, sizeof(buf));
309         path = dirname(buf);
310         if (*path == '.') {
311                 (void)fprintf(stderr, "%s: Unusable directory %s",
312                                 progname, parentdir);
313                 return false;
314         }
315
316         xlog(D_CALL, "Using %s as the state directory", parentdir);
317         strncpy(nsm_base_dirname, parentdir, sizeof(nsm_base_dirname));
318         return true;
319 }
320
321 /**
322  * nsm_is_default_parentdir - check if parent directory is default
323  *
324  * Returns true if the active statd parent directory, set by
325  * nsm_change_pathname(), is the same as the built-in default
326  * parent directory; otherwise false is returned.
327  */
328 _Bool
329 nsm_is_default_parentdir(void)
330 {
331         return strcmp(nsm_base_dirname, NSM_DEFAULT_STATEDIR) == 0;
332 }
333
334 /*
335  * Clear all capabilities but CAP_NET_BIND_SERVICE.  This permits
336  * callers to acquire privileged source ports, but all other root
337  * capabilities are disallowed.
338  *
339  * Returns true if successful, or false if some error occurred.
340  */
341 static _Bool
342 nsm_clear_capabilities(void)
343 {
344 #ifdef HAVE_SYS_CAPABILITY_H
345         cap_t caps;
346
347         caps = cap_from_text("cap_net_bind_service=ep");
348         if (caps == NULL) {
349                 xlog(L_ERROR, "Failed to allocate capability: %m");
350                 return false;
351         }
352
353         if (cap_set_proc(caps) == -1) {
354                 xlog(L_ERROR, "Failed to set capability flags: %m");
355                 (void)cap_free(caps);
356                 return false;
357         }
358
359         (void)cap_free(caps);
360 #endif
361         return true;
362 }
363
364 /**
365  * nsm_drop_privileges - drop root privileges
366  * @pidfd: file descriptor of a pid file
367  *
368  * Returns true if successful, or false if some error occurred.
369  *
370  * Set our effective UID and GID to that of our on-disk database.
371  */
372 _Bool
373 nsm_drop_privileges(const int pidfd)
374 {
375         struct stat st;
376
377         (void)umask(S_IRWXO);
378
379         /*
380          * XXX: If we can't stat dirname, or if dirname is owned by
381          *      root, we should use "statduser" instead, which is set up
382          *      by configure.ac.  Nothing in nfs-utils seems to use
383          *      "statduser," though.
384          */
385         if (lstat(nsm_base_dirname, &st) == -1) {
386                 xlog(L_ERROR, "Failed to stat %s: %m", nsm_base_dirname);
387                 return false;
388         }
389
390         if (chdir(nsm_base_dirname) == -1) {
391                 xlog(L_ERROR, "Failed to change working directory to %s: %m",
392                                 nsm_base_dirname);
393                 return false;
394         }
395
396         if (st.st_uid == 0) {
397                 xlog_warn("Running as root.  "
398                         "chown %s to choose different user", nsm_base_dirname);
399                 return true;
400         }
401
402         /*
403          * If the pidfile happens to reside on NFS, dropping privileges
404          * will probably cause us to lose access, even though we are
405          * holding it open.  Chown it to prevent this.
406          */
407         if (pidfd >= 0)
408                 if (fchown(pidfd, st.st_uid, st.st_gid) == -1)
409                         xlog_warn("Failed to change owner of pidfile: %m");
410
411         /*
412          * Don't clear capabilities when dropping root.
413          */
414         if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
415                 xlog(L_ERROR, "prctl(PR_SET_KEEPCAPS) failed: %m");
416                 return false;
417         }
418
419         if (setgroups(0, NULL) == -1) {
420                 xlog(L_ERROR, "Failed to drop supplementary groups: %m");
421                 return false;
422         }
423
424         /*
425          * ORDER
426          *
427          * setgid(2) first, as setuid(2) may remove privileges needed
428          * to set the group id.
429          */
430         if (setgid(st.st_gid) == -1 || setuid(st.st_uid) == -1) {
431                 xlog(L_ERROR, "Failed to drop privileges: %m");
432                 return false;
433         }
434
435         xlog(D_CALL, "Effective UID, GID: %u, %u", st.st_uid, st.st_gid);
436
437         return nsm_clear_capabilities();
438 }
439
440 /**
441  * nsm_get_state - retrieve on-disk NSM state number
442  *
443  * Returns an odd NSM state number read from disk, or an initial
444  * state number.  Zero is returned if some error occurs.
445  */
446 int
447 nsm_get_state(_Bool update)
448 {
449         int fd, state = 0;
450         ssize_t result;
451         char *path = NULL;
452
453         path = nsm_make_pathname(NSM_STATE_FILE);
454         if (path == NULL) {
455                 xlog(L_ERROR, "Failed to allocate path for " NSM_STATE_FILE);
456                 goto out;
457         }
458
459         fd = open(path, O_RDONLY);
460         if (fd == -1) {
461                 if (errno != ENOENT) {
462                         xlog(L_ERROR, "Failed to open %s: %m", path);
463                         goto out;
464                 }
465
466                 xlog(L_NOTICE, "Initializing NSM state");
467                 state = 1;
468                 update = true;
469                 goto update;
470         }
471
472         result = read(fd, &state, sizeof(state));
473         if (exact_error_check(result, sizeof(state))) {
474                 xlog_warn("Failed to read %s: %m", path);
475
476                 xlog(L_NOTICE, "Initializing NSM state");
477                 state = 1;
478                 update = true;
479                 goto update;
480         }
481
482         if ((state & 1) == 0)
483                 state++;
484
485 update:
486         (void)close(fd);
487
488         if (update) {
489                 state += 2;
490                 if (!nsm_atomic_write(path, &state, sizeof(state)))
491                         state = 0;
492         }
493
494 out:
495         free(path);
496         return state;
497 }
498
499 /**
500  * nsm_update_kernel_state - attempt to post new NSM state to kernel
501  * @state: NSM state number
502  *
503  */
504 void
505 nsm_update_kernel_state(const int state)
506 {
507         ssize_t result;
508         char buf[20];
509         int fd, len;
510
511         fd = open(NSM_KERNEL_STATE_FILE, O_WRONLY);
512         if (fd == -1) {
513                 xlog(D_GENERAL, "Failed to open " NSM_KERNEL_STATE_FILE ": %m");
514                 return;
515         }
516
517         len = snprintf(buf, sizeof(buf), "%d", state);
518         if (error_check(len, sizeof(buf))) {
519                 xlog_warn("Failed to form NSM state number string");
520                 return;
521         }
522
523         result = write(fd, buf, strlen(buf));
524         if (exact_error_check(result, strlen(buf)))
525                 xlog_warn("Failed to write NSM state number: %m");
526
527         if (close(fd) == -1)
528                 xlog(L_ERROR, "Failed to close NSM state file "
529                                 NSM_KERNEL_STATE_FILE ": %m");
530 }
531
532 /**
533  * nsm_retire_monitored_hosts - back up all hosts from "sm/" to "sm.bak/"
534  *
535  * Returns the count of host records that were moved.
536  *
537  * Note that if any error occurs during this process, some monitor
538  * records may be left in the "sm" directory.
539  */
540 unsigned int
541 nsm_retire_monitored_hosts(void)
542 {
543         unsigned int count = 0;
544         struct dirent *de;
545         char *path;
546         DIR *dir;
547
548         path = nsm_make_pathname(NSM_MONITOR_DIR);
549         if (path == NULL) {
550                 xlog(L_ERROR, "Failed to allocate path for " NSM_MONITOR_DIR);
551                 return count;
552         }
553
554         dir = opendir(path);
555         free(path);
556         if (dir == NULL) {
557                 xlog_warn("Failed to open " NSM_MONITOR_DIR ": %m");
558                 return count;
559         }
560
561         while ((de = readdir(dir)) != NULL) {
562                 char *src, *dst;
563                 struct stat stb;
564
565                 if (de->d_name[0] == '.')
566                         continue;
567
568                 src = nsm_make_record_pathname(NSM_MONITOR_DIR, de->d_name);
569                 if (src == NULL) {
570                         xlog_warn("Bad monitor file name, skipping");
571                         continue;
572                 }
573
574                 /* NB: not all file systems fill in d_type correctly */
575                 if (lstat(src, &stb) == -1) {
576                         xlog_warn("Bad monitor file %s, skipping: %m",
577                                         de->d_name);
578                         free(src);
579                         continue;
580                 }
581                 if (!S_ISREG(stb.st_mode)) {
582                         xlog(D_GENERAL, "Skipping non-regular file %s",
583                                         de->d_name);
584                         free(src);
585                         continue;
586                 }
587
588                 dst = nsm_make_record_pathname(NSM_NOTIFY_DIR, de->d_name);
589                 if (dst == NULL) {
590                         free(src);
591                         xlog_warn("Bad notify file name, skipping");
592                         continue;
593                 }
594
595                 if (rename(src, dst) == -1)
596                         xlog_warn("Failed to rename %s -> %s: %m",
597                                 src, dst);
598                 else {
599                         xlog(D_GENERAL, "Retired record for mon_name %s",
600                                         de->d_name);
601                         count++;
602                 }
603
604                 free(dst);
605                 free(src);
606         }
607
608         (void)closedir(dir);
609         return count;
610 }
611
612 /*
613  * nsm_priv_to_hex - convert a NSM private cookie to a hex string.
614  *
615  * @priv: buffer holding the binary NSM private cookie
616  * @buf: output buffer for NULL terminated hex string
617  * @buflen: size of output buffer
618  *
619  * Returns the length of the resulting string or 0 on error
620  */
621 size_t
622 nsm_priv_to_hex(const char *priv, char *buf, const size_t buflen)
623 {
624         int i, len;
625         size_t remaining = buflen;
626
627         for (i = 0; i < SM_PRIV_SIZE; i++) {
628                 len = snprintf(buf, remaining, "%02x",
629                                 (unsigned int)(0xff & priv[i]));
630                 if (error_check(len, remaining))
631                         return 0;
632                 buf += len;
633                 remaining -= (size_t)len;
634         }
635
636         return buflen - remaining;
637 }
638
639 /*
640  * Returns the length in bytes of the created record.
641  */
642 __attribute__((__noinline__))
643 static size_t
644 nsm_create_monitor_record(char *buf, const size_t buflen,
645                 const struct sockaddr *sap, const struct mon *m)
646 {
647         const struct sockaddr_in *sin = (const struct sockaddr_in *)sap;
648         size_t hexlen, remaining = buflen;
649         int len;
650
651         len = snprintf(buf, remaining, "%08x %08x %08x %08x ",
652                         (unsigned int)sin->sin_addr.s_addr,
653                         (unsigned int)m->mon_id.my_id.my_prog,
654                         (unsigned int)m->mon_id.my_id.my_vers,
655                         (unsigned int)m->mon_id.my_id.my_proc);
656         if (error_check(len, remaining))
657                 return 0;
658         buf += len;
659         remaining -= (size_t)len;
660
661         hexlen = nsm_priv_to_hex(m->priv, buf, remaining);
662         if (hexlen == 0)
663                 return 0;
664         buf += hexlen;
665         remaining -= hexlen;
666
667         len = snprintf(buf, remaining, " %s %s\n",
668                         m->mon_id.mon_name, m->mon_id.my_id.my_name);
669         if (error_check(len, remaining))
670                 return 0;
671         remaining -= (size_t)len;
672
673         return buflen - remaining;
674 }
675
676 static _Bool
677 nsm_append_monitored_host(const char *path, const char *line)
678 {
679         _Bool result = false;
680         char *buf = NULL;
681         struct stat stb;
682         size_t buflen;
683         ssize_t len;
684         int fd;
685
686         if (stat(path, &stb) == -1) {
687                 xlog(L_ERROR, "Failed to insert: "
688                         "could not stat original file %s: %m", path);
689                 goto out;
690         }
691         buflen = (size_t)stb.st_size + strlen(line);
692
693         buf = malloc(buflen + 1);
694         if (buf == NULL) {
695                 xlog(L_ERROR, "Failed to insert: no memory");
696                 goto out;
697         }
698         memset(buf, 0, buflen + 1);
699
700         fd = open(path, O_RDONLY);
701         if (fd == -1) {
702                 xlog(L_ERROR, "Failed to insert: "
703                         "could not open original file %s: %m", path);
704                 goto out;
705         }
706
707         len = read(fd, buf, (size_t)stb.st_size);
708         if (exact_error_check(len, (size_t)stb.st_size)) {
709                 xlog(L_ERROR, "Failed to insert: "
710                         "could not read original file %s: %m", path);
711                 (void)close(fd);
712                 goto out;
713         }
714         (void)close(fd);
715
716         strcat(buf, line);
717
718         if (nsm_atomic_write(path, buf, buflen))
719                 result = true;
720
721 out:
722         free(buf);
723         return result;
724 }
725
726 /**
727  * nsm_insert_monitored_host - write callback data for one host to disk
728  * @hostname: C string containing a hostname
729  * @sap: sockaddr containing NLM callback address
730  * @mon: SM_MON arguments to save
731  *
732  * Returns true if successful, otherwise false if some error occurs.
733  */
734 _Bool
735 nsm_insert_monitored_host(const char *hostname, const struct sockaddr *sap,
736                 const struct mon *m)
737 {
738         static char buf[LINELEN + 1 + SM_MAXSTRLEN + 2];
739         char *path;
740         _Bool result = false;
741         ssize_t len;
742         size_t size;
743         int fd;
744
745         path = nsm_make_record_pathname(NSM_MONITOR_DIR, hostname);
746         if (path == NULL) {
747                 xlog(L_ERROR, "Failed to insert: bad monitor hostname '%s'",
748                                 hostname);
749                 return false;
750         }
751
752         size = nsm_create_monitor_record(buf, sizeof(buf), sap, m);
753         if (size == 0) {
754                 xlog(L_ERROR, "Failed to insert: record too long");
755                 goto out;
756         }
757
758         /*
759          * If exclusive create fails, we're adding a new line to an
760          * existing file.
761          */
762         fd = open(path, O_WRONLY | O_CREAT | O_EXCL | O_SYNC, S_IRUSR | S_IWUSR);
763         if (fd == -1) {
764                 if (errno != EEXIST) {
765                         xlog(L_ERROR, "Failed to insert: creating %s: %m", path);
766                         goto out;
767                 }
768
769                 result = nsm_append_monitored_host(path, buf);
770                 goto out;
771         }
772         result = true;
773
774         len = write(fd, buf, size);
775         if (exact_error_check(len, size)) {
776                 xlog_warn("Failed to insert: writing %s: %m", path);
777                 (void)unlink(path);
778                 result = false;
779         }
780
781         if (close(fd) == -1) {
782                 xlog(L_ERROR, "Failed to insert: closing %s: %m", path);
783                 (void)unlink(path);
784                 result = false;
785         }
786
787 out:
788         free(path);
789         return result;
790 }
791
792 __attribute__((__noinline__))
793 static _Bool
794 nsm_parse_line(char *line, struct sockaddr_in *sin, struct mon *m)
795 {
796         unsigned int i, tmp;
797         int count;
798         char *c;
799
800         c = strchr(line, '\n');
801         if (c != NULL)
802                 *c = '\0';
803
804         count = sscanf(line, "%8x %8x %8x %8x ",
805                         (unsigned int *)&sin->sin_addr.s_addr,
806                         (unsigned int *)&m->mon_id.my_id.my_prog,
807                         (unsigned int *)&m->mon_id.my_id.my_vers,
808                         (unsigned int *)&m->mon_id.my_id.my_proc);
809         if (count != 4)
810                 return false;
811
812         c = line + RPCARGSLEN;
813         for (i = 0; i < SM_PRIV_SIZE; i++) {
814                 if (sscanf(c, "%2x", &tmp) != 1)
815                         return false;
816                 m->priv[i] = (char)tmp;
817                 c += 2;
818         }
819
820         c++;
821         m->mon_id.mon_name = c;
822         while (*c != '\0' && *c != ' ')
823                 c++;
824         if (*c != '\0')
825                 *c++ = '\0';
826         while (*c == ' ')
827                 c++;
828         m->mon_id.my_id.my_name = c;
829
830         return true;
831 }
832
833 /*
834  * Stuff a 'struct mon' with callback data, and call @func.
835  *
836  * Returns the count of in-core records created.
837  */
838 static unsigned int
839 nsm_read_line(const char *hostname, const time_t timestamp, char *line,
840                 nsm_populate_t func)
841 {
842         struct sockaddr_in sin = {
843                 .sin_family             = AF_INET,
844         };
845         struct mon m;
846
847         if (!nsm_parse_line(line, &sin, &m))
848                 return 0;
849
850         return func(hostname, (struct sockaddr *)(char *)&sin, &m, timestamp);
851 }
852
853 /*
854  * Given a filename, reads data from a file under "directory"
855  * and invokes @func so caller can populate their in-core
856  * database with this data.
857  */
858 static unsigned int
859 nsm_load_host(const char *directory, const char *filename, nsm_populate_t func)
860 {
861         char buf[LINELEN + 1 + SM_MAXSTRLEN + 2];
862         unsigned int result = 0;
863         struct stat stb;
864         char *path;
865         FILE *f;
866
867         path = nsm_make_record_pathname(directory, filename);
868         if (path == NULL)
869                 goto out_err;
870
871         if (lstat(path, &stb) == -1) {
872                 xlog(L_ERROR, "Failed to stat %s: %m", path);
873                 goto out_freepath;
874         }
875         if (!S_ISREG(stb.st_mode)) {
876                 xlog(D_GENERAL, "Skipping non-regular file %s",
877                                 path);
878                 goto out_freepath;
879         }
880
881         f = fopen(path, "r");
882         if (f == NULL) {
883                 xlog(L_ERROR, "Failed to open %s: %m", path);
884                 goto out_freepath;
885         }
886
887         while (fgets(buf, (int)sizeof(buf), f) != NULL) {
888                 buf[sizeof(buf) - 1] = '\0';
889                 result += nsm_read_line(filename, stb.st_mtime, buf, func);
890         }
891         if (result == 0)
892                 xlog(L_ERROR, "Failed to read monitor data from %s", path);
893
894         (void)fclose(f);
895
896 out_freepath:
897         free(path);
898 out_err:
899         return result;
900 }
901
902 static unsigned int
903 nsm_load_dir(const char *directory, nsm_populate_t func)
904 {
905         unsigned int count = 0;
906         struct dirent *de;
907         char *path;
908         DIR *dir;
909
910         path = nsm_make_pathname(directory);
911         if (path == NULL) {
912                 xlog(L_ERROR, "Failed to allocate path for directory %s",
913                                 directory);
914                 return 0;
915         }
916
917         dir = opendir(path);
918         free(path);
919         if (dir == NULL) {
920                 xlog(L_ERROR, "Failed to open directory %s: %m",
921                                 directory);
922                 return 0;
923         }
924
925         while ((de = readdir(dir)) != NULL) {
926                 if (de->d_name[0] == '.')
927                         continue;
928
929                 count += nsm_load_host(directory, de->d_name, func);
930         }
931
932         (void)closedir(dir);
933         return count;
934 }
935
936 /**
937  * nsm_load_monitor_list - load list of hosts to monitor
938  * @func: callback function to create entry for one host
939  *
940  * Returns the count of hosts that were found in the directory.
941  */
942 unsigned int
943 nsm_load_monitor_list(nsm_populate_t func)
944 {
945         return nsm_load_dir(NSM_MONITOR_DIR, func);
946 }
947
948 /**
949  * nsm_load_notify_list - load list of hosts to notify
950  * @func: callback function to create entry for one host
951  *
952  * Returns the count of hosts that were found in the directory.
953  */
954 unsigned int
955 nsm_load_notify_list(nsm_populate_t func)
956 {
957         return nsm_load_dir(NSM_NOTIFY_DIR, func);
958 }
959
960 static void
961 nsm_delete_host(const char *directory, const char *hostname,
962                 const char *mon_name, const char *my_name)
963 {
964         char line[LINELEN + 1 + SM_MAXSTRLEN + 2];
965         char *outbuf = NULL;
966         struct stat stb;
967         char *path, *next;
968         size_t remaining;
969         FILE *f;
970
971         path = nsm_make_record_pathname(directory, hostname);
972         if (path == NULL) {
973                 xlog(L_ERROR, "Bad filename, not deleting");
974                 return;
975         }
976
977         if (stat(path, &stb) == -1) {
978                 xlog(L_ERROR, "Failed to delete: "
979                         "could not stat original file %s: %m", path);
980                 goto out;
981         }
982         remaining = (size_t)stb.st_size + 1;
983
984         outbuf = malloc(remaining);
985         if (outbuf == NULL) {
986                 xlog(L_ERROR, "Failed to delete: no memory");
987                 goto out;
988         }
989
990         f = fopen(path, "r");
991         if (f == NULL) {
992                 xlog(L_ERROR, "Failed to delete: "
993                         "could not open original file %s: %m", path);
994                 goto out;
995         }
996
997         /*
998          * Walk the records in the file, and copy the non-matching
999          * ones to our output buffer.
1000          */
1001         next = outbuf;
1002         while (fgets(line, (int)sizeof(line), f) != NULL) {
1003                 struct sockaddr_in sin;
1004                 struct mon m;
1005                 size_t len;
1006
1007                 if (!nsm_parse_line(line, &sin, &m)) {
1008                         xlog(L_ERROR, "Failed to delete: "
1009                                 "could not parse original file %s", path);
1010                         (void)fclose(f);
1011                         goto out;
1012                 }
1013
1014                 if (strcmp(mon_name, m.mon_id.mon_name) == 0 &&
1015                          strcmp(my_name, m.mon_id.my_id.my_name) == 0)
1016                         continue;
1017
1018                 /* nsm_parse_line destroys the contents of line[], so
1019                  * reconstruct the copy in our output buffer. */
1020                 len = nsm_create_monitor_record(next, remaining,
1021                                         (struct sockaddr *)(char *)&sin, &m);
1022                 if (len == 0) {
1023                         xlog(L_ERROR, "Failed to delete: "
1024                                 "could not construct output record");
1025                         (void)fclose(f);
1026                         goto out;
1027                 }
1028                 next += len;
1029                 remaining -= len;
1030         }
1031
1032         (void)fclose(f);
1033
1034         /*
1035          * If nothing was copied when we're done, then unlink the file.
1036          * Otherwise, atomically update the contents of the file.
1037          */
1038         if (next != outbuf) {
1039                 if (!nsm_atomic_write(path, outbuf, strlen(outbuf)))
1040                         xlog(L_ERROR, "Failed to delete: "
1041                                 "could not write new file %s: %m", path);
1042         } else {
1043                 if (unlink(path) == -1)
1044                         xlog(L_ERROR, "Failed to delete: "
1045                                 "could not unlink file %s: %m", path);
1046         }
1047
1048 out:
1049         free(outbuf);
1050         free(path);
1051 }
1052
1053 /**
1054  * nsm_delete_monitored_host - delete on-disk record for monitored host
1055  * @hostname: '\0'-terminated C string containing hostname of record to delete
1056  * @mon_name: '\0'-terminated C string containing monname of record to delete
1057  * @my_name: '\0'-terminated C string containing myname of record to delete
1058  *
1059  */
1060 void
1061 nsm_delete_monitored_host(const char *hostname, const char *mon_name,
1062                 const char *my_name)
1063 {
1064         nsm_delete_host(NSM_MONITOR_DIR, hostname, mon_name, my_name);
1065 }
1066
1067 /**
1068  * nsm_delete_notified_host - delete on-disk host record after notification
1069  * @hostname: '\0'-terminated C string containing hostname of record to delete
1070  * @mon_name: '\0'-terminated C string containing monname of record to delete
1071  * @my_name: '\0'-terminated C string containing myname of record to delete
1072  *
1073  */
1074 void
1075 nsm_delete_notified_host(const char *hostname, const char *mon_name,
1076                 const char *my_name)
1077 {
1078         nsm_delete_host(NSM_NOTIFY_DIR, hostname, mon_name, my_name);
1079 }