summaryrefslogtreecommitdiff
path: root/usr.sbin/tcpdump/privsep.c
blob: 046f3a49db335973b5351b7b16471b1d1a6368ab (plain)
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
/*	$OpenBSD: privsep.c,v 1.18 2005/05/03 01:01:14 djm Exp $	*/

/*
 * Copyright (c) 2003 Can Erkin Acar
 * Copyright (c) 2003 Anil Madhavapeddy <anil@recoil.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>

#include <net/bpf.h>
#include <net/if.h>
#include <net/pfvar.h>
#include <netinet/in.h>
#include <netinet/if_ether.h>

#include <rpc/rpc.h>

#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <paths.h>
#include <pwd.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <tzfile.h>
#include <unistd.h>

#include "interface.h"
#include "privsep.h"
#include "pfctl_parser.h"

/*
 * tcpdump goes through five states: STATE_INIT is where the
 * bpf device and the input file is opened. In STATE_BPF, the
 * pcap filter gets set. STATE_FILTER is used for parsing
 * /etc/services and /etc/protocols and opening the output
 * file. STATE_RUN is the packet processing part.
 */

enum priv_state {
	STATE_INIT,		/* initial state */
	STATE_BPF,		/* input file/device opened */
	STATE_FILTER,		/* filter applied */
	STATE_RUN,		/* running and accepting network traffic */
};

#define ALLOW(action)	(1 << (action))

/*
 * Set of maximum allowed actions.
 */
static const int allowed_max[] = {
	/* INIT */	ALLOW(PRIV_OPEN_BPF) | ALLOW(PRIV_OPEN_DUMP) |
			ALLOW(PRIV_SETFILTER),
	/* BPF */	ALLOW(PRIV_SETFILTER),
	/* FILTER */	ALLOW(PRIV_OPEN_OUTPUT) | ALLOW(PRIV_GETSERVENTRIES) |
			ALLOW(PRIV_GETPROTOENTRIES) |
			ALLOW(PRIV_ETHER_NTOHOST) | ALLOW(PRIV_INIT_DONE),
	/* RUN */	ALLOW(PRIV_GETHOSTBYADDR) | ALLOW(PRIV_ETHER_NTOHOST) |
			ALLOW(PRIV_GETRPCBYNUMBER) | ALLOW(PRIV_GETLINES) |
			ALLOW(PRIV_LOCALTIME),
	/* QUIT */	0
};

/*
 * Default set of allowed actions. More actions get added
 * later depending on the supplied parameters.
 */
static int allowed_ext[] = {
	/* INIT */	ALLOW(PRIV_SETFILTER),
	/* BPF */	ALLOW(PRIV_SETFILTER),
	/* FILTER */	ALLOW(PRIV_GETSERVENTRIES),
	/* RUN */	ALLOW(PRIV_GETLINES) | ALLOW(PRIV_LOCALTIME),
	/* QUIT */	0
};

struct ftab {
	char *name;
	int max;
	int count;
};

static struct ftab file_table[] = {{"/etc/appletalk.names", 1, 0},
				   {PF_OSFP_FILE, 1, 0}};

#define NUM_FILETAB (sizeof(file_table) / sizeof(struct ftab))

int		debug_level = LOG_INFO;
int		priv_fd = -1;
static volatile	pid_t child_pid = -1;
static volatile	sig_atomic_t cur_state = STATE_INIT;

static void	parent_open_bpf(int, int *);
static void	parent_open_dump(int, const char *);
static void	parent_open_output(int, const char *);
static void	parent_setfilter(int, char *, int *);
static void	parent_init_done(int, int *);
static void	parent_gethostbyaddr(int);
static void	parent_ether_ntohost(int);
static void	parent_getrpcbynumber(int);
static void	parent_getserventries(int);
static void	parent_getprotoentries(int);
static void	parent_localtime(int fd);
static void	parent_getlines(int);

static void	sig_pass_to_chld(int);
static void	sig_got_chld(int);
static void	test_state(int, int);
static void	logmsg(int, const char *, ...);

int
priv_init(int argc, char **argv)
{
	int bpfd = -1;
	int i, socks[2], cmd, nflag = 0;
	struct passwd *pw;
	uid_t uid;
	gid_t gid;
	char *cmdbuf, *infile = NULL;
	char *RFileName = NULL;
	char *WFileName = NULL;

	closefrom(STDERR_FILENO + 1);
	for (i = 1; i < _NSIG; i++)
		signal(i, SIG_DFL);

	/* Create sockets */
	if (socketpair(AF_LOCAL, SOCK_STREAM, PF_UNSPEC, socks) == -1)
		err(1, "socketpair() failed");

	child_pid = fork();
	if (child_pid < 0)
		err(1, "fork() failed");

	if (!child_pid) {
		if (getuid() == 0) {
			pw = getpwnam("_tcpdump");
			if (pw == NULL)
				errx(1, "unknown user _tcpdump");
			endpwent();

			/* chroot, drop privs and return */
			if (chroot(pw->pw_dir) != 0)
				err(1, "unable to chroot");
			if (chdir("/") != 0)
				err(1, "unable to chdir");

			/* drop to _tcpdump */
			if (setgroups(1, &pw->pw_gid) == -1)
				err(1, "setgroups() failed");
			if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1)
				err(1, "setresgid() failed");
			if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
				err(1, "setresuid() failed");
		} else {
			/* Child - drop suid privileges */
			gid = getgid();
			uid = getuid();
			if (setresgid(gid, gid, gid) == -1)
				err(1, "setresgid() failed");
			if (setresuid(uid, uid, uid) == -1)
				err(1, "setresuid() failed");
		}
		close(socks[0]);
		priv_fd = socks[1];
		return (0);
	}

	/* Father - drop suid privileges */
	gid = getgid();
	uid = getuid();

	if (setresgid(gid, gid, gid) == -1)
		err(1, "setresgid() failed");
	if (setresuid(uid, uid, uid) == -1)
		err(1, "setresuid() failed");

	/* parse the arguments for required options so that the child
	 * need not send them back */
	opterr = 0;
	while ((i = getopt(argc, argv,
	    "ac:deE:fF:i:lLnNOopqr:s:StT:vw:xXy:Y")) != -1) {
		switch (i) {
		case 'n':
			nflag++;
			break;

		case 'r':
			RFileName = optarg;
			break;

		case 'w':
			WFileName = optarg;
			break;

		case 'F':
			infile = optarg;
			break;

		default:
			/* nothing */
			break;
		}
	}

	if (RFileName != NULL) {
		if (strcmp(RFileName, "-") != 0)
			allowed_ext[STATE_INIT] |= ALLOW(PRIV_OPEN_DUMP);
	} else
		allowed_ext[STATE_INIT] |= ALLOW(PRIV_OPEN_BPF);
	if (WFileName != NULL) {
		if (strcmp(WFileName, "-") != 0)
			allowed_ext[STATE_FILTER] |= ALLOW(PRIV_OPEN_OUTPUT);
		else
			allowed_ext[STATE_FILTER] |= ALLOW(PRIV_INIT_DONE);
	} else
		allowed_ext[STATE_FILTER] |= ALLOW(PRIV_INIT_DONE);
	if (!nflag) {
		allowed_ext[STATE_RUN] |= ALLOW(PRIV_GETHOSTBYADDR);
		allowed_ext[STATE_FILTER] |= ALLOW(PRIV_ETHER_NTOHOST);
		allowed_ext[STATE_RUN] |= ALLOW(PRIV_ETHER_NTOHOST);
		allowed_ext[STATE_RUN] |= ALLOW(PRIV_GETRPCBYNUMBER);
		allowed_ext[STATE_FILTER] |= ALLOW(PRIV_GETPROTOENTRIES);
	}

	if (infile)
		cmdbuf = read_infile(infile);
	else
		cmdbuf = copy_argv(&argv[optind]);

	/* Pass ALRM/TERM/HUP through to child, and accept CHLD */
	signal(SIGALRM, sig_pass_to_chld);
	signal(SIGTERM, sig_pass_to_chld);
	signal(SIGHUP,  sig_pass_to_chld);
	signal(SIGCHLD, sig_got_chld);

	setproctitle("[priv]");
	close(socks[1]);

	for (;;) {
		if (may_read(socks[0], &cmd, sizeof(int)))
			break;
		switch (cmd) {
		case PRIV_OPEN_BPF:
			test_state(cmd, STATE_BPF);
			parent_open_bpf(socks[0], &bpfd);
			break;
		case PRIV_OPEN_DUMP:
			test_state(cmd, STATE_BPF);
			parent_open_dump(socks[0], RFileName);
			break;
		case PRIV_OPEN_OUTPUT:
			test_state(cmd, STATE_RUN);
			parent_open_output(socks[0], WFileName);
			break;
		case PRIV_SETFILTER:
			test_state(cmd, STATE_FILTER);
			parent_setfilter(socks[0], cmdbuf, &bpfd);
			break;
		case PRIV_INIT_DONE:
			test_state(cmd, STATE_RUN);
			parent_init_done(socks[0], &bpfd);
			break;
		case PRIV_GETHOSTBYADDR:
			test_state(cmd, STATE_RUN);
			parent_gethostbyaddr(socks[0]);
			break;
		case PRIV_ETHER_NTOHOST:
			test_state(cmd, cur_state);
			parent_ether_ntohost(socks[0]);
			break;
		case PRIV_GETRPCBYNUMBER:
			test_state(cmd, STATE_RUN);
			parent_getrpcbynumber(socks[0]);
			break;
		case PRIV_GETSERVENTRIES:
			test_state(cmd, STATE_FILTER);
			parent_getserventries(socks[0]);
			break;
		case PRIV_GETPROTOENTRIES:
			test_state(cmd, STATE_FILTER);
			parent_getprotoentries(socks[0]);
			break;
		case PRIV_LOCALTIME:
			test_state(cmd, STATE_RUN);
			parent_localtime(socks[0]);
			break;
		case PRIV_GETLINES:
			test_state(cmd, STATE_RUN);
			parent_getlines(socks[0]);
			break;
		default:
			logmsg(LOG_ERR, "[priv]: unknown command %d", cmd);
			_exit(1);
			/* NOTREACHED */
		}
	}

	/* NOTREACHED */
	_exit(0);
}

static void
parent_open_bpf(int fd, int *bpfd)
{
	int snaplen, promisc, err;
	u_int dlt;
	char device[IFNAMSIZ];
	size_t iflen;

	logmsg(LOG_DEBUG, "[priv]: msg PRIV_OPEN_BPF received");

	must_read(fd, &snaplen, sizeof(int));
	must_read(fd, &promisc, sizeof(int));
	must_read(fd, &dlt, sizeof(u_int));
	iflen = read_string(fd, device, sizeof(device), __func__);
	if (iflen == 0)
		errx(1, "Invalid interface size specified");
	*bpfd = pcap_live(device, snaplen, promisc, dlt);
	err = errno;
	if (*bpfd < 0)
		logmsg(LOG_DEBUG,
		    "[priv]: failed to open bpf device for %s: %s",
		    device, strerror(errno));
	send_fd(fd, *bpfd);
	must_write(fd, &err, sizeof(int));
	/* do not close bpfd until filter is set */
}

static void
parent_open_dump(int fd, const char *RFileName)
{
	int file, err = 0;

	logmsg(LOG_DEBUG, "[priv]: msg PRIV_OPEN_DUMP received");

	if (RFileName == NULL) {
		file = -1;
		logmsg(LOG_ERR, "[priv]: No offline file specified");
	} else {
		file = open(RFileName, O_RDONLY, 0);
		err = errno;
		if (file < 0)
			logmsg(LOG_DEBUG, "[priv]: failed to open %s: %s",
			    RFileName, strerror(errno));
	}
	send_fd(fd, file);
	must_write(fd, &err, sizeof(int));
	if (file >= 0)
		close(file);
}

static void
parent_open_output(int fd, const char *WFileName)
{
	int file, err;

	logmsg(LOG_DEBUG, "[priv]: msg PRIV_OPEN_OUTPUT received");

	file = open(WFileName, O_WRONLY|O_CREAT|O_TRUNC, 0666);
	err = errno;
	send_fd(fd, file);
	must_write(fd, &err, sizeof(int));
	if (file < 0)
		logmsg(LOG_DEBUG, "[priv]: failed to open %s: %s",
		    WFileName, strerror(err));
	else
		close(file);
}

static void
parent_setfilter(int fd, char *cmdbuf, int *bpfd)
{
	logmsg(LOG_DEBUG, "[priv]: msg PRIV_SETFILTER received");

	if (setfilter(*bpfd, fd, cmdbuf))
		logmsg(LOG_DEBUG, "[priv]: setfilter() failed");
	close(*bpfd);	/* done with bpf descriptor */
	*bpfd = -1;
}

static void
parent_init_done(int fd, int *bpfd)
{
	int ret;

	logmsg(LOG_DEBUG, "[priv]: msg PRIV_INIT_DONE received");

	close(*bpfd);	/* done with bpf descriptor */
	*bpfd = -1;
	ret = 0;
	must_write(fd, &ret, sizeof(ret));
}

static void
parent_gethostbyaddr(int fd)
{
	char hostname[MAXHOSTNAMELEN];
	size_t hostname_len;
	int addr_af;
	struct hostent *hp;

	logmsg(LOG_DEBUG, "[priv]: msg PRIV_GETHOSTBYADDR received");

	/* Expecting: address block, address family */
	hostname_len = read_block(fd, hostname, sizeof(hostname), __func__);
	if (hostname_len == 0)
		_exit(1);
	must_read(fd, &addr_af, sizeof(int));
	hp = gethostbyaddr(hostname, hostname_len, addr_af);
	if (hp == NULL)
		write_zero(fd);
	else
		write_string(fd, hp->h_name);
}

static void
parent_ether_ntohost(int fd)
{
	struct ether_addr ether;
	char hostname[MAXHOSTNAMELEN];

	logmsg(LOG_DEBUG, "[priv]: msg PRIV_ETHER_NTOHOST received");

	/* Expecting: ethernet address */
	must_read(fd, &ether, sizeof(ether));
	if (ether_ntohost(hostname, &ether) == -1)
		write_zero(fd);
	else
		write_string(fd, hostname);
}

static void
parent_getrpcbynumber(int fd)
{
	int rpc;
	struct rpcent *rpce;

	logmsg(LOG_DEBUG, "[priv]: msg PRIV_GETRPCBYNUMBER received");

	must_read(fd, &rpc, sizeof(int));
	rpce = getrpcbynumber(rpc);
	if (rpce == NULL)
		write_zero(fd);
	else
		write_string(fd, rpce->r_name);
}

static void
parent_getserventries(int fd)
{
	struct servent *sp;

	logmsg(LOG_DEBUG, "[priv]: msg PRIV_GETSERVENTRIES received");

	for (;;) {
		sp = getservent();
		if (sp == NULL) {
			write_zero(fd);
			break;
		} else {
			write_string(fd, sp->s_name);
			must_write(fd, &sp->s_port, sizeof(int));
			write_string(fd, sp->s_proto);
		}
	}
	endservent();
}

static void
parent_getprotoentries(int fd)
{
	struct protoent *pe;

	logmsg(LOG_DEBUG, "[priv]: msg PRIV_GETPROTOENTRIES received");

	for (;;) {
		pe = getprotoent();
		if (pe == NULL) {
			write_zero(fd);
			break;
		} else {
			write_string(fd, pe->p_name);
			must_write(fd, &pe->p_proto, sizeof(int));
		}
	}
	endprotoent();
}

/* read the time and send the corresponding localtime and gmtime
 * results back to the child */
static void
parent_localtime(int fd)
{
	struct tm *lt, *gt;
	time_t t;

	logmsg(LOG_DEBUG, "[priv]: msg PRIV_LOCALTIME received");

	must_read(fd, &t, sizeof(time_t));

	/* this must be done seperately, since they apparently use the
	 * same local buffer */
	if ((lt = localtime(&t)) == NULL)
		errx(1, "localtime()");
	must_write(fd, lt, sizeof(*lt));

	if ((gt = gmtime(&t)) == NULL)
		errx(1, "gmtime()");
	must_write(fd, gt, sizeof(*gt));

	if (lt->tm_zone == NULL)
		write_zero(fd);
	else
		write_string(fd, lt->tm_zone);
}

static void
parent_getlines(int fd)
{
	FILE *fp;
	char *buf, *lbuf, *file;
	size_t len, fid;

	logmsg(LOG_DEBUG, "[priv]: msg PRIV_GETLINES received");

	must_read(fd, &fid, sizeof(size_t));
	if (fid >= NUM_FILETAB)
		errx(1, "invalid file id");

	file = file_table[fid].name;

	if (file == NULL)
		errx(1, "invalid file referenced");

	if (file_table[fid].count >= file_table[fid].max)
		errx(1, "maximum open count exceeded for %s", file);

	file_table[fid].count++;

	if ((fp = fopen(file, "r")) == NULL) {
		write_zero(fd);
		return;
	}

	lbuf = NULL;
	while ((buf = fgetln(fp, &len))) {
		if (buf[len - 1] == '\n')
			buf[len - 1] = '\0';
		else {
			if ((lbuf = (char *)malloc(len + 1)) == NULL)
				err(1, NULL);
			memcpy(lbuf, buf, len);
			lbuf[len] = '\0';
			buf = lbuf;
		}

		write_string(fd, buf);

		if (lbuf != NULL) {
			free(lbuf);
			lbuf = NULL;
		}
	}
	write_zero(fd);
	fclose(fp);
}

void
priv_init_done(void)
{
	int ret;

	if (priv_fd < 0)
		errx(1, "%s: called from privileged portion", __func__);

	write_command(priv_fd, PRIV_INIT_DONE);
	must_read(priv_fd, &ret, sizeof(int));
}

/* Reverse address resolution; response is placed into res, and length of
 * response is returned (zero on error) */
size_t
priv_gethostbyaddr(char *addr, size_t addr_len, int af, char *res, size_t res_len)
{
	if (priv_fd < 0)
		errx(1, "%s called from privileged portion", __func__);

	write_command(priv_fd, PRIV_GETHOSTBYADDR);
	write_block(priv_fd, addr_len, addr);
	must_write(priv_fd, &af, sizeof(int));

	return (read_string(priv_fd, res, res_len, __func__));
}

size_t
priv_ether_ntohost(char *name, size_t name_len, struct ether_addr *e)
{
	if (priv_fd < 0)
		errx(1, "%s called from privileged portion", __func__);

	write_command(priv_fd, PRIV_ETHER_NTOHOST);
	must_write(priv_fd, e, sizeof(*e));

	/* Read the host name */
	return (read_string(priv_fd, name, name_len, __func__));
}

size_t
priv_getrpcbynumber(int rpc, char *progname, size_t progname_len)
{
	if (priv_fd < 0)
		errx(1, "%s called from privileged portion", __func__);

	write_command(priv_fd, PRIV_GETRPCBYNUMBER);
	must_write(priv_fd, &rpc, sizeof(int));

	return read_string(priv_fd, progname, progname_len, __func__);
}

/* start getting service entries */
void
priv_getserventries(void)
{
	if (priv_fd < 0)
		errx(1, "%s called from privileged portion", __func__);

	write_command(priv_fd, PRIV_GETSERVENTRIES);
}

/* retrieve a service entry, should be called repeatedly after calling
   priv_getserventries(), until it returns zero. */
size_t
priv_getserventry(char *name, size_t name_len, int *port, char *prot,
    size_t prot_len)
{
	if (priv_fd < 0)
		errx(1, "%s called from privileged portion", __func__);

	/* read the service name */
	if (read_string(priv_fd, name, name_len, __func__) == 0)
		return 0;

	/* read the port */
	must_read(priv_fd, port, sizeof(int));

	/* read the protocol */
	return (read_string(priv_fd, prot, prot_len, __func__));
}

/* start getting ip protocol entries */
void
priv_getprotoentries(void)
{
	if (priv_fd < 0)
		errx(1, "%s called from privileged portion", __func__);

	write_command(priv_fd, PRIV_GETPROTOENTRIES);
}

/* retrieve a ip protocol entry, should be called repeatedly after calling
   priv_getprotoentries(), until it returns zero. */
size_t
priv_getprotoentry(char *name, size_t name_len, int *num)
{
	if (priv_fd < 0)
		errx(1, "%s called from privileged portion", __func__);

	/* read the proto name */
	if (read_string(priv_fd, name, name_len, __func__) == 0)
		return 0;

	/* read the num */
	must_read(priv_fd, num, sizeof(int));

	return (1);
}

/* localtime() replacement: ask parent for localtime and gmtime, cache
 * the localtime for about one minute i.e. until one of the fields other
 * than seconds changes. The check is done using gmtime
 * values since they are the same in parent and child. */
struct	tm *
priv_localtime(const time_t *t)
{
	static struct tm lt, gt0;
	static struct tm *gt = NULL;
	static char zone[TZ_MAX_CHARS];

	if (gt != NULL) {
		gt = gmtime(t);
		gt0.tm_sec = gt->tm_sec;
		gt0.tm_zone = gt->tm_zone;

		if (memcmp(gt, &gt0, sizeof(struct tm)) == 0) {
			lt.tm_sec = gt0.tm_sec;
			return &lt;
		}
	}

	write_command(priv_fd, PRIV_LOCALTIME);
	must_write(priv_fd, t, sizeof(time_t));
	must_read(priv_fd, &lt, sizeof(lt));
	must_read(priv_fd, &gt0, sizeof(gt0));

	if (read_string(priv_fd, zone, sizeof(zone), __func__))
		lt.tm_zone = zone;
	else
		lt.tm_zone = NULL;

	gt0.tm_zone = NULL;
	gt = &gt0;

	return &lt;
}

/* start getting lines from a file */
void
priv_getlines(size_t sz)
{
	if (priv_fd < 0)
		errx(1, "%s called from privileged portion", __func__);

	write_command(priv_fd, PRIV_GETLINES);
	must_write(priv_fd, &sz, sizeof(size_t));
}

/* retrieve a line from a file, should be called repeatedly after calling
   priv_getlines(), until it returns zero. */
size_t
priv_getline(char *line, size_t line_len)
{
	if (priv_fd < 0)
		errx(1, "%s called from privileged portion", __func__);

	/* read the line */
	return (read_string(priv_fd, line, line_len, __func__));
}

/* If priv parent gets a TERM or HUP, pass it through to child instead */
static void
sig_pass_to_chld(int sig)
{
	int save_err = errno;

	if (child_pid != -1)
		kill(child_pid, sig);
	errno = save_err;
}

/* When child dies, move into the shutdown state */
static void
sig_got_chld(int sig)
{
	pid_t pid;
	int status;
	int save_err = errno;

	do {
		pid = waitpid(child_pid, &status, WNOHANG);
		if (pid > 0 && (WIFEXITED(status) || WIFSIGNALED(status)))
			_exit(0);
	} while (pid == -1 && errno == EINTR);

	if (pid == -1)
		_exit(1);

	errno = save_err;
}

/* Read all data or return 1 for error. */
int
may_read(int fd, void *buf, size_t n)
{
	char *s = buf;
	ssize_t res, pos = 0;

	while (n > pos) {
		res = read(fd, s + pos, n - pos);
		switch (res) {
		case -1:
			if (errno == EINTR || errno == EAGAIN)
				continue;
		case 0:
			return (1);
		default:
			pos += res;
		}
	}
	return (0);
}

/* Read data with the assertion that it all must come through, or
 * else abort the process.  Based on atomicio() from openssh. */
void
must_read(int fd, void *buf, size_t n)
{
	char *s = buf;
	ssize_t res, pos = 0;

	while (n > pos) {
		res = read(fd, s + pos, n - pos);
		switch (res) {
		case -1:
			if (errno == EINTR || errno == EAGAIN)
				continue;
		case 0:
			_exit(0);
		default:
			pos += res;
		}
	}
}

/* Write data with the assertion that it all has to be written, or
 * else abort the process.  Based on atomicio() from openssh. */
void
must_write(int fd, const void *buf, size_t n)
{
	const char *s = buf;
	ssize_t res, pos = 0;

	while (n > pos) {
		res = write(fd, s + pos, n - pos);
		switch (res) {
		case -1:
			if (errno == EINTR || errno == EAGAIN)
				continue;
		case 0:
			_exit(0);
		default:
			pos += res;
		}
	}
}

/* test for a given state, and possibly increase state */
static void
test_state(int action, int next)
{
	if (cur_state < 0 || cur_state > STATE_RUN) {
		logmsg(LOG_ERR, "[priv] Invalid state: %d", cur_state);
		_exit(1);
	}
	if ((allowed_max[cur_state] & allowed_ext[cur_state]
	    & ALLOW(action)) == 0) {
		logmsg(LOG_ERR, "[priv] Invalid action %d in state %d",
		    action, cur_state);
		_exit(1);
	}
	if (next < cur_state) {
		logmsg(LOG_ERR, "[priv] Invalid next state: %d < %d",
		    next, cur_state);
		_exit(1);
	}

	cur_state = next;
}

static void
logmsg(int pri, const char *message, ...)
{
	va_list ap;
	if (pri > debug_level)
		return;
	va_start(ap, message);

	vfprintf(stderr, message, ap);
	fprintf(stderr, "\n");
	va_end(ap);
}

/* write a command to the peer */
void
write_command(int fd, int cmd)
{
	must_write(fd, &cmd, sizeof(cmd));
}

/* write a zero 'length' to signal an error to read_{string|block} */
void
write_zero(int fd)
{
	size_t len = 0;
	must_write(fd, &len, sizeof(size_t));
}

/* send a string */
void
write_string(int fd, const char *str)
{
	size_t len;

	len = strlen(str) + 1;
	must_write(fd, &len, sizeof(size_t));
	must_write(fd, str, len);
}

/* send a block of data of given size */
void
write_block(int fd, size_t size, const char *str)
{
	must_write(fd, &size, sizeof(size_t));
	must_write(fd, str, size);
}

/* read a string from the channel, return 0 if error, or total size of
 * the buffer, including the terminating '\0' */
size_t
read_string(int fd, char *buf, size_t size, const char *func)
{
	size_t len;

	len = read_block(fd, buf, size, func);
	if (len == 0)
		return (0);

	if (buf[len - 1] != '\0')
		errx(1, "%s: received invalid string", func);

	return (len);
}

/* read a block of data from the channel, return length of data, or 0
 * if error */
size_t
read_block(int fd, char *buf, size_t size, const char *func)
{
	size_t len;
	/* Expect back an integer size, and then a string of that length */
	must_read(fd, &len, sizeof(size_t));

	/* Check there was no error (indicated by a return of 0) */
	if (len == 0)
		return (0);

	/* Make sure we aren't overflowing the passed in buffer */
	if (size < len)
		errx(1, "%s: overflow attempt in return", func);

	/* Read the string and make sure we got all of it */
	must_read(fd, buf, len);
	return (len);
}