allow.py revision 219089
1219089Spjd#! /usr/bin/python2.6
2209962Smm#
3209962Smm# CDDL HEADER START
4209962Smm#
5209962Smm# The contents of this file are subject to the terms of the
6209962Smm# Common Development and Distribution License (the "License").
7209962Smm# You may not use this file except in compliance with the License.
8209962Smm#
9209962Smm# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10209962Smm# or http://www.opensolaris.org/os/licensing.
11209962Smm# See the License for the specific language governing permissions
12209962Smm# and limitations under the License.
13209962Smm#
14209962Smm# When distributing Covered Code, include this CDDL HEADER in each
15209962Smm# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16209962Smm# If applicable, add the following below this CDDL HEADER, with the
17209962Smm# fields enclosed by brackets "[]" replaced with your own identifying
18209962Smm# information: Portions Copyright [yyyy] [name of copyright owner]
19209962Smm#
20209962Smm# CDDL HEADER END
21209962Smm#
22219089Spjd# Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
23209962Smm#
24209962Smm
25209962Smm"""This module implements the "zfs allow" and "zfs unallow" subcommands.
26209962SmmThe only public interface is the zfs.allow.do_allow() function."""
27209962Smm
28209962Smmimport zfs.util
29209962Smmimport zfs.dataset
30209962Smmimport optparse
31209962Smmimport sys
32209962Smmimport pwd
33209962Smmimport grp
34209962Smmimport errno
35209962Smm
36209962Smm_ = zfs.util._
37209962Smm
38209962Smmclass FSPerms(object):
39209962Smm	"""This class represents all the permissions that are set on a
40209962Smm	particular filesystem (not including those inherited)."""
41209962Smm
42209962Smm	__slots__ = "create", "sets", "local", "descend", "ld"
43209962Smm	__repr__ = zfs.util.default_repr
44209962Smm
45209962Smm	def __init__(self, raw):
46209962Smm		"""Create a FSPerms based on the dict of raw permissions
47209962Smm		from zfs.ioctl.get_fsacl()."""
48209962Smm		# set of perms
49209962Smm		self.create = set()
50209962Smm
51209962Smm		# below are { "Ntype name": set(perms) }
52209962Smm		# where N is a number that we just use for sorting,
53209962Smm		# type is "user", "group", "everyone", or "" (for sets)
54209962Smm		# name is a user, group, or set name, or "" (for everyone)
55209962Smm		self.sets = dict()
56209962Smm		self.local = dict()
57209962Smm		self.descend = dict()
58209962Smm		self.ld = dict()
59209962Smm
60209962Smm		# see the comment in dsl_deleg.c for the definition of whokey
61209962Smm		for whokey in raw.keys():
62209962Smm			perms = raw[whokey].keys()
63209962Smm			whotypechr = whokey[0].lower()
64209962Smm			ws = whokey[3:]
65209962Smm			if whotypechr == "c":
66209962Smm				self.create.update(perms)
67209962Smm			elif whotypechr == "s":
68209962Smm				nwho = "1" + ws
69209962Smm				self.sets.setdefault(nwho, set()).update(perms)
70209962Smm			else:
71209962Smm				if whotypechr == "u":
72209962Smm					try:
73209962Smm						name = pwd.getpwuid(int(ws)).pw_name
74209962Smm					except KeyError:
75209962Smm						name = ws
76209962Smm					nwho = "1user " + name
77209962Smm				elif whotypechr == "g":
78209962Smm					try:
79209962Smm						name = grp.getgrgid(int(ws)).gr_name
80209962Smm					except KeyError:
81209962Smm						name = ws
82209962Smm					nwho = "2group " + name
83209962Smm				elif whotypechr == "e":
84209962Smm					nwho = "3everyone"
85209962Smm				else:
86209962Smm					raise ValueError(whotypechr)
87209962Smm
88209962Smm				if whokey[1] == "l":
89209962Smm					d = self.local
90209962Smm				elif whokey[1] == "d":
91209962Smm					d = self.descend
92209962Smm				else:
93209962Smm					raise ValueError(whokey[1])
94209962Smm
95209962Smm				d.setdefault(nwho, set()).update(perms)
96209962Smm
97209962Smm		# Find perms that are in both local and descend, and
98209962Smm		# move them to ld.
99209962Smm		for nwho in self.local:
100209962Smm			if nwho not in self.descend:
101209962Smm				continue
102209962Smm			# note: these are set operations
103209962Smm			self.ld[nwho] = self.local[nwho] & self.descend[nwho]
104209962Smm			self.local[nwho] -= self.ld[nwho]
105209962Smm			self.descend[nwho] -= self.ld[nwho]
106209962Smm
107209962Smm	@staticmethod
108209962Smm	def __ldstr(d, header):
109209962Smm		s = ""
110209962Smm		for (nwho, perms) in sorted(d.items()):
111209962Smm			# local and descend may have entries where perms
112209962Smm			# is an empty set, due to consolidating all
113209962Smm			# permissions into ld
114209962Smm			if perms:
115209962Smm				s += "\t%s %s\n" % \
116209962Smm				    (nwho[1:], ",".join(sorted(perms)))
117209962Smm		if s:
118209962Smm			s = header + s
119209962Smm		return s
120209962Smm
121209962Smm	def __str__(self):
122209962Smm		s = self.__ldstr(self.sets, _("Permission sets:\n"))
123209962Smm
124209962Smm		if self.create:
125209962Smm			s += _("Create time permissions:\n")
126209962Smm			s += "\t%s\n" % ",".join(sorted(self.create))
127209962Smm
128209962Smm		s += self.__ldstr(self.local, _("Local permissions:\n"))
129209962Smm		s += self.__ldstr(self.descend, _("Descendent permissions:\n"))
130209962Smm		s += self.__ldstr(self.ld, _("Local+Descendent permissions:\n"))
131209962Smm		return s.rstrip()
132209962Smm
133209962Smmdef args_to_perms(parser, options, who, perms):
134209962Smm	"""Return a dict of raw perms {"whostr" -> {"perm" -> None}}
135209962Smm	based on the command-line input."""
136209962Smm
137209962Smm	# perms is not set if we are doing a "zfs unallow <who> <fs>" to
138209962Smm	# remove all of someone's permissions
139209962Smm	if perms:
140209962Smm		setperms = dict(((p, None) for p in perms if p[0] == "@"))
141209962Smm		baseperms = dict(((canonicalized_perm(p), None)
142209962Smm		    for p in perms if p[0] != "@"))
143209962Smm	else:
144209962Smm		setperms = None
145209962Smm		baseperms = None
146209962Smm
147209962Smm	d = dict()
148209962Smm
149209962Smm	def storeperm(typechr, inheritchr, arg):
150209962Smm		assert typechr in "ugecs"
151209962Smm		assert inheritchr in "ld-"
152209962Smm
153209962Smm		def mkwhokey(t):
154209962Smm			return "%c%c$%s" % (t, inheritchr, arg)
155209962Smm
156209962Smm		if baseperms or not perms:
157209962Smm			d[mkwhokey(typechr)] = baseperms
158209962Smm		if setperms or not perms:
159209962Smm			d[mkwhokey(typechr.upper())] = setperms
160209962Smm
161209962Smm	def decodeid(w, toidfunc, fmt):
162209962Smm		try:
163209962Smm			return int(w)
164209962Smm		except ValueError:
165209962Smm			try:
166209962Smm				return toidfunc(w)[2]
167209962Smm			except KeyError:
168209962Smm				parser.error(fmt % w)
169209962Smm
170209962Smm	if options.set:
171209962Smm		storeperm("s", "-", who)
172209962Smm	elif options.create:
173209962Smm		storeperm("c", "-", "")
174209962Smm	else:
175209962Smm		for w in who:
176209962Smm			if options.user:
177209962Smm				id = decodeid(w, pwd.getpwnam,
178209962Smm				    _("invalid user %s"))
179209962Smm				typechr = "u"
180209962Smm			elif options.group:
181209962Smm				id = decodeid(w, grp.getgrnam,
182209962Smm				    _("invalid group %s"))
183209962Smm				typechr = "g"
184209962Smm			elif w == "everyone":
185209962Smm				id = ""
186209962Smm				typechr = "e"
187209962Smm			else:
188209962Smm				try:
189209962Smm					id = pwd.getpwnam(w)[2]
190209962Smm					typechr = "u"
191209962Smm				except KeyError:
192209962Smm					try:
193209962Smm						id = grp.getgrnam(w)[2]
194209962Smm						typechr = "g"
195209962Smm					except KeyError:
196209962Smm						parser.error(_("invalid user/group %s") % w)
197209962Smm			if options.local:
198209962Smm				storeperm(typechr, "l", id)
199209962Smm			if options.descend:
200209962Smm				storeperm(typechr, "d", id)
201209962Smm	return d
202209962Smm
203209962Smmperms_subcmd = dict(
204209962Smm    create=_("Must also have the 'mount' ability"),
205209962Smm    destroy=_("Must also have the 'mount' ability"),
206219089Spjd    snapshot="",
207219089Spjd    rollback="",
208209962Smm    clone=_("""Must also have the 'create' ability and 'mount'
209209962Smm\t\t\t\tability in the origin file system"""),
210209962Smm    promote=_("""Must also have the 'mount'
211209962Smm\t\t\t\tand 'promote' ability in the origin file system"""),
212209962Smm    rename=_("""Must also have the 'mount' and 'create'
213209962Smm\t\t\t\tability in the new parent"""),
214209962Smm    receive=_("Must also have the 'mount' and 'create' ability"),
215209962Smm    allow=_("Must also have the permission that is being\n\t\t\t\tallowed"),
216209962Smm    mount=_("Allows mount/umount of ZFS datasets"),
217209962Smm    share=_("Allows sharing file systems over NFS or SMB\n\t\t\t\tprotocols"),
218209962Smm    send="",
219219089Spjd    hold=_("Allows adding a user hold to a snapshot"),
220219089Spjd    release=_("Allows releasing a user hold which\n\t\t\t\tmight destroy the snapshot"),
221219089Spjd    diff=_("Allows lookup of paths within a dataset,\n\t\t\t\tgiven an object number. Ordinary users need this\n\t\t\t\tin order to use zfs diff"),
222209962Smm)
223209962Smm
224209962Smmperms_other = dict(
225209962Smm    userprop=_("Allows changing any user property"),
226209962Smm    userquota=_("Allows accessing any userquota@... property"),
227209962Smm    groupquota=_("Allows accessing any groupquota@... property"),
228209962Smm    userused=_("Allows reading any userused@... property"),
229209962Smm    groupused=_("Allows reading any groupused@... property"),
230209962Smm)
231209962Smm
232209962Smmdef hasset(ds, setname):
233209962Smm	"""Return True if the given setname (string) is defined for this
234209962Smm	ds (Dataset)."""
235209962Smm	# It would be nice to cache the result of get_fsacl().
236209962Smm	for raw in ds.get_fsacl().values():
237209962Smm		for whokey in raw.keys():
238209962Smm			if whokey[0].lower() == "s" and whokey[3:] == setname:
239209962Smm				return True
240209962Smm	return False
241209962Smm
242209962Smmdef canonicalized_perm(permname):
243209962Smm	"""Return the canonical name (string) for this permission (string).
244209962Smm	Raises ZFSError if it is not a valid permission."""
245209962Smm	if permname in perms_subcmd.keys() or permname in perms_other.keys():
246209962Smm		return permname
247209962Smm	try:
248209962Smm		return zfs.dataset.getpropobj(permname).name
249209962Smm	except KeyError:
250209962Smm		raise zfs.util.ZFSError(errno.EINVAL, permname,
251209962Smm		    _("invalid permission"))
252209962Smm
253209962Smmdef print_perms():
254209962Smm	"""Print the set of supported permissions."""
255209962Smm	print(_("\nThe following permissions are supported:\n"))
256209962Smm	fmt = "%-16s %-14s\t%s"
257209962Smm	print(fmt % (_("NAME"), _("TYPE"), _("NOTES")))
258209962Smm
259209962Smm	for (name, note) in sorted(perms_subcmd.iteritems()):
260209962Smm		print(fmt % (name, _("subcommand"), note))
261209962Smm
262209962Smm	for (name, note) in sorted(perms_other.iteritems()):
263209962Smm		print(fmt % (name, _("other"), note))
264209962Smm
265209962Smm	for (name, prop) in sorted(zfs.dataset.proptable.iteritems()):
266209962Smm		if prop.visible and prop.delegatable():
267209962Smm			print(fmt % (name, _("property"), ""))
268209962Smm
269209962Smmdef do_allow():
270219089Spjd	"""Implements the "zfs allow" and "zfs unallow" subcommands."""
271209962Smm	un = (sys.argv[1] == "unallow")
272209962Smm
273209962Smm	def usage(msg=None):
274209962Smm		parser.print_help()
275209962Smm		print_perms()
276209962Smm		if msg:
277209962Smm			print
278209962Smm			parser.exit("zfs: error: " + msg)
279209962Smm		else:
280209962Smm			parser.exit()
281209962Smm
282209962Smm	if un:
283209962Smm		u = _("""unallow [-rldug] <"everyone"|user|group>[,...]
284209962Smm	    [<perm|@setname>[,...]] <filesystem|volume>
285209962Smm	unallow [-rld] -e [<perm|@setname>[,...]] <filesystem|volume>
286209962Smm	unallow [-r] -c [<perm|@setname>[,...]] <filesystem|volume>
287209962Smm	unallow [-r] -s @setname [<perm|@setname>[,...]] <filesystem|volume>""")
288209962Smm		verb = _("remove")
289209962Smm		sstr = _("undefine permission set")
290209962Smm	else:
291209962Smm		u = _("""allow <filesystem|volume>
292209962Smm	allow [-ldug] <"everyone"|user|group>[,...] <perm|@setname>[,...]
293209962Smm	    <filesystem|volume>
294209962Smm	allow [-ld] -e <perm|@setname>[,...] <filesystem|volume>
295209962Smm	allow -c <perm|@setname>[,...] <filesystem|volume>
296209962Smm	allow -s @setname <perm|@setname>[,...] <filesystem|volume>""")
297209962Smm		verb = _("set")
298209962Smm		sstr = _("define permission set")
299209962Smm
300209962Smm	parser = optparse.OptionParser(usage=u, prog="zfs")
301209962Smm
302209962Smm	parser.add_option("-l", action="store_true", dest="local",
303209962Smm	    help=_("%s permission locally") % verb)
304209962Smm	parser.add_option("-d", action="store_true", dest="descend",
305209962Smm	    help=_("%s permission for descendents") % verb)
306209962Smm	parser.add_option("-u", action="store_true", dest="user",
307209962Smm	    help=_("%s permission for user") % verb)
308209962Smm	parser.add_option("-g", action="store_true", dest="group",
309209962Smm	    help=_("%s permission for group") % verb)
310209962Smm	parser.add_option("-e", action="store_true", dest="everyone",
311209962Smm	    help=_("%s permission for everyone") % verb)
312209962Smm	parser.add_option("-c", action="store_true", dest="create",
313209962Smm	    help=_("%s create time permissions") % verb)
314209962Smm	parser.add_option("-s", action="store_true", dest="set", help=sstr)
315209962Smm	if un:
316209962Smm		parser.add_option("-r", action="store_true", dest="recursive",
317209962Smm		    help=_("remove permissions recursively"))
318209962Smm
319209962Smm	if len(sys.argv) == 3 and not un:
320209962Smm		# just print the permissions on this fs
321209962Smm
322209962Smm		if sys.argv[2] == "-h":
323209962Smm			# hack to make "zfs allow -h" work
324209962Smm			usage()
325219089Spjd		ds = zfs.dataset.Dataset(sys.argv[2], snaps=False)
326209962Smm
327209962Smm		p = dict()
328209962Smm		for (fs, raw) in ds.get_fsacl().items():
329209962Smm			p[fs] = FSPerms(raw)
330209962Smm
331209962Smm		for fs in sorted(p.keys(), reverse=True):
332209962Smm			s = _("---- Permissions on %s ") % fs
333209962Smm			print(s + "-" * (70-len(s)))
334209962Smm			print(p[fs])
335209962Smm		return
336209962Smm
337209962Smm
338209962Smm	(options, args) = parser.parse_args(sys.argv[2:])
339209962Smm
340209962Smm	if sum((bool(options.everyone), bool(options.user),
341209962Smm	    bool(options.group))) > 1:
342209962Smm		parser.error(_("-u, -g, and -e are mutually exclusive"))
343209962Smm
344209962Smm	def mungeargs(expected_len):
345209962Smm		if un and len(args) == expected_len-1:
346209962Smm			return (None, args[expected_len-2])
347209962Smm		elif len(args) == expected_len:
348209962Smm			return (args[expected_len-2].split(","),
349209962Smm			    args[expected_len-1])
350209962Smm		else:
351209962Smm			usage(_("wrong number of parameters"))
352209962Smm
353209962Smm	if options.set:
354209962Smm		if options.local or options.descend or options.user or \
355209962Smm		    options.group or options.everyone or options.create:
356209962Smm			parser.error(_("invalid option combined with -s"))
357209962Smm		if args[0][0] != "@":
358209962Smm			parser.error(_("invalid set name: missing '@' prefix"))
359209962Smm
360209962Smm		(perms, fsname) = mungeargs(3)
361209962Smm		who = args[0]
362209962Smm	elif options.create:
363209962Smm		if options.local or options.descend or options.user or \
364209962Smm		    options.group or options.everyone or options.set:
365209962Smm			parser.error(_("invalid option combined with -c"))
366209962Smm
367209962Smm		(perms, fsname) = mungeargs(2)
368209962Smm		who = None
369209962Smm	elif options.everyone:
370209962Smm		if options.user or options.group or \
371209962Smm		    options.create or options.set:
372209962Smm			parser.error(_("invalid option combined with -e"))
373209962Smm
374209962Smm		(perms, fsname) = mungeargs(2)
375209962Smm		who = ["everyone"]
376209962Smm	else:
377209962Smm		(perms, fsname) = mungeargs(3)
378209962Smm		who = args[0].split(",")
379209962Smm
380209962Smm	if not options.local and not options.descend:
381209962Smm		options.local = True
382209962Smm		options.descend = True
383209962Smm
384209962Smm	d = args_to_perms(parser, options, who, perms)
385209962Smm
386209962Smm	ds = zfs.dataset.Dataset(fsname, snaps=False)
387209962Smm
388209962Smm	if not un and perms:
389209962Smm		for p in perms:
390209962Smm			if p[0] == "@" and not hasset(ds, p):
391209962Smm				parser.error(_("set %s is not defined") % p)
392209962Smm
393209962Smm	ds.set_fsacl(un, d)
394209962Smm	if un and options.recursive:
395209962Smm		for child in ds.descendents():
396209962Smm			child.set_fsacl(un, d)
397