Загрузка данных
#!/usr/bin/env python3
import os
import sys
STATS_FILE = "/tmp/chown_stats.txt"
def load_statistics() -> tuple[int, int]:
if os.path.exists(STATS_FILE):
try:
with open(STATS_FILE, "r", encoding="utf-8") as f:
data = f.read().split()
if len(data) == 2:
return int(data[0]), int(data[1])
except (IOError, ValueError):
pass
return 0, 0
def save_statistics(success: int, failed: int) -> None:
try:
with open(STATS_FILE, "w", encoding="utf-8") as f:
f.write(f"{success} {failed}")
except IOError:
pass
def reset_statistics() -> None:
save_statistics(0, 0)
def is_valid_name(name: str) -> bool:
if not name:
return False
# Имя не должно начинаться с цифры или дефиса
if name[0].isdigit() or name[0] == '-':
return False
for char in name:
if not (char.isalnum() or char in ('_', '-')):
return False
return True
def validate_owner_group(token: str) -> bool:
if not token:
return False
colons = token.count(':')
dots = token.count('.')
if (colons > 0 and dots > 0) or colons > 1 or dots > 1:
return False
if colons == 1:
if token == ':':
return False
if token.endswith(':'): # Правило ТЗ для "root:"
return False
parts = token.split(':')
owner, group = parts[0], parts[1]
ok = True
if owner:
ok = ok and is_valid_name(owner)
if group:
ok = ok and is_valid_name(group)
return ok
if dots == 1:
if token.startswith('.') or token.endswith('.'):
return False
parts = token.split('.')
return is_valid_name(parts[0]) and is_valid_name(parts[1])
return is_valid_name(token)
def validate_chown(cmd_line: str) -> bool:
tokens = cmd_line.strip().split()
if not tokens or tokens[0] != "chown":
return False
parsing_flags = True
owner_group = None
file_count = 0
for t in tokens[1:]:
if parsing_flags and t.startswith('-'):
if t == '-' or t.startswith('--'):
return False
for char in t[1:]:
if char not in ('R', 'v', 'c', 'f'):
return False
else:
if owner_group is None:
owner_group = t
parsing_flags = False
else:
file_count += 1
if owner_group is None or file_count == 0:
return False
return validate_owner_group(owner_group)
def main() -> None:
for line in sys.stdin:
cleaned_line = line.strip()
if not cleaned_line:
continue
success_count, failed_count = load_statistics()
if cleaned_line == "getsuccess":
print(success_count)
elif cleaned_line == "getfailed":
print(failed_count)
elif cleaned_line == "getstats":
print(f"{success_count} {failed_count} {success_count + failed_count}")
elif cleaned_line == "resetstats":
reset_statistics()
print()
else:
if validate_chown(cleaned_line):
success_count += 1
save_statistics(success_count, failed_count)
print("True")
else:
failed_count += 1
save_statistics(success_count, failed_count)
print("False")
sys.stdout.flush()
if __name__ == "__main__":
main()