Skip to content

Commit

Permalink
Merge pull request #505 from waterkip/agent-rewrite
Browse files Browse the repository at this point in the history
Refactor agent.c for socket initialisation by @waterkip
  • Loading branch information
GPaulovics authored Apr 16, 2019
2 parents 81b9889 + afd66ad commit d318aac
Showing 1 changed file with 24 additions and 24 deletions.
48 changes: 24 additions & 24 deletions agent.c
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,26 @@ static int agent_socket_get_cred(int fd, struct ucred *cred)
}
#endif

void _assert_socket_sun_path(struct sockaddr_un *sa, char *path)
{
if (strlen(path) >= sizeof(sa->sun_path)) {
die("Path too large for agent control socket.");
}
}

int _setup_agent_socket(struct sockaddr_un *sa, char *path)
{
int fd;

_assert_socket_sun_path(sa, path);
memset(sa, 0, sizeof(*sa));
sa->sun_family = AF_UNIX;
strlcpy(sa->sun_path, path, sizeof(sa->sun_path));

fd = socket(AF_UNIX, SOCK_STREAM, 0);
return fd;
}

static void agent_run(unsigned const char key[KDF_HASH_LEN])
{
char *agent_timeout_str;
Expand All @@ -150,6 +170,7 @@ static void agent_run(unsigned const char key[KDF_HASH_LEN])
signal(SIGQUIT, agent_cleanup);
signal(SIGTERM, agent_cleanup);
signal(SIGALRM, agent_cleanup);

agent_timeout_str = getenv("LPASS_AGENT_TIMEOUT");
agent_timeout = 60 * 60; /* One hour by default. */
if (agent_timeout_str && strlen(agent_timeout_str))
Expand All @@ -158,14 +179,7 @@ static void agent_run(unsigned const char key[KDF_HASH_LEN])
alarm(agent_timeout);

_cleanup_free_ char *path = agent_socket_path();
if (strlen(path) >= sizeof(sa.sun_path))
die("Path too large for agent control socket.");

fd = socket(AF_UNIX, SOCK_STREAM, 0);

memset(&sa, 0, sizeof(sa));
sa.sun_family = AF_UNIX;
strlcpy(sa.sun_path, path, sizeof(sa.sun_path));
fd = _setup_agent_socket(&sa, path);

unlink(path);

Expand Down Expand Up @@ -209,14 +223,7 @@ void agent_kill(void)
int fd;

_cleanup_free_ char *path = agent_socket_path();
if (strlen(path) >= sizeof(sa.sun_path))
die("Path too large for agent control socket.");

fd = socket(AF_UNIX, SOCK_STREAM, 0);

memset(&sa, 0, sizeof(sa));
sa.sun_family = AF_UNIX;
strlcpy(sa.sun_path, path, sizeof(sa.sun_path));
fd = _setup_agent_socket(&sa, path);

if (connect(fd, (struct sockaddr *)&sa, SUN_LEN(&sa)) < 0)
goto out;
Expand All @@ -243,14 +250,7 @@ bool agent_ask(unsigned char key[KDF_HASH_LEN])
bool ret = false;

_cleanup_free_ char *path = agent_socket_path();
if (strlen(path) >= sizeof(sa.sun_path))
die("Path too large for agent control socket.");

fd = socket(AF_UNIX, SOCK_STREAM, 0);

memset(&sa, 0, sizeof(sa));
sa.sun_family = AF_UNIX;
strlcpy(sa.sun_path, path, sizeof(sa.sun_path));
fd = _setup_agent_socket(&sa, path);

ret = connect(fd, (struct sockaddr *)&sa, SUN_LEN(&sa)) >= 0;
if (!ret)
Expand Down

0 comments on commit d318aac

Please sign in to comment.