utils.c

#include "utils.h"

#include <err.h>
#include <errno.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

extern int verbose;

int
locate_xauthority_file(const char *login, char **out)
{
	const char * const suffix = "/.Xauthority";
	size_t length;
	struct passwd *entry;

	if (verbose)
		fprintf(stderr, "locate_xauthority_file(%s, %p)\n", login,
		    (void*)out);

	if ((entry = getpwnam(login)) == NULL)
		return -1;

	/* number is strlen("/.Xauthority") + 1 */
	length = strlen(entry->pw_dir) + strlen(suffix) + 1;
	*out = malloc(length);
	if (snprintf(*out, length, "%s%s", entry->pw_dir, suffix) == -1) {
		free(*out);
		return -1;
	}
	if (verbose)
		fprintf(stderr, "out: %s", *out);
	return 0;
}