]>
Commit | Line | Data |
---|---|---|
09491b73 JM |
1 | #!/usr/bin/python |
2 | # | |
3 | # wpa_supplicant/hostapd control interface using Python | |
4 | # Copyright (c) 2013, Jouni Malinen <j@w1.fi> | |
5 | # | |
6 | # This software may be distributed under the terms of the BSD license. | |
7 | # See README for more details. | |
8 | ||
9 | import os | |
10 | import socket | |
11 | import select | |
12 | ||
13 | counter = 0 | |
14 | ||
15 | class Ctrl: | |
16 | def __init__(self, path): | |
17 | global counter | |
18 | self.started = False | |
19 | self.attached = False | |
20 | self.s = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) | |
21 | self.dest = path | |
22 | self.local = "/tmp/wpa_ctrl_" + str(os.getpid()) + '-' + str(counter) | |
23 | counter += 1 | |
24 | self.s.bind(self.local) | |
d52747c9 JM |
25 | try: |
26 | self.s.connect(self.dest) | |
27 | except Exception, e: | |
28 | self.s.close() | |
29 | os.unlink(self.local) | |
30 | raise | |
09491b73 JM |
31 | self.started = True |
32 | ||
33 | def __del__(self): | |
34 | self.close() | |
35 | ||
36 | def close(self): | |
37 | if self.attached: | |
b44db5f6 JM |
38 | try: |
39 | self.detach() | |
40 | except Exception, e: | |
41 | # Need to ignore this allow the socket to be closed | |
19318861 | 42 | self.attached = False |
b44db5f6 | 43 | pass |
09491b73 JM |
44 | if self.started: |
45 | self.s.close() | |
46 | os.unlink(self.local) | |
47 | self.started = False | |
48 | ||
c2149b08 | 49 | def request(self, cmd, timeout=10): |
09491b73 | 50 | self.s.send(cmd) |
c2149b08 | 51 | [r, w, e] = select.select([self.s], [], [], timeout) |
09491b73 JM |
52 | if r: |
53 | return self.s.recv(4096) | |
54 | raise Exception("Timeout on waiting response") | |
55 | ||
56 | def attach(self): | |
57 | if self.attached: | |
58 | return None | |
59 | res = self.request("ATTACH") | |
60 | if "OK" in res: | |
b44db5f6 | 61 | self.attached = True |
09491b73 JM |
62 | return None |
63 | raise Exception("ATTACH failed") | |
64 | ||
65 | def detach(self): | |
66 | if not self.attached: | |
67 | return None | |
19318861 JM |
68 | while self.pending(): |
69 | ev = self.recv() | |
09491b73 | 70 | res = self.request("DETACH") |
19318861 | 71 | if "FAIL" not in res: |
b44db5f6 | 72 | self.attached = False |
09491b73 JM |
73 | return None |
74 | raise Exception("DETACH failed") | |
75 | ||
606110e6 JM |
76 | def pending(self, timeout=0): |
77 | [r, w, e] = select.select([self.s], [], [], timeout) | |
09491b73 JM |
78 | if r: |
79 | return True | |
80 | return False | |
81 | ||
82 | def recv(self): | |
83 | res = self.s.recv(4096) | |
84 | return res |