summaryrefslogtreecommitdiffstats
path: root/lass/5pkgs/autowifi/autowifi.py
blob: fa3d007e76ed7389355fa130a09c7346799805ca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import subprocess
import time
import urllib.request
import logging
import argparse
import socket
import struct
import signal
import os

wifiDB = ''
logger = logging.getLogger()
got_signal = False


def signal_handler(signum, frame):
    global got_signal
    got_signal = True


def get_default_gateway() -> str:
    """Read the default gateway directly from /proc."""
    with open("/proc/net/route") as fh:
        for line in fh:
            fields = line.strip().split()
            if fields[1] != '00000000' or not int(fields[3], 16) & 2:
                continue

            return socket.inet_ntoa(struct.pack("<L", int(fields[2], 16)))


def connect(ssid, psk=None):
    subprocess.run(
        ["nmcli", "connection", "delete", "autowifi"],
        stdout=subprocess.PIPE,
    )
    logging.info('connecting to %s', ssid)
    if psk is None:
        subprocess.run(
            [
                "nmcli",
                "device",
                "wifi",
                "connect",
                ssid,
                "name",
                "autowifi",
            ],
            stdout=subprocess.PIPE,
        )
    else:
        subprocess.run(
            [
                "nmcli",
                "device",
                "wifi",
                "connect",
                ssid,
                "name",
                "autowifi",
                "password",
                psk,
            ],
            stdout=subprocess.PIPE,
        )
    time.sleep(5)


def scan():
    logging.debug('scanning wifis')
    wifis_raw = subprocess.check_output([
        "nmcli",
        "-t",
        "device",
        "wifi",
        "list",
        "--rescan",
        "yes",
    ])
    wifis_list = wifis_raw.split(b'\n')
    logging.debug('scanning wifis finished')
    wifis = []
    for line in wifis_list:
        logging.debug(line)
        ls = line.split(b':')
        if len(ls) == 8:
            wifis.append({
                "ssid": ls[1],
                "signal": int(ls[5]),
                "crypto": ls[7]
            })
    return wifis


def get_known_wifis():
    wifis_lines = []
    with open(wifiDB) as f:
        wifis_lines = f.read().splitlines()
    wifis = []
    for line in wifis_lines:
        ls = line.split('/')
        wifis.append({"ssid": ls[0].encode(), "psk": ls[1].encode()})
    return wifis


def check_network():
    logging.debug('checking network')

    global got_signal
    if got_signal:
        logging.info('got disconnect signal')
        got_signal = False
        return False
    else:
        gateway = get_default_gateway()
        if gateway:
            response = subprocess.run(
                [
                    'ping',
                    '-q',
                    '-c',
                    '1',
                    gateway,
                ],
                stdout=subprocess.PIPE,
            )
            if response.returncode == 0:
                logging.debug('host %s is up', gateway)
                return True
            else:
                logging.debug('host %s is down', gateway)
                return False
        else:
            logging.debug('no gateway')
            return False


def check_internet():
    logging.debug('checking internet')

    try:
        with open('./dummy_internet') as f:
            dummy_content = f.read()
            if dummy_content == 'xxx\n':
                return True
        beacon = urllib.request.urlopen('http://krebsco.de/secret')
    except Exception as e:  # noqa
        logging.debug(e)
        logging.info('no internet exc')
        return False
    if beacon.read() == b'1337\n':
        return True
    logging.info('no internet oh')
    return False


def is_wifi_open(wifi):
    if wifi['crypto'] == b'':
        return True
    else:
        return False


def is_wifi_seen(wifi, seen_wifis):
    for seen_wifi in seen_wifis:
        if seen_wifi["ssid"] == wifi["ssid"]:
            return True
    return False


def main():
    parser = argparse.ArgumentParser()

    parser.add_argument(
        '-c', '--config',
        dest='config',
        help='wifi config file to use',
        default='/etc/wifis',
    )

    parser.add_argument(
        '-l', '--loglevel',
        dest='loglevel',
        help='loglevel to use',
        default=logging.INFO,
    )

    parser.add_argument(
        '-p', '--pidfile',
        dest='pidfile',
        help='file to write the pid to',
        default=None,
    )

    args = parser.parse_args()

    global wifiDB
    wifiDB = args.config
    logger.setLevel(args.loglevel)

    signal.signal(signal.SIGUSR1, signal_handler)

    if args.pidfile:
        with open(args.pidfile, 'w+') as f:
            f.write(str(os.getpid()))

    while True:
        if not check_network():
            wifis = scan()
            known_wifis = get_known_wifis()
            known_seen_wifis = [
                wifi for wifi in known_wifis if is_wifi_seen(wifi, wifis)
            ]
            for wifi in known_seen_wifis:
                connect(wifi['ssid'], wifi['psk'])
                if check_network():
                    break
            open_wifis = filter(is_wifi_open, wifis)
            for wifi in open_wifis:
                connect(wifi['ssid'])

                if check_network():
                    break
        time.sleep(10)


if __name__ == '__main__':
    main()