Added the permissions command.
[pspp-builds.git] / src / permissions.c
1 /* PSPP - computes sample statistics.
2    Copyright (C) 2004 Free Software Foundation, Inc.
3    Author: John Darrington
4
5    This program is free software; you can redistribute it and/or
6    modify it under the terms of the GNU General Public License as
7    published by the Free Software Foundation; either version 2 of the
8    License, or (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful, but
11    WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software
17    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
18    02111-1307, USA. */
19
20 #include <config.h>
21 #include "error.h"
22 #include <stdlib.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <unistd.h>
26 #include <errno.h>
27
28 #include "command.h"
29 #include "error.h"
30 #include "lexer.h"
31 #include "misc.h"
32 #include "str.h"
33
34
35
36 enum PER {PER_RO, PER_RW};
37
38 int change_permissions(const char *filename, enum PER per);
39
40
41 /* Parses the PERMISSIONS command. */
42 int
43 cmd_permissions (void)
44 {
45   char  *fn = 0;
46
47   lex_match ('/');
48
49   if (lex_match_id ("FILE"))
50     lex_match ('=');
51
52   fn = strdup(ds_c_str(&tokstr));
53   lex_force_match(T_STRING);
54
55
56   lex_match ('/');
57   
58   if ( ! lex_match_id ("PERMISSIONS"))
59     goto error;
60
61   lex_match('=');
62
63   if ( lex_match_id("READONLY"))
64     {
65       if ( ! change_permissions(fn, PER_RO ) ) 
66         goto error;
67     }
68   else if ( lex_match_id("WRITEABLE"))
69     {
70       if ( ! change_permissions(fn, PER_RW ) ) 
71         goto error;
72     }
73   else
74     {
75       msg(ME, _("Expecting %s or %s."), "WRITEABLE", "READONLY");
76       goto error;
77     }
78
79   free(fn);
80
81   return CMD_SUCCESS;
82
83  error:
84
85   free(fn);
86
87   return CMD_FAILURE;
88 }
89
90
91
92 int
93 change_permissions(const char *filename, enum PER per)
94 {
95   struct stat buf;
96   mode_t mode;
97
98   if ( -1 == stat(filename, &buf) ) 
99     {
100       const int errnum = errno;
101       msg(ME,_("Cannot stat %s: %s"), filename, strerror(errnum));
102       return 0;
103     }
104
105   if ( per == PER_RW )
106     mode = buf.st_mode | S_IWUSR ;
107   else
108     mode = buf.st_mode & ~( S_IWOTH | S_IWUSR | S_IWGRP );
109
110   if ( -1 == chmod(filename, mode))
111
112     {
113       const int errnum = errno;
114       msg(ME,_("Cannot change mode of %s: %s"), filename, strerror(errnum));
115       return 0;
116     }
117
118   return 1;
119 }