/*
 * follow untrusted symlink in sticky directory
 */

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>

int main(void)
{
	char tmpl[] = "/tmp/t106_XXXXXX";
	char *dir = mkdtemp(tmpl);
	if (!dir) return errno;

	/* Set sticky bit on directory. */
	chmod(dir, 01777);

	/* Create a regular file in the directory. */
	char target[256];
	snprintf(target, sizeof(target), "%s/target", dir);
	int fd = open(target, O_CREAT | O_WRONLY, 0644);
	if (fd < 0) {
		rmdir(dir);
		return errno;
	}
	close(fd);

	/* Create a symlink in the sticky directory. */
	char link[256];
	snprintf(link, sizeof(link), "%s/link", dir);
	symlink(target, link);

	/* Try to open the symlink. */
	fd = open(link, O_RDONLY);
	if (fd >= 0) close(fd);

	unlink(link);
	unlink(target);
	rmdir(dir);
	return 0;
}
