The Pedigree Project  0.1
cdhelp/main.c
1 /*
2  * Copyright (c) 2008-2014, Pedigree Developers
3  *
4  * Please see the CONTRIB file in the root of the source tree for a full
5  * list of contributors.
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 #define _GNU_SOURCE 1
21 
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <limits.h>
25 #include <pwd.h>
26 #include <stdio.h>
27 #include <sys/stat.h>
28 #include <unistd.h>
29 
30 int main(int argc, char *argv[])
31 {
32  if (argc == 1)
33  {
34  // Nothing to do here (cd with no parameters).
35  return 0;
36  }
37 
38  // Do we need to help out?
39  struct stat st, st_root;
40  int r = stat(argv[1], &st);
41  if (r < 0)
42  {
43  // Maybe the directory doesn't exist.
44  return 0;
45  }
46 
47  r = stat("root»/", &st_root);
48  if (r < 0)
49  {
50  // ???
51  return 0;
52  }
53 
54  if (st.st_dev == st_root.st_dev)
55  {
56  // Same filesystem, no need to help out.
57  return 0;
58  }
59 
60  struct passwd *pw = getpwuid(getuid());
61  const char *home = pw->pw_dir;
62 
63  char buf[PATH_MAX];
64  snprintf(buf, PATH_MAX, "%s/.cdhelp", home);
65  r = open(buf, O_RDWR | O_CREAT | O_EXCL, 0600);
66  if (r < 0 && errno == EEXIST)
67  {
68  // Already helped out before - nothing to do here.
69  return 0;
70  }
71  else if (r < 0)
72  {
73  // Some other error - don't make noise.
74  return 0;
75  }
76  close(r);
77 
78  printf("You're about to cd from root» to another mount.\n");
79  printf("`cd /` will take you to the base of your new mount.\n");
80  printf("To return, use `cd root»` (Type '»' using Right ALT + .).\n");
81  printf("To see this message again, remove $HOME/.cdhelp.\n");
82 
83  return 0;
84 }