Sync from coreutils.
[gnulib.git] / lib / modechange.c
1 /* modechange.c -- file mode manipulation
2
3    Copyright (C) 1989, 1990, 1997, 1998, 1999, 2001, 2003, 2004, 2005
4    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 2, or (at your option)
9    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, write to the Free Software Foundation,
18    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
19
20 /* Written by David MacKenzie <djm@ai.mit.edu> */
21
22 /* The ASCII mode string is compiled into an array of `struct
23    modechange', which can then be applied to each file to be changed.
24    We do this instead of re-parsing the ASCII string for each file
25    because the compiled form requires less computation to use; when
26    changing the mode of many files, this probably results in a
27    performance gain.  */
28
29 #ifdef HAVE_CONFIG_H
30 # include <config.h>
31 #endif
32
33 #include "modechange.h"
34 #include <sys/stat.h>
35 #include "stat-macros.h"
36 #include "xalloc.h"
37 #include <stdlib.h>
38
39 /* The traditional octal values corresponding to each mode bit.  */
40 #define SUID 04000
41 #define SGID 02000
42 #define SVTX 01000
43 #define RUSR 00400
44 #define WUSR 00200
45 #define XUSR 00100
46 #define RGRP 00040
47 #define WGRP 00020
48 #define XGRP 00010
49 #define ROTH 00004
50 #define WOTH 00002
51 #define XOTH 00001
52 #define ALLM 07777 /* all octal mode bits */
53
54 /* Special operations flags.  */
55 enum
56   {
57     /* For the sentinel at the end of the mode changes array.  */
58     MODE_DONE,
59
60     /* The typical case.  */
61     MODE_ORDINARY_CHANGE,
62
63     /* In addition to the typical case, affect the execute bits if at
64        least one execute bit is set already, or if the file is a
65        directory.  */
66     MODE_X_IF_ANY_X,
67
68     /* Instead of the typical case, copy some existing permissions for
69        u, g, or o onto the other two.  Which of u, g, or o is copied
70        is determined by which bits are set in the `value' field.  */
71     MODE_COPY_EXISTING
72   };
73
74 /* Description of a mode change.  */
75 struct mode_change
76 {
77   char op;                      /* One of "=+-".  */
78   char flag;                    /* Special operations flag.  */
79   mode_t affected;              /* Set for u, g, o, or a.  */
80   mode_t value;                 /* Bits to add/remove.  */
81 };
82
83 /* Return a mode_change array with the specified `=ddd'-style
84    mode change operation, where NEW_MODE is `ddd'.  */
85
86 static struct mode_change *
87 make_node_op_equals (mode_t new_mode)
88 {
89   struct mode_change *p = xmalloc (2 * sizeof *p);
90   p->op = '=';
91   p->flag = MODE_ORDINARY_CHANGE;
92   p->affected = CHMOD_MODE_BITS;
93   p->value = new_mode;
94   p[1].flag = MODE_DONE;
95   return p;
96 }
97
98 /* Return a pointer to an array of file mode change operations created from
99    MODE_STRING, an ASCII string that contains either an octal number
100    specifying an absolute mode, or symbolic mode change operations with
101    the form:
102    [ugoa...][[+-=][rwxXstugo...]...][,...]
103
104    Return NULL if `mode_string' does not contain a valid
105    representation of file mode change operations.  */
106
107 struct mode_change *
108 mode_compile (char const *mode_string)
109 {
110   /* The array of mode-change directives to be returned.  */
111   struct mode_change *mc;
112   size_t used = 0;
113
114   if ('0' <= *mode_string && *mode_string < '8')
115     {
116       mode_t mode;
117       unsigned int octal_value = 0;
118
119       do
120         {
121           octal_value = 8 * octal_value + *mode_string++ - '0';
122           if (ALLM < octal_value)
123             return NULL;
124         }
125       while ('0' <= *mode_string && *mode_string < '8');
126
127       if (*mode_string)
128         return NULL;
129
130       /* Help the compiler optimize the usual case where mode_t uses
131          the traditional octal representation.  */
132       mode = ((S_ISUID == SUID && S_ISGID == SGID && S_ISVTX == SVTX
133                && S_IRUSR == RUSR && S_IWUSR == WUSR && S_IXUSR == XUSR
134                && S_IRGRP == RGRP && S_IWGRP == WGRP && S_IXGRP == XGRP
135                && S_IROTH == ROTH && S_IWOTH == WOTH && S_IXOTH == XOTH)
136               ? octal_value
137               : (mode_t) ((octal_value & SUID ? S_ISUID : 0)
138                           | (octal_value & SGID ? S_ISGID : 0)
139                           | (octal_value & SVTX ? S_ISVTX : 0)
140                           | (octal_value & RUSR ? S_IRUSR : 0)
141                           | (octal_value & WUSR ? S_IWUSR : 0)
142                           | (octal_value & XUSR ? S_IXUSR : 0)
143                           | (octal_value & RGRP ? S_IRGRP : 0)
144                           | (octal_value & WGRP ? S_IWGRP : 0)
145                           | (octal_value & XGRP ? S_IXGRP : 0)
146                           | (octal_value & ROTH ? S_IROTH : 0)
147                           | (octal_value & WOTH ? S_IWOTH : 0)
148                           | (octal_value & XOTH ? S_IXOTH : 0)));
149
150       return make_node_op_equals (mode);
151     }
152
153   /* Allocate enough space to hold the result.  */
154   {
155     size_t needed = 1;
156     char const *p;
157     for (p = mode_string; *p; p++)
158       needed += (*p == '=' || *p == '+' || *p == '-');
159     mc = xnmalloc (needed, sizeof *mc);
160   }
161
162   /* One loop iteration for each `[ugoa]*([-+=]([rwxXst]*|[ugo]))+'.  */
163   for (;; mode_string++)
164     {
165       /* Which bits in the mode are operated on.  */
166       mode_t affected = 0;
167
168       /* Turn on all the bits in `affected' for each group given.  */
169       for (;; mode_string++)
170         switch (*mode_string)
171           {
172           default:
173             goto invalid;
174           case 'u':
175             affected |= S_ISUID | S_IRWXU;
176             break;
177           case 'g':
178             affected |= S_ISGID | S_IRWXG;
179             break;
180           case 'o':
181             affected |= S_ISVTX | S_IRWXO;
182             break;
183           case 'a':
184             affected |= CHMOD_MODE_BITS;
185             break;
186           case '=': case '+': case '-':
187             goto no_more_affected;
188           }
189     no_more_affected:;
190
191       do
192         {
193           char op = *mode_string++;
194           mode_t value;
195           char flag = MODE_COPY_EXISTING;
196           struct mode_change *change;
197
198           switch (*mode_string++)
199             {
200             case 'u':
201               /* Set the affected bits to the value of the `u' bits
202                  on the same file.  */
203               value = S_IRWXU;
204               break;
205             case 'g':
206               /* Set the affected bits to the value of the `g' bits
207                  on the same file.  */
208               value = S_IRWXG;
209               break;
210             case 'o':
211               /* Set the affected bits to the value of the `o' bits
212                  on the same file.  */
213               value = S_IRWXO;
214               break;
215
216             default:
217               value = 0;
218               flag = MODE_ORDINARY_CHANGE;
219
220               for (mode_string--;; mode_string++)
221                 switch (*mode_string)
222                   {
223                   case 'r':
224                     value |= S_IRUSR | S_IRGRP | S_IROTH;
225                     break;
226                   case 'w':
227                     value |= S_IWUSR | S_IWGRP | S_IWOTH;
228                     break;
229                   case 'x':
230                     value |= S_IXUSR | S_IXGRP | S_IXOTH;
231                     break;
232                   case 'X':
233                     flag = MODE_X_IF_ANY_X;
234                     break;
235                   case 's':
236                     /* Set the setuid/gid bits if `u' or `g' is selected.  */
237                     value |= S_ISUID | S_ISGID;
238                     break;
239                   case 't':
240                     /* Set the "save text image" bit if `o' is selected.  */
241                     value |= S_ISVTX;
242                     break;
243                   default:
244                     goto no_more_values;
245                   }
246             no_more_values:;
247             }
248
249           change = &mc[used++];
250           change->op = op;
251           change->flag = flag;
252           change->affected = affected;
253           change->value = value;
254         }
255       while (*mode_string == '=' || *mode_string == '+'
256              || *mode_string == '-');
257
258       if (*mode_string != ',')
259         break;
260     }
261
262   if (*mode_string == 0)
263     {
264       mc[used].flag = MODE_DONE;
265       return mc;
266     }
267
268 invalid:
269   free (mc);
270   return NULL;
271 }
272
273 /* Return a file mode change operation that sets permissions to match those
274    of REF_FILE.  Return NULL (setting errno) if REF_FILE can't be accessed.  */
275
276 struct mode_change *
277 mode_create_from_ref (const char *ref_file)
278 {
279   struct stat ref_stats;
280
281   if (stat (ref_file, &ref_stats) != 0)
282     return NULL;
283   return make_node_op_equals (ref_stats.st_mode);
284 }
285
286 /* Return file mode OLDMODE, adjusted as indicated by the list of change
287    operations CHANGES, which are interpreted assuming the umask is
288    UMASK_VALUE.  If OLDMODE is a directory, the type `X'
289    change affects it even if no execute bits were set in OLDMODE.
290    The returned value has the S_IFMT bits cleared.  */
291
292 mode_t
293 mode_adjust (mode_t oldmode, struct mode_change const *changes,
294              mode_t umask_value)
295 {
296   /* The adjusted mode.  */
297   mode_t newmode = oldmode & CHMOD_MODE_BITS;
298
299   for (; changes->flag != MODE_DONE; changes++)
300     {
301       mode_t affected = changes->affected;
302       mode_t value = changes->value;
303
304       switch (changes->flag)
305         {
306         case MODE_ORDINARY_CHANGE:
307           break;
308
309         case MODE_COPY_EXISTING:
310           /* Isolate in `value' the bits in `newmode' to copy.  */
311           value &= newmode;
312
313           /* Copy the isolated bits to the other two parts.  */
314           value |= ((value & (S_IRUSR | S_IRGRP | S_IROTH)
315                      ? S_IRUSR | S_IRGRP | S_IROTH : 0)
316                     | (value & (S_IWUSR | S_IWGRP | S_IWOTH)
317                        ? S_IWUSR | S_IWGRP | S_IWOTH : 0)
318                     | (value & (S_IXUSR | S_IXGRP | S_IXOTH)
319                        ? S_IXUSR | S_IXGRP | S_IXOTH : 0));
320           break;
321
322         case MODE_X_IF_ANY_X:
323           /* Affect the execute bits if execute bits are already set
324              or if the file is a directory.  */
325           if ((newmode & (S_IXUSR | S_IXGRP | S_IXOTH)) || S_ISDIR (oldmode))
326             value |= S_IXUSR | S_IXGRP | S_IXOTH;
327           break;
328         }
329
330       /* If WHO was specified, limit the change to the affected bits.
331          Otherwise, apply the umask.  */
332       value &= (affected ? affected : ~umask_value);
333
334       switch (changes->op)
335         {
336         case '=':
337           /* If WHO was specified, preserve the previous values of
338              bits that are not affected by this change operation.
339              Otherwise, clear all the bits.  */
340           newmode = (affected ? newmode & ~affected : 0);
341           /* Fall through.  */
342         case '+':
343           newmode |= value;
344           break;
345
346         case '-':
347           newmode &= ~value;
348           break;
349         }
350     }
351
352   return newmode;
353 }