Imported Upstream version 1.4
[debian/gzip] / lib / mkdir.c
1 /* On some systems, mkdir ("foo/", 0700) fails because of the trailing
2    slash.  On those systems, this wrapper removes the trailing slash.
3
4    Copyright (C) 2001, 2003, 2006, 2008-2010 Free Software Foundation, Inc.
5
6    This program is free software: you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
18
19 /* written by Jim Meyering */
20
21 #include <config.h>
22
23 /* Specification.  */
24 #include <sys/stat.h>
25
26 #include <errno.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30
31 #include "dirname.h"
32
33 /* Disable the definition of mkdir to rpl_mkdir (from the <sys/stat.h>
34    substitute) in this file.  Otherwise, we'd get an endless recursion.  */
35 #undef mkdir
36
37 /* mingw's _mkdir() function has 1 argument, but we pass 2 arguments.
38    Additionally, it declares _mkdir (and depending on compile flags, an
39    alias mkdir), only in the nonstandard io.h.  */
40 #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
41 # define mkdir(name,mode) _mkdir (name)
42 # define maybe_unused _GL_UNUSED
43 #else
44 # define maybe_unused /* empty */
45 #endif
46
47 /* This function is required at least for NetBSD 1.5.2.  */
48
49 int
50 rpl_mkdir (char const *dir, mode_t mode maybe_unused)
51 {
52   int ret_val;
53   char *tmp_dir;
54   size_t len = strlen (dir);
55
56   if (len && dir[len - 1] == '/')
57     {
58       tmp_dir = strdup (dir);
59       if (!tmp_dir)
60         {
61           /* Rather than rely on strdup-posix, we set errno ourselves.  */
62           errno = ENOMEM;
63           return -1;
64         }
65       strip_trailing_slashes (tmp_dir);
66     }
67   else
68     {
69       tmp_dir = (char *) dir;
70     }
71 #if FUNC_MKDIR_DOT_BUG
72   /* Additionally, cygwin 1.5 mistakenly creates a directory "d/./".  */
73   {
74     char *last = last_component (tmp_dir);
75     if (*last == '.' && (last[1] == '\0'
76                          || (last[1] == '.' && last[2] == '\0')))
77       {
78         struct stat st;
79         if (stat (tmp_dir, &st) == 0)
80           errno = EEXIST;
81         return -1;
82       }
83   }
84 #endif /* FUNC_MKDIR_DOT_BUG */
85
86   ret_val = mkdir (tmp_dir, mode);
87
88   if (tmp_dir != dir)
89     free (tmp_dir);
90
91   return ret_val;
92 }