user.c revision 1.18
1/*	$OpenBSD: user.c,v 1.18 2015/11/15 23:24:24 millert Exp $	*/
2
3/* Copyright 1988,1990,1993,1994 by Paul Vixie
4 * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
5 * Copyright (c) 1997,2000 by Internet Software Consortium, Inc.
6 *
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
10 *
11 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
17 * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 */
19
20#include <sys/types.h>
21
22#include <bitstring.h>		/* for structs.h */
23#include <ctype.h>
24#include <errno.h>
25#include <pwd.h>
26#include <stdio.h>
27#include <stdlib.h>
28#include <string.h>
29#include <syslog.h>
30#include <time.h>		/* for structs.h */
31
32#include "macros.h"
33#include "structs.h"
34#include "funcs.h"
35
36void
37free_user(user *u)
38{
39	entry *e;
40
41	while ((e = SLIST_FIRST(&u->crontab))) {
42		SLIST_REMOVE_HEAD(&u->crontab, entries);
43		free_entry(e);
44	}
45	free(u->name);
46	free(u);
47}
48
49user *
50load_user(int crontab_fd, struct passwd	*pw, const char *name)
51{
52	char envstr[MAX_ENVSTR];
53	FILE *file;
54	user *u;
55	entry *e;
56	int status, save_errno;
57	char **envp, **tenvp;
58
59	if (!(file = fdopen(crontab_fd, "r"))) {
60		syslog(LOG_ERR, "(%s) FDOPEN (%m)", pw->pw_name);
61		return (NULL);
62	}
63
64	/* file is open.  build user entry, then read the crontab file.
65	 */
66	if ((u = malloc(sizeof(user))) == NULL)
67		return (NULL);
68	if ((u->name = strdup(name)) == NULL) {
69		save_errno = errno;
70		free(u);
71		errno = save_errno;
72		return (NULL);
73	}
74	SLIST_INIT(&u->crontab);
75
76	/* init environment.  this will be copied/augmented for each entry.
77	 */
78	if ((envp = env_init()) == NULL) {
79		save_errno = errno;
80		free(u->name);
81		free(u);
82		errno = save_errno;
83		return (NULL);
84	}
85
86	/* load the crontab
87	 */
88	while ((status = load_env(envstr, file)) >= 0) {
89		switch (status) {
90		case FALSE:
91			/* Not an env variable, parse as crontab entry. */
92			e = load_entry(file, NULL, pw, envp);
93			if (e)
94				SLIST_INSERT_HEAD(&u->crontab, e, entries);
95			break;
96		case TRUE:
97			if ((tenvp = env_set(envp, envstr)) == NULL) {
98				save_errno = errno;
99				free_user(u);
100				u = NULL;
101				errno = save_errno;
102				goto done;
103			}
104			envp = tenvp;
105			break;
106		}
107	}
108
109 done:
110	env_free(envp);
111	fclose(file);
112	return (u);
113}
114