globals.py 1.96 KB
Newer Older
Matt Traudt's avatar
Matt Traudt committed
1
import os
2
import logging
Matt Traudt's avatar
Matt Traudt committed
3

4
log = logging.getLogger(__name__)
Matt Traudt's avatar
Matt Traudt committed
5
6
7

G_PKG_DIR = os.path.abspath(os.path.dirname(__file__))

Matt Traudt's avatar
Matt Traudt committed
8
# Minimum and maximum number of bytes a scanner is allowed to request from a
9
10
# server. If these are changed, a WIRE_PROTO_VER bump is required, which also
# happens to require an sbws major version bump.
11
#
Matt Traudt's avatar
Matt Traudt committed
12
# Note for smart people and people who pull out Wireshark: Even if the scanner
13
14
15
16
17
18
# requests 1 byte, that request and the 1 byte response will each be carried
# over the Internet in 514 byte Tor cells. Theoretically we could bump the
# minimum request size up to ~498 bytes, but I see no reason why we should.
# Trying to hit the maximum cell size just makes sbws server send more, us read
# more, and it runs the risk of standards changing underneath us and sbws
# suddenly creating more than one cell.
19
MIN_REQ_BYTES = 1
20
MAX_REQ_BYTES = 1 * 1024 * 1024 * 1024  # 1 GiB
21
SOCKET_TIMEOUT = 60  # seconds
22

Matt Traudt's avatar
Matt Traudt committed
23
24

def is_initted(d):
25
    if not os.path.isdir(d):
26
        log.debug('%s not initialized: %s doesn\'t exist', d, d)
Matt Traudt's avatar
Matt Traudt committed
27
        return False
Matt Traudt's avatar
Matt Traudt committed
28
29
30
    conf_fnames = [os.path.join(d, 'config.ini'),
                   os.path.join(d, 'config.log.ini')]
    for fname in conf_fnames:
31
        if not os.path.isfile(fname):
32
            log.debug('%s not initialized: missing %s', d, fname)
Matt Traudt's avatar
Matt Traudt committed
33
            return False
34
    log.debug('%s seems initialized.', d)
Matt Traudt's avatar
Matt Traudt committed
35
    return True
36
37


38
def fail_hard(*a, **kw):
Matt Traudt's avatar
Matt Traudt committed
39
    ''' Log something ... and then exit as fast as possible '''
Matt Traudt's avatar
Matt Traudt committed
40
    log.critical(*a, **kw)
41
    exit(1)
Matt Traudt's avatar
Matt Traudt committed
42
43


44
45
46
47
48
49
50
51
52
53
54
55
56
def touch_file(fname, times=None):
    '''
    If **fname** exists, update its last access and modified times to now. If
    **fname** does not exist, create it. If **times** are specified, pass them
    to os.utime for use.

    :param str fname: Name of file to update or create
    :param tuple times: 2-tuple of floats for access time and modified time
        respectively
    '''
    log.debug('Touching %s', fname)
    with open(fname, 'a') as fd:
        os.utime(fd.fileno(), times=times)