swaylock/comm.c

110 lines
2.3 KiB
C
Raw Normal View History

2019-01-16 16:35:14 -06:00
#include <stdbool.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include "comm.h"
#include "log.h"
#include "swaylock.h"
2022-05-30 04:50:30 -05:00
#include "password-buffer.h"
2019-01-16 16:35:14 -06:00
2019-01-17 05:42:13 -06:00
static int comm[2][2] = {{-1, -1}, {-1, -1}};
2019-01-16 16:35:14 -06:00
ssize_t read_comm_request(char **buf_ptr) {
size_t size;
ssize_t amt;
amt = read(comm[0][0], &size, sizeof(size));
if (amt == 0) {
return 0;
} else if (amt < 0) {
swaylock_log_errno(LOG_ERROR, "read pw request");
return -1;
}
swaylock_log(LOG_DEBUG, "received pw check request");
2022-05-30 04:50:30 -05:00
char *buf = password_buffer_create(size);
2019-01-16 16:35:14 -06:00
if (!buf) {
return -1;
}
size_t offs = 0;
do {
amt = read(comm[0][0], &buf[offs], size - offs);
if (amt <= 0) {
swaylock_log_errno(LOG_ERROR, "failed to read pw");
return -1;
}
offs += (size_t)amt;
} while (offs < size);
*buf_ptr = buf;
return size;
}
bool write_comm_reply(bool success) {
if (write(comm[1][1], &success, sizeof(success)) != sizeof(success)) {
swaylock_log_errno(LOG_ERROR, "failed to write pw check result");
return false;
}
return true;
}
bool spawn_comm_child(void) {
if (pipe(comm[0]) != 0) {
swaylock_log_errno(LOG_ERROR, "failed to create pipe");
return false;
}
if (pipe(comm[1]) != 0) {
swaylock_log_errno(LOG_ERROR, "failed to create pipe");
return false;
}
pid_t child = fork();
if (child < 0) {
swaylock_log_errno(LOG_ERROR, "failed to fork");
return false;
} else if (child == 0) {
close(comm[0][1]);
close(comm[1][0]);
run_pw_backend_child();
}
close(comm[0][0]);
close(comm[1][1]);
return true;
}
2019-01-17 05:42:13 -06:00
bool write_comm_request(struct swaylock_password *pw) {
2019-01-16 16:35:14 -06:00
bool result = false;
2019-01-17 05:42:13 -06:00
2019-01-16 16:35:14 -06:00
size_t len = pw->len + 1;
size_t offs = 0;
if (write(comm[0][1], &len, sizeof(len)) < 0) {
swaylock_log_errno(LOG_ERROR, "Failed to request pw check");
2019-01-17 05:42:13 -06:00
goto out;
2019-01-16 16:35:14 -06:00
}
2019-01-17 05:42:13 -06:00
2019-01-16 16:35:14 -06:00
do {
ssize_t amt = write(comm[0][1], &pw->buffer[offs], len - offs);
if (amt < 0) {
swaylock_log_errno(LOG_ERROR, "Failed to write pw buffer");
2019-01-17 05:42:13 -06:00
goto out;
2019-01-16 16:35:14 -06:00
}
offs += amt;
} while (offs < len);
2019-01-17 05:42:13 -06:00
result = true;
out:
clear_password_buffer(pw);
return result;
}
bool read_comm_reply(void) {
bool result = false;
2019-01-16 16:35:14 -06:00
if (read(comm[1][0], &result, sizeof(result)) != sizeof(result)) {
swaylock_log_errno(LOG_ERROR, "Failed to read pw result");
2019-01-17 05:42:13 -06:00
result = false;
2019-01-16 16:35:14 -06:00
}
return result;
}
2019-01-17 05:42:13 -06:00
int get_comm_reply_fd(void) {
return comm[1][0];
}