1 /* $Id$ */
2 
3 /*
4  * Copyright (c) 2006 Nicholas Marriott <nicholas.marriott@gmail.com>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
15  * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
16  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #include <sys/types.h>
20 
21 #include "fdm.h"
22 
23 int
privsep_send(struct io * io,struct msg * msg,struct msgbuf * msgbuf)24 privsep_send(struct io *io, struct msg *msg, struct msgbuf *msgbuf)
25 {
26 	char *cause;
27 
28 	msg->size = 0;
29 	if (msgbuf != NULL && msgbuf->buf != NULL && msgbuf->len > 0)
30 		msg->size = msgbuf->len;
31 
32 	io_write(io, msg, sizeof *msg);
33 	if (io_flush(io, INFTIM, &cause) != 0)
34 		return (-1);
35 
36 	if (msg->size != 0) {
37 		io_write(io, msgbuf->buf, msgbuf->len);
38 		if (io_flush(io, INFTIM, &cause) != 0)
39 			return (-1);
40 	}
41 
42 	return (0);
43 }
44 
45 int
privsep_check(struct io * io)46 privsep_check(struct io *io)
47 {
48 	return (IO_RDSIZE(io) >= sizeof (struct msg));
49 }
50 
51 int
privsep_recv(struct io * io,struct msg * msg,struct msgbuf * msgbuf)52 privsep_recv(struct io *io, struct msg *msg, struct msgbuf *msgbuf)
53 {
54 	char	*tmpbuf;
55 
56 	if (msgbuf != NULL) {
57 		msgbuf->buf = NULL;
58 		msgbuf->len = 0;
59 	}
60 
61 	if (io_wait(io, sizeof *msg, INFTIM, NULL) != 0)
62 		return (-1);
63 	if (io_read2(io, msg, sizeof *msg) != 0)
64 		return (-1);
65 
66 	if (msg->size == 0)
67 		return (0);
68 
69 	if (io_wait(io, msg->size, INFTIM, NULL) != 0)
70 		return (-1);
71 	if (msgbuf == NULL) {
72 		if ((tmpbuf = io_read(io, msg->size)) == NULL)
73 			return (-1);
74 		xfree(tmpbuf);
75 	} else {
76 		if ((msgbuf->buf = io_read(io, msg->size)) == NULL)
77 			return (-1);
78 		msgbuf->len = msg->size;
79 	}
80 
81 	return (0);
82 }
83