1/*	$OpenBSD: ypldap.c,v 1.16 2015/11/02 10:06:06 jmatthew Exp $ */
2/*	$FreeBSD */
3
4/*
5 * Copyright (c) 2008 Pierre-Yves Ritschard <pyr@openbsd.org>
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 THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR 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 OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 */
19
20#include <sys/types.h>
21#include <sys/param.h>
22#include <sys/queue.h>
23#include <sys/socket.h>
24#include <sys/signal.h>
25#include <sys/tree.h>
26#include <sys/wait.h>
27
28#include <netinet/in.h>
29#include <arpa/inet.h>
30
31#include <err.h>
32#include <errno.h>
33#include <event.h>
34#include <unistd.h>
35#include <pwd.h>
36#include <stdio.h>
37#include <stdlib.h>
38#include <string.h>
39#include <limits.h>
40
41#include "ypldap.h"
42
43enum ypldap_process_type		ypldap_process;
44
45__dead2 void	 usage(void);
46int		 check_child(pid_t, const char *);
47void		 main_sig_handler(int, short, void *);
48void		 main_shutdown(void);
49void		 main_dispatch_client(int, short, void *);
50void		 main_configure_client(struct env *);
51void		 main_init_timer(int, short, void *);
52void		 main_start_update(struct env *);
53void		 main_trash_update(struct env *);
54void		 main_end_update(struct env *);
55int		 main_create_user_groups(struct env *);
56void		 purge_config(struct env *);
57void		 reconfigure(struct env *);
58
59int		 pipe_main2client[2];
60
61pid_t		 client_pid = 0;
62char		*conffile = YPLDAP_CONF_FILE;
63int		 opts = 0;
64
65void
66usage(void)
67{
68	extern const char	*__progname;
69
70	fprintf(stderr, "usage: %s [-dnv] [-D macro=value] [-f file]\n",
71	    __progname);
72	exit(1);
73}
74
75int
76check_child(pid_t pid, const char *pname)
77{
78	int	status;
79
80	if (waitpid(pid, &status, WNOHANG) > 0) {
81		if (WIFEXITED(status)) {
82			log_warnx("check_child: lost child %s exited", pname);
83			return (1);
84		}
85		if (WIFSIGNALED(status)) {
86			log_warnx("check_child: lost child %s terminated; "
87			    "signal %d", pname, WTERMSIG(status));
88			return (1);
89		}
90	}
91	return (0);
92}
93
94/* ARGUSED */
95void
96main_sig_handler(int sig, short event, void *p)
97{
98	int		 die = 0;
99
100	switch (sig) {
101	case SIGTERM:
102	case SIGINT:
103		die = 1;
104		/* FALLTHROUGH */
105	case SIGCHLD:
106		if (check_child(client_pid, "ldap client")) {
107			client_pid = 0;
108			die = 1;
109		}
110		if (die)
111			main_shutdown();
112		break;
113	case SIGHUP:
114		/* reconfigure */
115		break;
116	default:
117		fatalx("unexpected signal");
118	}
119}
120
121void
122main_shutdown(void)
123{
124	_exit(0);
125}
126
127void
128main_start_update(struct env *env)
129{
130	env->update_trashed = 0;
131
132	log_debug("starting directory update");
133	env->sc_user_line_len = 0;
134	env->sc_group_line_len = 0;
135	if ((env->sc_user_names_t = calloc(1,
136	    sizeof(*env->sc_user_names_t))) == NULL ||
137	    (env->sc_group_names_t = calloc(1,
138	    sizeof(*env->sc_group_names_t))) == NULL)
139		fatal(NULL);
140	RB_INIT(env->sc_user_names_t);
141	RB_INIT(env->sc_group_names_t);
142}
143
144/*
145 * XXX: Currently this function should only be called when updating is
146 * finished. A notification should be send to ldapclient that it should stop
147 * sending new pwd/grp entries before it can be called from different places.
148 */
149void
150main_trash_update(struct env *env)
151{
152	struct userent	*ue;
153	struct groupent	*ge;
154
155	env->update_trashed = 1;
156
157	while ((ue = RB_ROOT(env->sc_user_names_t)) != NULL) {
158		RB_REMOVE(user_name_tree,
159		    env->sc_user_names_t, ue);
160		free(ue->ue_line);
161		free(ue->ue_netid_line);
162		free(ue);
163	}
164	free(env->sc_user_names_t);
165	env->sc_user_names_t = NULL;
166	while ((ge = RB_ROOT(env->sc_group_names_t))
167	    != NULL) {
168		RB_REMOVE(group_name_tree,
169		    env->sc_group_names_t, ge);
170		free(ge->ge_line);
171		free(ge);
172	}
173	free(env->sc_group_names_t);
174	env->sc_group_names_t = NULL;
175}
176
177int
178main_create_user_groups(struct env *env)
179{
180	struct userent		*ue;
181	struct userent		 ukey;
182	struct groupent		*ge;
183	gid_t			 pw_gid;
184	char			*bp, *cp;
185	char			*p;
186	const char		*errstr = NULL;
187	size_t			 len;
188
189	RB_FOREACH(ue, user_name_tree, env->sc_user_names_t) {
190		bp = cp = ue->ue_line;
191
192		/* name */
193		bp += strlen(bp) + 1;
194
195		/* password */
196		bp += strcspn(bp, ":") + 1;
197
198		/* uid */
199		bp += strcspn(bp, ":") + 1;
200
201		/* gid */
202		bp[strcspn(bp, ":")] = '\0';
203
204		pw_gid = (gid_t)strtonum(bp, 0, GID_MAX, &errstr);
205		if (errstr) {
206			log_warnx("main: failed to parse gid for uid: %d\n", ue->ue_uid);
207			return (-1);
208		}
209
210		/* bring gid column back to its proper state */
211		bp[strlen(bp)] = ':';
212
213		if ((ue->ue_netid_line = calloc(1, LINE_WIDTH)) == NULL) {
214			return (-1);
215		}
216
217		if (snprintf(ue->ue_netid_line, LINE_WIDTH-1, "%d:%d", ue->ue_uid, pw_gid) >= LINE_WIDTH) {
218
219			return (-1);
220		}
221
222		ue->ue_gid = pw_gid;
223	}
224
225	RB_FOREACH(ge, group_name_tree, env->sc_group_names_t) {
226		bp = cp = ge->ge_line;
227
228		/* name */
229		bp += strlen(bp) + 1;
230
231		/* password */
232		bp += strcspn(bp, ":") + 1;
233
234		/* gid */
235		bp += strcspn(bp, ":") + 1;
236
237		cp = bp;
238		if (*bp == '\0')
239			continue;
240		bp = cp;
241		for (;;) {
242			if (!(cp = strsep(&bp, ",")))
243				break;
244			ukey.ue_line = cp;
245			if ((ue = RB_FIND(user_name_tree, env->sc_user_names_t,
246			    &ukey)) == NULL) {
247				/* User not found */
248				log_warnx("main: unknown user %s in group %s\n",
249				   ukey.ue_line, ge->ge_line);
250				if (bp != NULL)
251					*(bp-1) = ',';
252				continue;
253			}
254			if (bp != NULL)
255				*(bp-1) = ',';
256
257			/* Make sure the new group doesn't equal to the main gid */
258			if (ge->ge_gid == ue->ue_gid)
259				continue;
260
261			len = strlen(ue->ue_netid_line);
262			p = ue->ue_netid_line + len;
263
264			if ((snprintf(p, LINE_WIDTH-len-1, ",%d",
265				ge->ge_gid)) >= (int)(LINE_WIDTH-len)) {
266				return (-1);
267			}
268		}
269	}
270
271	return (0);
272}
273
274void
275main_end_update(struct env *env)
276{
277	struct userent		*ue;
278	struct groupent		*ge;
279
280	if (env->update_trashed)
281		return;
282
283	log_debug("updates are over, cleaning up trees now");
284
285	if (main_create_user_groups(env) == -1) {
286		main_trash_update(env);
287		return;
288	}
289
290	if (env->sc_user_names == NULL) {
291		env->sc_user_names = env->sc_user_names_t;
292		env->sc_user_lines = NULL;
293		env->sc_user_names_t = NULL;
294
295		env->sc_group_names = env->sc_group_names_t;
296		env->sc_group_lines = NULL;
297		env->sc_group_names_t = NULL;
298
299		flatten_entries(env);
300		goto make_uids;
301	}
302
303	/*
304	 * clean previous tree.
305	 */
306	while ((ue = RB_ROOT(env->sc_user_names)) != NULL) {
307		RB_REMOVE(user_name_tree, env->sc_user_names,
308		    ue);
309		free(ue->ue_netid_line);
310		free(ue);
311	}
312	free(env->sc_user_names);
313	free(env->sc_user_lines);
314
315	env->sc_user_names = env->sc_user_names_t;
316	env->sc_user_lines = NULL;
317	env->sc_user_names_t = NULL;
318
319	while ((ge = RB_ROOT(env->sc_group_names)) != NULL) {
320		RB_REMOVE(group_name_tree,
321		    env->sc_group_names, ge);
322		free(ge);
323	}
324	free(env->sc_group_names);
325	free(env->sc_group_lines);
326
327	env->sc_group_names = env->sc_group_names_t;
328	env->sc_group_lines = NULL;
329	env->sc_group_names_t = NULL;
330
331
332	flatten_entries(env);
333
334	/*
335	 * trees are flat now. build up uid, gid and netid trees.
336	 */
337
338make_uids:
339	RB_INIT(&env->sc_user_uids);
340	RB_INIT(&env->sc_group_gids);
341	RB_FOREACH(ue, user_name_tree, env->sc_user_names)
342		RB_INSERT(user_uid_tree,
343		    &env->sc_user_uids, ue);
344	RB_FOREACH(ge, group_name_tree, env->sc_group_names)
345		RB_INSERT(group_gid_tree,
346		    &env->sc_group_gids, ge);
347
348}
349
350void
351main_dispatch_client(int fd, short events, void *p)
352{
353	int		 n;
354	int		 shut = 0;
355	struct env	*env = p;
356	struct imsgev	*iev = env->sc_iev;
357	struct imsgbuf	*ibuf = &iev->ibuf;
358	struct idm_req	 ir;
359	struct imsg	 imsg;
360
361	if ((events & (EV_READ | EV_WRITE)) == 0)
362		fatalx("unknown event");
363
364	if (events & EV_READ) {
365		if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
366			fatal("imsg_read error");
367		if (n == 0)
368			shut = 1;
369	}
370	if (events & EV_WRITE) {
371		if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
372			fatal("msgbuf_write");
373		if (n == 0)
374			shut = 1;
375		goto done;
376	}
377
378	for (;;) {
379		if ((n = imsg_get(ibuf, &imsg)) == -1)
380			fatal("main_dispatch_client: imsg_get error");
381		if (n == 0)
382			break;
383
384		switch (imsg.hdr.type) {
385		case IMSG_START_UPDATE:
386			main_start_update(env);
387			break;
388		case IMSG_PW_ENTRY: {
389			struct userent	*ue;
390			size_t		 len;
391
392			if (env->update_trashed)
393				break;
394
395			(void)memcpy(&ir, imsg.data, sizeof(ir));
396			if ((ue = calloc(1, sizeof(*ue))) == NULL ||
397			    (ue->ue_line = strdup(ir.ir_line)) == NULL) {
398				/*
399				 * should cancel tree update instead.
400				 */
401				fatal("out of memory");
402			}
403			ue->ue_uid = ir.ir_key.ik_uid;
404			len = strlen(ue->ue_line) + 1;
405			ue->ue_line[strcspn(ue->ue_line, ":")] = '\0';
406			if (RB_INSERT(user_name_tree, env->sc_user_names_t,
407			    ue) != NULL) { /* dup */
408				free(ue->ue_line);
409				free(ue);
410			} else
411				env->sc_user_line_len += len;
412			break;
413		}
414		case IMSG_GRP_ENTRY: {
415			struct groupent	*ge;
416			size_t		 len;
417
418			if (env->update_trashed)
419				break;
420
421			(void)memcpy(&ir, imsg.data, sizeof(ir));
422			if ((ge = calloc(1, sizeof(*ge))) == NULL ||
423			    (ge->ge_line = strdup(ir.ir_line)) == NULL) {
424				/*
425				 * should cancel tree update instead.
426				 */
427				fatal("out of memory");
428			}
429			ge->ge_gid = ir.ir_key.ik_gid;
430			len = strlen(ge->ge_line) + 1;
431			ge->ge_line[strcspn(ge->ge_line, ":")] = '\0';
432			if (RB_INSERT(group_name_tree, env->sc_group_names_t,
433			    ge) != NULL) { /* dup */
434				free(ge->ge_line);
435				free(ge);
436			} else
437				env->sc_group_line_len += len;
438			break;
439		}
440		case IMSG_TRASH_UPDATE:
441			main_trash_update(env);
442			break;
443		case IMSG_END_UPDATE: {
444			main_end_update(env);
445			break;
446		}
447		default:
448			log_debug("main_dispatch_client: unexpected imsg %d",
449			   imsg.hdr.type);
450			break;
451		}
452		imsg_free(&imsg);
453	}
454
455done:
456	if (!shut)
457		imsg_event_add(iev);
458	else {
459		log_debug("king bula sez: ran into dead pipe");
460		event_del(&iev->ev);
461		event_loopexit(NULL);
462	}
463}
464
465void
466main_configure_client(struct env *env)
467{
468	struct idm	*idm;
469	struct imsgev	*iev = env->sc_iev;
470
471	imsg_compose_event(iev, IMSG_CONF_START, 0, 0, -1, env, sizeof(*env));
472	TAILQ_FOREACH(idm, &env->sc_idms, idm_entry) {
473		imsg_compose_event(iev, IMSG_CONF_IDM, 0, 0, -1,
474		    idm, sizeof(*idm));
475	}
476	imsg_compose_event(iev, IMSG_CONF_END, 0, 0, -1, NULL, 0);
477}
478
479void
480main_init_timer(int fd, short event, void *p)
481{
482	struct env	*env = p;
483
484	main_configure_client(env);
485}
486
487void
488purge_config(struct env *env)
489{
490	struct idm	*idm;
491
492	while ((idm = TAILQ_FIRST(&env->sc_idms)) != NULL) {
493		TAILQ_REMOVE(&env->sc_idms, idm, idm_entry);
494		free(idm);
495	}
496}
497
498int
499main(int argc, char *argv[])
500{
501	int		 c;
502	int		 debug;
503	struct passwd	*pw;
504	struct env	 env;
505	struct event	 ev_sigint;
506	struct event	 ev_sigterm;
507	struct event	 ev_sigchld;
508	struct event	 ev_sighup;
509	struct event	 ev_timer;
510	struct timeval	 tv;
511
512	debug = 0;
513	ypldap_process = PROC_MAIN;
514
515	log_init(1);
516
517	while ((c = getopt(argc, argv, "dD:nf:v")) != -1) {
518		switch (c) {
519		case 'd':
520			debug = 2;
521			break;
522		case 'D':
523			if (cmdline_symset(optarg) < 0)
524				log_warnx("could not parse macro definition %s",
525				    optarg);
526			break;
527		case 'n':
528			debug = 2;
529			opts |= YPLDAP_OPT_NOACTION;
530			break;
531		case 'f':
532			conffile = optarg;
533			break;
534		case 'v':
535			opts |= YPLDAP_OPT_VERBOSE;
536			break;
537		default:
538			usage();
539		}
540	}
541
542	argc -= optind;
543	argv += optind;
544
545	if (argc)
546		usage();
547
548	RB_INIT(&env.sc_user_uids);
549	RB_INIT(&env.sc_group_gids);
550
551	if (parse_config(&env, conffile, opts))
552		exit(1);
553	if (opts & YPLDAP_OPT_NOACTION) {
554		fprintf(stderr, "configuration OK\n");
555		exit(0);
556	}
557
558	if (geteuid())
559		errx(1, "need root privileges");
560
561	log_init(debug);
562
563	if (!debug) {
564		if (daemon(1, 0) == -1)
565			err(1, "failed to daemonize");
566	}
567
568	log_info("startup%s", (debug > 1)?" [debug mode]":"");
569
570	if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, PF_UNSPEC,
571	    pipe_main2client) == -1)
572		fatal("socketpair");
573
574	client_pid = ldapclient(pipe_main2client);
575
576	setproctitle("parent");
577	event_init();
578
579	signal_set(&ev_sigint, SIGINT, main_sig_handler, &env);
580	signal_set(&ev_sigterm, SIGTERM, main_sig_handler, &env);
581	signal_set(&ev_sighup, SIGHUP, main_sig_handler, &env);
582	signal_set(&ev_sigchld, SIGCHLD, main_sig_handler, &env);
583	signal_add(&ev_sigint, NULL);
584	signal_add(&ev_sigterm, NULL);
585	signal_add(&ev_sighup, NULL);
586	signal_add(&ev_sigchld, NULL);
587
588	close(pipe_main2client[1]);
589	if ((env.sc_iev = calloc(1, sizeof(*env.sc_iev))) == NULL)
590		fatal(NULL);
591	imsg_init(&env.sc_iev->ibuf, pipe_main2client[0]);
592	env.sc_iev->handler = main_dispatch_client;
593
594	env.sc_iev->events = EV_READ;
595	env.sc_iev->data = &env;
596	event_set(&env.sc_iev->ev, env.sc_iev->ibuf.fd, env.sc_iev->events,
597	     env.sc_iev->handler, &env);
598	event_add(&env.sc_iev->ev, NULL);
599
600	yp_init(&env);
601
602	if ((pw = getpwnam(YPLDAP_USER)) == NULL)
603		fatal("getpwnam");
604
605#ifndef DEBUG
606	if (setgroups(1, &pw->pw_gid) ||
607	    setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
608	    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
609		fatal("cannot drop privileges");
610#else
611#warning disabling privilege revocation in debug mode
612#endif
613
614	memset(&tv, 0, sizeof(tv));
615	evtimer_set(&ev_timer, main_init_timer, &env);
616	evtimer_add(&ev_timer, &tv);
617
618	yp_enable_events();
619	event_dispatch();
620	main_shutdown();
621
622	return (0);
623}
624
625void
626imsg_event_add(struct imsgev *iev)
627{
628	if (iev->handler == NULL) {
629		imsg_flush(&iev->ibuf);
630		return;
631	}
632
633	iev->events = EV_READ;
634	if (iev->ibuf.w.queued)
635		iev->events |= EV_WRITE;
636
637	event_del(&iev->ev);
638	event_set(&iev->ev, iev->ibuf.fd, iev->events, iev->handler, iev->data);
639	event_add(&iev->ev, NULL);
640}
641
642int
643imsg_compose_event(struct imsgev *iev, u_int16_t type, u_int32_t peerid,
644    pid_t pid, int fd, void *data, u_int16_t datalen)
645{
646	int	ret;
647
648	if ((ret = imsg_compose(&iev->ibuf, type, peerid,
649	    pid, fd, data, datalen)) != -1)
650		imsg_event_add(iev);
651	return (ret);
652}
653