/*
 * oo7-daemon's PAM socket ($XDG_RUNTIME_DIR/oo7-pam.sock, oo7 >= 0.6):
 * unlock the wallet with a password, or change its password. The daemon
 * takes these from root or from its own user. A message is its length
 * (u32, little-endian) and then a D-Bus struct (y s ay ay), little-endian:
 * operation, user name, old secret, new secret. Shared by c8-wallet and
 * pam_c8wallet, so plain C and no GLib.
 */
#ifndef C8_OO7_PAM_H
#define C8_OO7_PAM_H

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>

enum oo7_pam_op { OO7_PAM_UNLOCK = 0, OO7_PAM_CHANGE_PASSWORD = 1 };

static inline size_t oo7_pam_put(unsigned char *buf, size_t at, const void *data,
		uint32_t len, int nul) {
	while (at % 4) {
		buf[at++] = 0;
	}
	buf[at++] = len & 0xff;
	buf[at++] = (len >> 8) & 0xff;
	buf[at++] = (len >> 16) & 0xff;
	buf[at++] = (len >> 24) & 0xff;
	memcpy(buf + at, data, len);
	at += len;
	if (nul) {
		buf[at++] = 0;
	}
	return at;
}

/* Sends one message; 0 once written. The buffer is wiped either way. */
static inline int oo7_pam_send(const char *socket_path, enum oo7_pam_op op,
		const char *user, const char *old_secret, const char *new_secret) {
	size_t ul = strlen(user), ol = strlen(old_secret), nl = strlen(new_secret);
	size_t size = 4 + 4 + 4 + ul + 1 + 3 + 4 + ol + 3 + 4 + nl;
	unsigned char *buf = calloc(1, size);
	if (buf == NULL) {
		return -1;
	}
	size_t at = 4;
	buf[at++] = op;
	at = oo7_pam_put(buf, at, user, ul, 1);
	at = oo7_pam_put(buf, at, old_secret, ol, 0);
	at = oo7_pam_put(buf, at, new_secret, nl, 0);
	uint32_t body = at - 4;
	buf[0] = body & 0xff;
	buf[1] = (body >> 8) & 0xff;
	buf[2] = (body >> 16) & 0xff;
	buf[3] = (body >> 24) & 0xff;

	int ret = -1;
	struct sockaddr_un addr = {.sun_family = AF_UNIX};
	int fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
	if (fd >= 0 && snprintf(addr.sun_path, sizeof(addr.sun_path), "%s",
			socket_path) < (int)sizeof(addr.sun_path) &&
			connect(fd, (struct sockaddr *)&addr, sizeof(addr)) == 0) {
		size_t done = 0;
		while (done < at) {
			ssize_t n = write(fd, buf + done, at - done);
			if (n <= 0) {
				break;
			}
			done += n;
		}
		ret = done == at ? 0 : -1;
	}
	if (fd >= 0) {
		close(fd);
	}
	explicit_bzero(buf, size);
	free(buf);
	return ret;
}

#endif
