Obey SessionMaxAge for session expiration
[mod_auth_gssapi.git] / contrib / sweeper.py
1 #!/usr/bin/env python
2 # Works with both python2 and python3; please preserve this property
3
4 # Copyright (C) 2016 mod_auth_gssapi contributors - See COPYING for (C) terms
5
6 # If one uses both sessions and unique ccache names, then the filesystem will
7 # become littered with ccache files unless the accessed application cleans
8 # them up itself.  This script will minimize ccache file proliferation by
9 # removing any ccaches that have expired from the filesystem, and serves as an
10 # example of how this cleaning can be performed.
11
12 import gssapi
13 import os
14 import re
15 import stat
16 import sys
17 import time
18
19 try:
20     from gssapi.raw import acquire_cred_from
21 except ImportError:
22     print("Your GSSAPI does not provide cred store extension; exiting!")
23     exit(1)
24
25 # process file as a ccache and indicate whether it is expired
26 def should_delete(fname, t):
27     try:
28         # skip directories and other non-files
29         st = os.stat(fname)
30         if not stat.S_ISREG(st.st_mode):
31             return False
32
33         # ignore files that are newer than 30 minutes
34         if t - st.st_mtime < 30 * 60:
35             return False
36
37         creds = acquire_cred_from({b"ccache": fname.encode("UTF-8")})
38     except FileNotFoundError:
39         # someone else did the work for us
40         return False
41     except Exception as e:
42         print("Not deleting %s due to error %s" % (fname, e))
43         return False
44
45     return creds.lifetime == 0
46
47 if __name__ == "__main__":
48     dirs = sys.argv[1:]
49     if len(dirs) < 1:
50         print("Usage: %s dir1 [dir2...]" % sys.argv[0])
51         exit(1)
52
53     print("System looks okay; running sweeper...")
54
55     t = time.time()
56
57     for basedir in dirs:
58         os.chdir(basedir)
59         print("Sweeping %s" % basedir)
60
61         for fname in os.listdir(basedir):
62             if should_delete(fname, t):
63                 os.unlink(fname)
64
65     print("Sweeper finished successfully!")
66     exit(0)