make getpeername() return the original socket address which before it was intercepted
[hband-tools.git] / compiled-tools / relpath.c
blobeb92065e04d9d78bca77163921f6d28f1822db89
2 #include <strings.h>
3 #include <limits.h>
4 #include <stdio.h>
6 #define VERSION 0.5
7 #define MYNAME "relpath"
9 void help(FILE* fd)
11 fprintf(fd, "%s",
12 "Usage: " MYNAME " [-n] <DIR-1> <DIR-2>\n"
13 " Print a relative path from <DIR-2> to <DIR-1>.\n"
14 " Useful for creating relative symlinks.\n"
15 "Example:\n"
16 " This command creates <DIR-2>/symlink.txt pointing to <DIR-1>/link_target.txt:\n"
17 " ln -s $(" MYNAME " <DIR-1> <DIR-2>)link_target.txt <DIR-2>/symlink.txt\n"
18 "Options:\n"
19 " -n do not print newline\n"
20 "Exit codes:\n"
21 " 0 success\n"
22 " 1 a directory does not exist\n"
23 " 2 parameter error\n");
26 int main(int argc, char *argv[]) {
28 unsigned int i = 1;
29 unsigned int i2 = 0;
30 unsigned int per = 0;
31 unsigned int newline = 1;
32 char commondir[_POSIX_PATH_MAX];
33 char buff[_POSIX_PATH_MAX];
34 char route[_POSIX_PATH_MAX];
35 char realname1[_POSIX_PATH_MAX];
36 char realname2[_POSIX_PATH_MAX];
38 while(i < argc && argv[i][0] == '-') {
39 if(strcmp(argv[i], "-n")==0) {
40 newline = 0;
42 else if(strcmp(argv[i], "--help")==0) {
43 help(stdout);
44 exit(0);
46 i++;
49 if(i+1 < argc) {
50 if(realpath(argv[i], realname1)==0) exit(1);
51 i++;
52 if(realpath(argv[i], realname2)==0) exit(1);
54 else {
55 fprintf(stderr, MYNAME ": Parameter error\n");
56 help(stderr);
57 exit(2);
61 strcpy(buff, "");
62 strcpy(commondir, "");
63 strcpy(route, "");
64 #ifdef DEBUG
65 fprintf(stderr, " %s\n %s\n", realname1, realname2);
66 #endif
67 if(strcmp(realname1, realname2)==0) {
68 // directories are identical!
69 printf("./");
70 if(newline) printf("\n");
71 exit(0);
73 if(realname1[strlen(realname1)-1] != '/') strcat(realname1, "/");
74 if(realname2[strlen(realname2)-1] != '/') strcat(realname2, "/");
76 i = 0;
77 while(strlen(realname1)>i && strlen(realname2)>i && realname1[i] == realname2[i]) {
78 sprintf(buff, "%s%c", buff, realname1[i]);
79 if(realname1[i]=='/') {
80 strcat(commondir, buff);
81 strcpy(buff, "");
82 i2=i;
84 i++;
87 //route = "../"*(1+count("/",a2)).a1
89 while(strlen(realname2)>=++i) {
90 if(realname2[i]=='/') per++;
92 strcpy(buff, "");
93 while(per>0) {
94 strcat(buff, "../");
95 per--;
97 strcpy(route, buff);
99 while(strlen(realname1)>=++i2) {
100 sprintf(route, "%s%c", route, realname1[i2]);
103 #ifdef DEBUG
104 fprintf(stderr, "%s\n", commondir);
105 #endif
106 printf("%s", route);
107 if(newline) printf("\n");
109 exit(0);