#include <9pm/u.h>
#include <9pm/libc.h>

/*
 * The tls device is sufficiently special, and guaranteeing security,
 * that we use #a rather than /net/tls
 */

int
pushtls(int fd, char *alg, int isclient, char *secret, char *dir)
{
	char buf[8];
	char dname[64];
	int n, data, ctl;

	ctl = open("#a/tls/clone", ORDWR);
	if(ctl < 0)
		return -1;
	n = read(ctl, buf, sizeof(buf)-1);
	if(n < 0)
		goto error;
	buf[n] = 0;
	if(dir)
		sprint(dir, "#a/tls/%s", buf);
	sprint(dname, "#a/tls/%s/data", buf);
	data = open(dname, ORDWR);
	if(data < 0)
		goto error;
	if(fprint(ctl, "fd %d 0x301", fd) < 0 ||
	   fprint(ctl, "secret %s %d %s", alg, isclient, secret) < 0 ||
	   fprint(ctl, "changecipher") < 0 ||
	   fprint(ctl, "opened") < 0){
		close(data);
		goto error;
	}
	close(fd);
	close(ctl);
	return data;
error:
	close(ctl);
	return -1;
}
