summaryrefslogtreecommitdiff
path: root/src/pwd.c
blob: 8ccd28be1d17ab9d72bac9f2065cd320e3c7e8fc (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
 * pwd.c
 * Implementation of SUSv3 XCU pwd utility
 * Copyright © 2007 Rich Felker
 * Licensed under the terms of the GNU General Public License, v2 or later
 */

/* NOTE: This implementation assumes PATH_MAX is defined and correct. */

#include <limits.h>
#include <unistd.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

static int my_write(int fd, const char *s, size_t l)
{
	if (!l) l = strlen(s);
	while (l) {
		ssize_t n = write(fd, s, l);
		if (n<0) return -1;
		s += n; l -= n;
	}
	return 0;
}

static void my_perror(char *prog, char *msg)
{
	char *err = strerror(errno);
	write(2, prog, strlen(prog));
	write(2, ": ", 2);
	write(2, msg, strlen(msg));
	write(2, ": ", 2);
	write(2, err, strlen(err));
	write(2, "\n", 1);
}

static int is_rel(const char *s)
{
	unsigned dots=0, slash=1;
	if (*s++ != '/') return 1;
	for (; *s; s++) {
		if (*s == '/') {
			if (dots-1<2) return 1;
			dots=0;
		}
		else slash=1;
		if (slash && *s == '.') dots++;
		else dots=slash=0;
	}
	return dots-1<2;
}

int main(int argc, char *argv[])
{
	int i, j;
	int p=0;
	char buf[PATH_MAX+2];
	struct stat st1, st2;
	char *pwd;
	
	for (i=1; i<argc && argv[i][0]=='-'; i++)
		for (j=1; argv[i][j]; j++) {
			switch (argv[i][j]) {
			case 'L': p=0; continue;
			case 'P': p=1;
			case 0: continue;
			}
invalid:
			errno = EINVAL;
			my_perror(argv[0], argv[i]);
			return 1;
		}
	if (i<argc) goto invalid;
	if (p || !(pwd=getenv("PWD")) || is_rel(pwd)
	 || stat(pwd, &st1) || stat(".", &st2)
	 || st1.st_dev != st2.st_dev
	 || st1.st_ino != st2.st_ino) {
		if (!getcwd(buf, sizeof buf)) {
			my_perror(argv[0], "getcwd");
			return 1;
		}
	} else {
		/* safe because stat succeeded */
		strcpy(buf, pwd);
	}
	strcat(buf, "\n");
	return my_write(1, buf, 0) != 0;
}