xref: /openbsd/usr.bin/readlink/readlink.c (revision 7b36286a)
1 /*
2  * $OpenBSD: readlink.c,v 1.24 2007/09/10 07:42:26 sobrado Exp $
3  *
4  * Copyright (c) 1997
5  *	Kenneth Stailey (hereinafter referred to as the author)
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. The name of the author may not be used to endorse or promote products
16  *    derived from this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 #include <limits.h>
31 #include <errno.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 
37 static void	usage(void);
38 
39 int
40 main(int argc, char *argv[])
41 {
42 	char buf[PATH_MAX];
43 	int n, ch, nflag = 0, fflag = 0;
44 	extern int optind;
45 
46 	while ((ch = getopt(argc, argv, "fn")) != -1)
47 		switch (ch) {
48 		case 'f':
49 			fflag = 1;
50 			break;
51 		case 'n':
52 			nflag = 1;
53 			break;
54 		default:
55 			usage();
56 		}
57 	argc -= optind;
58 	argv += optind;
59 
60 	if (argc != 1)
61 		usage();
62 
63 	n = strlen(argv[0]);
64 	if (n > PATH_MAX - 1) {
65 		fprintf(stderr,
66 		    "readlink: filename longer than PATH_MAX-1 (%d)\n",
67 		    PATH_MAX - 1);
68 		exit(1);
69 	}
70 
71 	if (fflag) {
72 		if (realpath(argv[0], buf) == NULL)
73 			err(1, "%s", argv[0]);
74 	} else {
75 		if ((n = readlink(argv[0], buf, sizeof buf-1)) < 0)
76 			exit(1);
77 		buf[n] = '\0';
78 	}
79 
80 	printf("%s", buf);
81 	if (!nflag)
82 		putchar('\n');
83 	exit(0);
84 }
85 
86 static void
87 usage(void)
88 {
89 	(void)fprintf(stderr, "usage: readlink [-fn] file\n");
90 	exit(1);
91 }
92