Merge 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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 #if 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       /* Help the compiler optimize the usual case where mode_t uses
128          the traditional octal representation.  */
129       mode = ((S_ISUID == SUID && S_ISGID == SGID && S_ISVTX == SVTX
130                && S_IRUSR == RUSR && S_IWUSR == WUSR && S_IXUSR == XUSR
131                && S_IRGRP == RGRP && S_IWGRP == WGRP && S_IXGRP == XGRP
132                && S_IROTH == ROTH && S_IWOTH == WOTH && S_IXOTH == XOTH)
133               ? octal_value
134               : (mode_t) ((octal_value & SUID ? S_ISUID : 0)
135                           | (octal_value & SGID ? S_ISGID : 0)
136                           | (octal_value & SVTX ? S_ISVTX : 0)
137                           | (octal_value & RUSR ? S_IRUSR : 0)
138                           | (octal_value & WUSR ? S_IWUSR : 0)
139                           | (octal_value & XUSR ? S_IXUSR : 0)
140                           | (octal_value & RGRP ? S_IRGRP : 0)
141                           | (octal_value & WGRP ? S_IWGRP : 0)
142                           | (octal_value & XGRP ? S_IXGRP : 0)
143                           | (octal_value & ROTH ? S_IROTH : 0)
144                           | (octal_value & WOTH ? S_IWOTH : 0)
145                           | (octal_value & XOTH ? S_IXOTH : 0)));
146
147       return make_node_op_equals (mode);
148     }
149
150   /* Allocate enough space to hold the result.  */
151   {
152     size_t needed = 1;
153     char const *p;
154     for (p = mode_string; *p; p++)
155       needed += (*p == '=' || *p == '+' || *p == '-');
156     mc = xnmalloc (needed, sizeof *mc);
157   }
158
159   /* One loop iteration for each `[ugoa]*([-+=]([rwxXst]*|[ugo]))+'.  */
160   for (;; mode_string++)
161     {
162       /* Which bits in the mode are operated on.  */
163       mode_t affected = 0;
164
165       /* Turn on all the bits in `affected' for each group given.  */
166       for (;; mode_string++)
167         switch (*mode_string)
168           {
169           default:
170             goto invalid;
171           case 'u':
172             affected |= S_ISUID | S_IRWXU;
173             break;
174           case 'g':
175             affected |= S_ISGID | S_IRWXG;
176             break;
177           case 'o':
178             affected |= S_ISVTX | S_IRWXO;
179             break;
180           case 'a':
181             affected |= CHMOD_MODE_BITS;
182             break;
183           case '=': case '+': case '-':
184             goto no_more_affected;
185           }
186     no_more_affected:;
187
188       do
189         {
190           char op = *mode_string++;
191           mode_t value;
192           char flag = MODE_COPY_EXISTING;
193           struct mode_change *change;
194
195           switch (*mode_string++)
196             {
197             case 'u':
198               /* Set the affected bits to the value of the `u' bits
199                  on the same file.  */
200               value = S_IRWXU;
201               break;
202             case 'g':
203               /* Set the affected bits to the value of the `g' bits
204                  on the same file.  */
205               value = S_IRWXG;
206               break;
207             case 'o':
208               /* Set the affected bits to the value of the `o' bits
209                  on the same file.  */
210               value = S_IRWXO;
211               break;
212
213             default:
214               value = 0;
215               flag = MODE_ORDINARY_CHANGE;
216
217               for (mode_string--;; mode_string++)
218                 switch (*mode_string)
219                   {
220                   case 'r':
221                     value |= S_IRUSR | S_IRGRP | S_IROTH;
222                     break;
223                   case 'w':
224                     value |= S_IWUSR | S_IWGRP | S_IWOTH;
225                     break;
226                   case 'x':
227                     value |= S_IXUSR | S_IXGRP | S_IXOTH;
228                     break;
229                   case 'X':
230                     flag = MODE_X_IF_ANY_X;
231                     break;
232                   case 's':
233                     /* Set the setuid/gid bits if `u' or `g' is selected.  */
234                     value |= S_ISUID | S_ISGID;
235                     break;
236                   case 't':
237                     /* Set the "save text image" bit if `o' is selected.  */
238                     value |= S_ISVTX;
239                     break;
240                   default:
241                     goto no_more_values;
242                   }
243             no_more_values:;
244             }
245
246           change = &mc[used++];
247           change->op = op;
248           change->flag = flag;
249           change->affected = affected;
250           change->value = value;
251         }
252       while (*mode_string == '=' || *mode_string == '+'
253              || *mode_string == '-');
254
255       if (*mode_string != ',')
256         break;
257     }
258
259   if (*mode_string == 0)
260     {
261       mc[used].flag = MODE_DONE;
262       return mc;
263     }
264
265 invalid:
266   free (mc);
267   return NULL;
268 }
269
270 /* Return a file mode change operation that sets permissions to match those
271    of REF_FILE.  Return NULL (setting errno) if REF_FILE can't be accessed.  */
272
273 struct mode_change *
274 mode_create_from_ref (const char *ref_file)
275 {
276   struct stat ref_stats;
277
278   if (stat (ref_file, &ref_stats) != 0)
279     return NULL;
280   return make_node_op_equals (ref_stats.st_mode);
281 }
282
283 /* Return file mode OLDMODE, adjusted as indicated by the list of change
284    operations CHANGES, which are interpreted assuming the umask is
285    UMASK_VALUE.  If OLDMODE is a directory, the type `X'
286    change affects it even if no execute bits were set in OLDMODE.
287    The returned value has the S_IFMT bits cleared.  */
288
289 mode_t
290 mode_adjust (mode_t oldmode, struct mode_change const *changes,
291              mode_t umask_value)
292 {
293   /* The adjusted mode.  */
294   mode_t newmode = oldmode & CHMOD_MODE_BITS;
295
296   for (; changes->flag != MODE_DONE; changes++)
297     {
298       mode_t affected = changes->affected;
299       mode_t value = changes->value;
300
301       switch (changes->flag)
302         {
303         case MODE_ORDINARY_CHANGE:
304           break;
305
306         case MODE_COPY_EXISTING:
307           /* Isolate in `value' the bits in `newmode' to copy.  */
308           value &= newmode;
309
310           /* Copy the isolated bits to the other two parts.  */
311           value |= ((value & (S_IRUSR | S_IRGRP | S_IROTH)
312                      ? S_IRUSR | S_IRGRP | S_IROTH : 0)
313                     | (value & (S_IWUSR | S_IWGRP | S_IWOTH)
314                        ? S_IWUSR | S_IWGRP | S_IWOTH : 0)
315                     | (value & (S_IXUSR | S_IXGRP | S_IXOTH)
316                        ? S_IXUSR | S_IXGRP | S_IXOTH : 0));
317           break;
318
319         case MODE_X_IF_ANY_X:
320           /* Affect the execute bits if execute bits are already set
321              or if the file is a directory.  */
322           if ((newmode & (S_IXUSR | S_IXGRP | S_IXOTH)) || S_ISDIR (oldmode))
323             value |= S_IXUSR | S_IXGRP | S_IXOTH;
324           break;
325         }
326
327       /* If WHO was specified, limit the change to the affected bits.
328          Otherwise, apply the umask.  */
329       value &= (affected ? affected : ~umask_value);
330
331       switch (changes->op)
332         {
333         case '=':
334           /* If WHO was specified, preserve the previous values of
335              bits that are not affected by this change operation.
336              Otherwise, clear all the bits.  */
337           newmode = (affected ? newmode & ~affected : 0);
338           /* Fall through.  */
339         case '+':
340           newmode |= value;
341           break;
342
343         case '-':
344           newmode &= ~value;
345           break;
346         }
347     }
348
349   return newmode;
350 }