Skip to content

Commit 563c823

Browse files
committed
File.mkdir_p: Fix TOCTOU issue & handle errors from parent mkdir
1 parent 965ee9b commit 563c823

File tree

1 file changed

+19
-16
lines changed

1 file changed

+19
-16
lines changed

lib/elixir/lib/file.ex

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -309,25 +309,28 @@ defmodule File do
309309
:ok
310310
end
311311

312-
defp do_mkdir_p(path) do
313-
if dir?(path) do
314-
:ok
315-
else
316-
parent = Path.dirname(path)
312+
defp do_mkdir_p(".") do
313+
:ok
314+
end
317315

318-
if parent == path do
319-
# Protect against infinite loop
320-
{:error, :einval}
321-
else
322-
_ = do_mkdir_p(parent)
316+
defp do_mkdir_p(path) do
317+
parent = Path.dirname(path)
323318

324-
case :file.make_dir(path) do
325-
{:error, :eexist} = error ->
326-
if dir?(path), do: :ok, else: error
319+
if parent == path do
320+
{:error, :einval}
321+
else
322+
case do_mkdir_p(parent) do
323+
:ok ->
324+
case :file.make_dir(path) do
325+
{:error, :eexist} ->
326+
if dir?(path), do: :ok, else: {:error, :enotdir}
327+
328+
other ->
329+
other
330+
end
327331

328-
other ->
329-
other
330-
end
332+
e ->
333+
e
331334
end
332335
end
333336
end

0 commit comments

Comments
 (0)