Skip to content

Commit

Permalink
File.mkdir_p: Fix TOCTOU issue & handle errors from parent mkdir
Browse files Browse the repository at this point in the history
  • Loading branch information
lanodan committed Jan 29, 2025
1 parent 965ee9b commit 5914634
Showing 1 changed file with 8 additions and 9 deletions.
17 changes: 8 additions & 9 deletions lib/elixir/lib/file.ex
Original file line number Diff line number Diff line change
Expand Up @@ -310,24 +310,23 @@ defmodule File do
end

defp do_mkdir_p(path) do
if dir?(path) do
if path == "/" or path == "." do
:ok
else
parent = Path.dirname(path)

if parent == path do
# Protect against infinite loop
{:error, :einval}
else
_ = do_mkdir_p(parent)

with {_, false} <- {:loop, parent == path},
{_, :ok} <- {:parent, do_mkdir_p(parent)} do
case :file.make_dir(path) do
{:error, :eexist} = error ->
if dir?(path), do: :ok, else: error
{:error, :eexist} ->
if dir?(path), do: :ok, else: {:error, :enotdir}

other ->
other
end
else
{:loop, _} -> {:error, :einval}
{:parent, e} -> e
end
end
end
Expand Down

0 comments on commit 5914634

Please sign in to comment.