Tom Hale <tomn...@gmail.com> added the comment:

The most correct work-around I believe exists is:

(updates at: https://stackoverflow.com/a/55742015/5353461)

    def symlink_force(target, link_name):
        '''
        Create a symbolic link pointing to target named link_name.
        Overwrite target if it exists.
        '''
    
        # os.replace may fail if files are on different filesystems.
        # Therefore, use the directory of target
        link_dir = os.path.dirname(target)
    
        # os.symlink requires that the target does NOT exist.
        # Avoid race condition of file creation between mktemp and symlink:
        while True:
            temp_pathname = tempfile.mktemp(suffix='.tmp', \
                            prefix='symlink_force_tmp-', dir=link_dir)
            try:
                os.symlink(target, temp_pathname)
                break  # Success, exit loop
            except FileExistsError:
                time.sleep(0.001)  # Prevent high load in pathological 
conditions
            except:
                raise
        os.replace(temp_pathname, link_name)

An unlikely race condition still remains: the symlink created at the 
randomly-named `temp_path` could be modified between creation and 
rename/replacing the specified link name.

Suggestions for improvement welcome.

----------
type:  -> security

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue36656>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to