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

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

7
RESULT_VERSION = 2
8
9
10
11
12
13
14
WIRE_VERSION = 1
SPEC_VERSION = '1.1.0'

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

SOCKET_TIMEOUT = 60  # seconds

15
16
17
18
19
20
21
22
23
24
25
26
# This is a dictionary of torrc options we always want to set when launching
# Tor and that do not depend on any runtime configuration
TORRC_STARTING_POINT = {
    # We will find out via the ControlPort and not setting something static
    # means a lower chance of conflict
    'SocksPort': 'auto',
    # Easier than password authentication
    'CookieAuthentication': '1',
    # To avoid path bias warnings
    'UseEntryGuards': '0',
}

Matt Traudt's avatar
Matt Traudt committed
27
28

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


42
def fail_hard(*a, **kw):
Matt Traudt's avatar
Matt Traudt committed
43
    ''' Log something ... and then exit as fast as possible '''
Matt Traudt's avatar
Matt Traudt committed
44
    log.critical(*a, **kw)
45
    exit(1)
Matt Traudt's avatar
Matt Traudt committed
46
47


48
49
50
51
52
53
54
55
56
57
58
59
60
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)
61
62
63
64
65
66
67
68
69
70
71
72
73
74


def resolve(hostname, ipv4_only=False, ipv6_only=False):
    assert not (ipv4_only and ipv6_only)
    ret = set()
    for result in socket.getaddrinfo(hostname, 0):
        fam, _, _, _, addr = result
        if fam == socket.AddressFamily.AF_INET6 and not ipv4_only:
            ret.add(addr[0])
        elif fam == socket.AddressFamily.AF_INET and not ipv6_only:
            ret.add(addr[0])
        else:
            assert None, 'Unknown address family {}'.format(fam)
    return list(ret)