The trouble with symbolic links
The trouble with symbolic links
Posted Jul 7, 2022 22:51 UTC (Thu) by zaitseff (subscriber, #851)Parent article: The trouble with symbolic links
As Chris points out, the problem is not so much symlinks as Time Of Check to Time of Use (TOCTOU). Take, for example, a problem I've faced writing a simple C program:
- I want my program to read and store user data/configuration.
- The traditional place for that data (over the thirty years of the program so far) has been ~/.PROGRAM.
- Modern XDG systems use ~/.local/share for such purposes (actually, possibly using XDG_DATA_HOME from the environment).
- I'd like my program to continue to use ~/.PROGRAM if it already exists, otherwise use ${XDG_DATA_HOME}/PROGRAM if $XDG_DATA_HOME is set (creating the directory, and any parents as required, if it doesn't exist), otherwise use ~/.local/share/PROGRAM (creating the directory, and any parents as required, if it doesn't exist).
The naïve way would be to code up something like the following pseudo-C for determining which directory to use:
const char *traditional_path = "/home/john/.PROGRAM"; /* Just for testing */
const char *xdg_default_path = "/home/john/.local/share/PROGRAM";
const char *xdg_data_home = getenv("XDG_DATA_HOME");
char *xdg_path;
if (stat(traditional_path, &statbuf) == 0 && S_ISDIR(statbuf.st_mode)) {
return traditional_path;
} else if (xdg_data_home != NULL && *xdg_data_home != '\0' && *xdg_data_home == '/') {
/* Use xdg_data_home + "/PROGRAM"; */
xdg_path = strcat_malloc(xdg_data_home, "/PROGRAM");
return xdg_path;
} else {
return xdg_default_path;
}
And there you have it: a TOCTOU error (check for /home/john/.trader before creating the final target path using mkdir() later). No symlinks need be involved.
Now you can merrily post your solution to the above problem! :-)