Updated through tag hostap_2_5 from git://w1.fi/hostap.git
[mech_eap.git] / libeap / wpaspy / wpaspy.py
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)
25         try:
26             self.s.connect(self.dest)
27         except Exception, e:
28             self.s.close()
29             os.unlink(self.local)
30             raise
31         self.started = True
32
33     def __del__(self):
34         self.close()
35
36     def close(self):
37         if self.attached:
38             try:
39                 self.detach()
40             except Exception, e:
41                 # Need to ignore this allow the socket to be closed
42                 self.attached = False
43                 pass
44         if self.started:
45             self.s.close()
46             os.unlink(self.local)
47             self.started = False
48
49     def request(self, cmd, timeout=10):
50         self.s.send(cmd)
51         [r, w, e] = select.select([self.s], [], [], timeout)
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:
61             self.attached = True
62             return None
63         raise Exception("ATTACH failed")
64
65     def detach(self):
66         if not self.attached:
67             return None
68         while self.pending():
69             ev = self.recv()
70         res = self.request("DETACH")
71         if "FAIL" not in res:
72             self.attached = False
73             return None
74         raise Exception("DETACH failed")
75
76     def pending(self, timeout=0):
77         [r, w, e] = select.select([self.s], [], [], timeout)
78         if r:
79             return True
80         return False
81
82     def recv(self):
83         res = self.s.recv(4096)
84         return res