Debian Codegraph @

smb2-quota

raw
1 #!/usr/bin/python3
2 # coding: utf-8
3 #
4 # smb2-quota is a cmdline tool to display quota information for the
5 # Linux SMB client file system (CIFS)
6 #
7 # Copyright (C) Ronnie Sahlberg ([email protected]) 2019
8 # Copyright (C) Kenneth D'souza ([email protected]) 2019
9 #
10 # This program is free software; you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 2 of the License, or
13 # (at your option) any later version.
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program; if not, write to the Free Software
20 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21
22
23 import array
24 import fcntl
25 import os
26 import struct
27 import sys
28 import argparse
29
30 CIFS_QUERY_INFO = 0xc018cf07
31 BBOLD = '\033[1;30;47m' # Bold black text with white background.
32 ENDC = '\033[m' # Rest to defaults
33
34
35 def usage():
36 print("Usage: %s [-h] <options> <filename>" % sys.argv[0])
37 print("Try 'smb2-quota -h' for more information")
38 sys.exit()
39
40
41 class SID:
42 def __init__(self, buf):
43 self.sub_authority_count = buf[1]
44 self.buffer = buf[:8 + self.sub_authority_count * 4]
45 self.revision = self.buffer[0]
46 if self.revision != 1:
47 raise ValueError('SID Revision %d not supported' % self.revision)
48 self.identifier_authority = 0
49 for x in self.buffer[2:8]:
50 self.identifier_authority = self.identifier_authority * 256 + x
51 self.sub_authority = []
52 for i in range(self.sub_authority_count):
53 self.sub_authority.append(struct.unpack_from('<I', self.buffer, 8 + 4 * i)[0])
54
55 def __str__(self):
56 s = "S-%u-%u" % (self.revision, self.identifier_authority)
57 for x in self.sub_authority:
58 s += '-%u' % x
59 return s
60
61
62 def convert(num): # Convert bytes to closest human readable UNIT.
63 for unit in ['', 'kiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB']:
64 if abs(num) < 1024.0:
65 return "%3.1f %s" % (num, unit)
66 num /= 1024.0
67
68
69 def percent_used(used, limit, warn):
70 if limit == warn:
71 return "N/A"
72 else:
73 return str(round((used / limit) * 100.0))
74
75
76 def status(used, limit, warn):
77 if limit == warn:
78 return "Ok"
79 elif used > limit:
80 return "Above Limit"
81 elif warn < used < limit:
82 return "Warning"
83 else:
84 return "Ok"
85
86
87 class QuotaEntry:
88 def __init__(self, buf, flag):
89 sl = struct.unpack_from('<I', buf, 4)[0]
90 self.sid = SID(buf[40:40 + sl])
91 self.used = struct.unpack_from('<Q', buf, 16)[0]
92 self.thr = struct.unpack_from('<Q', buf, 24)[0]
93 self.lim = struct.unpack_from('<Q', buf, 32)[0]
94 self.a = (convert(self.used))
95 self.b = (convert(self.thr))
96 self.c = (convert(self.lim))
97 self.percent = (percent_used(float(self.used), float(self.lim), float(self.thr)))
98 self.status = (status(float(self.used), float(self.lim), float(self.thr)))
99 self.flag = flag
100
101 def __str__(self):
102 if self.flag == 0:
103 s = " %-11s | %-11s | %-13s | %-12s | %-12s | %s" % (self.a, self.c, self.b, self.percent, self.status, self.sid)
104 elif self.flag == 1:
105 s = "%s,%d,%d,%d" % (self.sid, self.used, self.lim, self.thr)
106 else:
107 s = 'SID:%s\n' % self.sid
108 s += 'Quota Used:%d\n' % self.used
109 if self.thr == 0xffffffffffffffff:
110 s += 'Quota Threshold Limit:NO_WARNING_THRESHOLD\n'
111 else:
112 s += 'Quota Threshold Limit:%d\n' % self.thr
113 if self.lim == 0xffffffffffffffff:
114 s += 'Quota Limit:NO_LIMIT\n'
115 else:
116 s += 'Quota Limit:%d\n' % self.lim
117 return s
118
119
120 class Quota:
121 def __init__(self, buf, flag):
122 self.quota = []
123 while buf:
124 qe = QuotaEntry(buf, flag)
125 self.quota.append(qe)
126 s = struct.unpack_from('<I', buf, 0)[0]
127 if s == 0:
128 break
129 buf = buf[s:]
130
131 def __str__(self):
132 s = ''
133 for q in self.quota:
134 s += '%s\n' % q
135 return s
136
137
138 def parser_check(path, flag):
139 titleused = "Amount Used"
140 titlelim = "Quota Limit"
141 titlethr = "Warning Level"
142 titlepercent = "Percent Used"
143 titlestatus = "Status"
144 titlesid = "SID"
145 buf = array.array('B', [0] * 16384)
146 struct.pack_into('<I', buf, 0, 4) # InfoType: Quota
147 struct.pack_into('<I', buf, 16, 16384) # InputBufferLength
148 struct.pack_into('<I', buf, 20, 16) # OutputBufferLength
149 struct.pack_into('b', buf, 24, 0) # return single
150 struct.pack_into('b', buf, 25, 1) # return single
151 try:
152 f = os.open(path, os.O_RDONLY)
153 fcntl.ioctl(f, CIFS_QUERY_INFO, buf, 1)
154 os.close(f)
155 if flag == 0:
156 print((BBOLD + " %-7s | %-7s | %-7s | %-7s | %-12s | %s " + ENDC) % (titleused, titlelim, titlethr, titlepercent, titlestatus, titlesid))
157 q = Quota(buf[24:24 + struct.unpack_from('<I', buf, 16)[0]], flag)
158 print(q)
159 except IOError as reason:
160 print("ioctl failed: %s" % reason)
161 except OSError as reason:
162 print("ioctl failed: %s" % reason)
163
164
165 def main():
166 if len(sys.argv) < 2:
167 usage()
168
169 parser = argparse.ArgumentParser(description="Please specify an action to perform.", prog="smb2-quota")
170 parser.add_argument("-t", "--tabular", action="store_true", help="print quota information in tabular format")
171 parser.add_argument("-c", "--csv", action="store_true", help="print quota information in csv format")
172 parser.add_argument("-l", "--list", action="store_true", help="print quota information in list format")
173 parser.add_argument("filename", metavar="<filename>", nargs=1, help='filename on a share')
174 args = parser.parse_args()
175
176 default = True if not (args.tabular or args.csv or args.list) else False
177 path = args.filename[0]
178
179 if args.tabular or default:
180 parser_check(path, 0)
181
182 if args.csv:
183 parser_check(path, 1)
184
185 if args.list:
186 parser_check(path, 2)
187
188
189 if __name__ == "__main__":
190 main()