|
| 1 | +// SPDX-License-Identifier: Apache-2.0 |
| 2 | +/* |
| 3 | + * Copyright (C) 2024-2025 Aleksa Sarai <[email protected]> |
| 4 | + * Copyright (C) 2024-2025 SUSE LLC |
| 5 | + * |
| 6 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | + * you may not use this file except in compliance with the License. |
| 8 | + * You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, software |
| 13 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | + * See the License for the specific language governing permissions and |
| 16 | + * limitations under the License. |
| 17 | + */ |
| 18 | + |
| 19 | +package pathrs |
| 20 | + |
| 21 | +import ( |
| 22 | + "fmt" |
| 23 | + "os" |
| 24 | + "path/filepath" |
| 25 | +) |
| 26 | + |
| 27 | +// MkdirAllParentInRoot is like [MkdirAllInRoot] except that it only creates |
| 28 | +// the parent directory of the target path, returning the trailing component so |
| 29 | +// the caller has more flexibility around constructing the final inode. |
| 30 | +// |
| 31 | +// Callers need to be very careful operating on the trailing path, as trivial |
| 32 | +// mistakes like following symlinks can cause security bugs. Most people |
| 33 | +// should probably just use [MkdirAllInRoot] or [CreateInRoot]. |
| 34 | +func MkdirAllParentInRoot(root, unsafePath string, mode os.FileMode) (*os.File, string, error) { |
| 35 | + unsafePath, err := hallucinateUnsafePath(root, unsafePath) |
| 36 | + if err != nil { |
| 37 | + return nil, "", fmt.Errorf("failed to construct hallucinated target path: %w", err) |
| 38 | + } |
| 39 | + |
| 40 | + dirPath, filename := filepath.Split(unsafePath) |
| 41 | + if filepath.Join("/", filename) == "/" { |
| 42 | + return nil, "", fmt.Errorf("create parent dir in root subpath %q has bad trailing component %q", unsafePath, filename) |
| 43 | + } |
| 44 | + |
| 45 | + dirFd, err := MkdirAllInRoot(root, dirPath, mode) |
| 46 | + return dirFd, filename, err |
| 47 | +} |
0 commit comments