36 static int alt_root_initialized = 0; |
36 static int alt_root_initialized = 0; |
37 |
37 |
38 int fd; |
38 int fd; |
39 char alt_path[PATH_MAX + 1], *alt_path_end; |
39 char alt_path[PATH_MAX + 1], *alt_path_end; |
40 const char *s; |
40 const char *s; |
|
41 int free_space; |
41 |
42 |
42 if (!alt_root_initialized) { |
43 if (!alt_root_initialized) { |
43 alt_root_initialized = -1; |
44 alt_root_initialized = -1; |
44 alt_root = getenv(SA_ALTROOT); |
45 alt_root = getenv(SA_ALTROOT); |
45 } |
46 } |
46 |
47 |
47 if (alt_root == NULL) { |
48 if (alt_root == NULL) { |
48 return open(name, O_RDONLY); |
49 return open(name, O_RDONLY); |
49 } |
50 } |
50 |
51 |
51 strcpy(alt_path, alt_root); |
52 |
|
53 if (strlen(alt_root) + strlen(name) < PATH_MAX) { |
|
54 // Buffer too small. |
|
55 return -1; |
|
56 } |
|
57 |
|
58 strncpy(alt_path, alt_root, PATH_MAX); |
|
59 alt_path[PATH_MAX] = '\0'; |
52 alt_path_end = alt_path + strlen(alt_path); |
60 alt_path_end = alt_path + strlen(alt_path); |
53 |
61 free_space = PATH_MAX + 1 - (alt_path_end-alt_path); |
54 // Strip path items one by one and try to open file with alt_root prepended |
62 |
|
63 // Strip path items one by one and try to open file with alt_root prepended. |
55 s = name; |
64 s = name; |
56 while (1) { |
65 while (1) { |
57 strcat(alt_path, s); |
66 strncat(alt_path, s, free_space); |
58 s += 1; |
67 s += 1; // Skip /. |
59 |
68 |
60 fd = open(alt_path, O_RDONLY); |
69 fd = open(alt_path, O_RDONLY); |
61 if (fd >= 0) { |
70 if (fd >= 0) { |
62 print_debug("path %s substituted for %s\n", alt_path, name); |
71 print_debug("path %s substituted for %s\n", alt_path, name); |
63 return fd; |
72 return fd; |