Parcourir la source

retrieve current wifi config

Tobias Simetsreiter il y a 4 ans
Parent
commit
a6e2160b7a

+ 26 - 2
src/bootstrap_captive/api/__init__.py

@@ -5,11 +5,33 @@ def process_json(inp):
         return set_wifi(inp["set_wifi"])
     if "disable_portal" in inp:
         return disable_portal(inp["disable_portal"])
+    if "index_data" in inp:
+        return index_data(inp["index_data"])
     return {
         "ok":False,
         "api_err":"Request Handler not found"
     }
 
+def index_data(inp):
+    wifi_file = "/etc/wpa_supplicant/wpa_supplicant.conf"
+    ssid = "";
+    pw = ""
+    import re
+    with open(wifi_file) as fd:
+        wifi_config = fd.read()
+
+    reg = re.search(r'ssid="(.*)', wifi_config)
+    if reg:
+        ssid = reg.groups()[0].rstrip().rstrip('"')
+    reg = re.search(r'psk="(.*)', wifi_config)
+    if reg:
+        psk = reg.groups()[0].rstrip().rstrip('"')
+    return {
+        "ok":True,
+        "ssid": ssid,
+        "pw": psk,
+    }
+
 def disable_portal(inp):
     import subprocess
     p = subprocess.Popen(['bootstrap_captive','stop'],
@@ -22,12 +44,14 @@ def disable_portal(inp):
 
 def set_wifi(inp):
     import re
+    ssid = inp["ssid"].replace('"','\"')
+    pw = inp["pw"].replace('"','\"')
     wifi_file = "/etc/wpa_supplicant/wpa_supplicant.conf"
     with open(wifi_file) as fd:
         wifi_conf = fd.read()
 
-    wifi_conf = re.sub(r'ssid=".*','ssid="'+inp["ssid"]+'"', wifi_conf)
-    wifi_conf = re.sub(r'psk=".*','psk="'+inp["pw"]+'"', wifi_conf)
+    wifi_conf = re.sub(r'ssid=".*','ssid="'+ssid+'"', wifi_conf)
+    wifi_conf = re.sub(r'psk=".*','psk="'+pw+'"', wifi_conf)
 
     with open(wifi_file, "w") as fd:
         fd.write(wifi_conf)

+ 4 - 7
src/bootstrap_captive/server.py

@@ -18,16 +18,13 @@ class ThreadingHTTPServer(ThreadingMixIn, http.server.HTTPServer):
 
 class MyHttpRequestHandler(http.server.SimpleHTTPRequestHandler):
     portal_name = "portal.raspi.tsimnet.eu"
-    redirect_ip = "192.168.5.1"
-    portal_ip   = "192.168.5.2"
+    redirect_range = "192.168.5."
     def do_GET(self):
         self.directory = "http"
-        if self.headers["Host"].find(self.redirect_ip) >= 0:
-            self.redirect_portal()
-            return
         if self.headers["Host"].find(self.portal_name) < 0:
-            self.redirect_portal()
-            return
+            if self.client_address[0].find(self.redirect_range) >= 0:
+                self.redirect_portal()
+                return
         if self.server.server_port == 443:
             self.redirect_portal()
             return

+ 3 - 3
src/http/index.html

@@ -7,16 +7,16 @@
  <body>
    <div class="container-fluid">
      <h1>Welcome to Raspi Bootstrap Captive<h1>
-     <div class="progress">
+     <div class="progress" style="height: 30px;">
        <div id="progress_bar" class="progress-bar" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width: 100%"></div>
      </div>
      <div class="form-group">
        <input id="input_ssid" placeholder="SSID" class="form-control">
        <input id="input_pw" placeholder="Password" class="form-control">
-       <button onclick="portal.setWifi()" class="btn btn-primary">set</button>
+       <button id="wifi_button" onclick="portal.setWifi()" class="btn btn-primary btn-lg form-control">set</button>
      </div>
      <div class="form-group">
-       <button onclick="portal.disablePortal()" class="btn btn-warning">Disable Portal</button>
+       <button onclick="portal.disablePortal()" class="btn btn-warning btn-lg form-control">Disable Portal</button>
      </div>
      <pre id="error_box"></pre>
    </div>

+ 39 - 8
src/http/portal.js

@@ -23,7 +23,7 @@ portal = new function(){
         progress_bar.classList.add("progress-bar-animated")
         progress_bar.classList.remove("bg-success")
         progress_bar.classList.remove("bg-danger")
-        const response = await fetch(url, {
+        const req = fetch(url, {
             method: 'POST', // *GET, POST, PUT, DELETE, etc.
             mode: 'cors', // no-cors, *cors, same-origin
             cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
@@ -36,19 +36,50 @@ portal = new function(){
             referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
             body: JSON.stringify(data) // body data type must match "Content-Type" header
         });
-        progress_bar.classList.remove("progress-bar-striped")
-        progress_bar.classList.remove("progress-bar-animated")
-        resp = await response.json(); // parses JSON response into native JavaScript objects
-        if (resp["ok"]){
-            error_box.innerText = "";
-            progress_bar.classList.add("bg-success")
-        } else {
+        try {
+            const response = await req;
+            var resp = await response.json(); // parses JSON response into native JavaScript objects
+            if (resp["ok"]){
+                error_box.innerText = "";
+                progress_bar.classList.add("bg-success")
+            } else {
+                progress_bar.classList.add("bg-danger")
+                error_box.innerText = JSON.stringify(resp, null, 2);
+            }
+        } catch(err){
+            console.error(err);
             progress_bar.classList.add("bg-danger")
+            resp = {
+                "ok": false,
+                "err": err,
+            };
             error_box.innerText = JSON.stringify(resp, null, 2);
         }
+        progress_bar.classList.remove("progress-bar-striped")
+        progress_bar.classList.remove("progress-bar-animated")
         return resp;
     }
     function getId(id){
         return document.getElementById(id);
     }
+    function validate_input(){
+        if (
+            getId("input_ssid").value == "" ||
+            getId("input_pw").value == ""
+        ){
+            getId("wifi_button").disabled = true;
+        } else {
+            getId("wifi_button").disabled = false;
+        }
+    }
+    window.addEventListener("load",async ()=>{
+        getId("input_ssid").addEventListener("input",validate_input)
+        getId("input_pw").addEventListener("input",validate_input);
+        validate_input();
+        const resp = await postData("", {
+            "index_data":true
+        })
+        getId("input_ssid").value = resp["ssid"];
+        getId("input_pw").value   = resp["pw"];
+    });
 }();

+ 4 - 4
src/main.py

@@ -58,11 +58,10 @@ def com_start(args):
     COM="""
 set -x
 systemctl stop networking dhcpcd
-wpa_cli terminate
 sleep 3
-systemctl start networking hostapd.service
-sleep 3
-systemctl start dnsmasq.service bootstrap_captive@server.service dhcpcd
+systemctl start hostapd.service
+sleep 2
+systemctl start networking dnsmasq.service bootstrap_captive@server.service dhcpcd
 iptables -t nat -A PREROUTING -d 192.168.5.2 -j ACCEPT
 iptables -t nat -A PREROUTING -d 0/0 -p tcp --dport 80 -j DNAT --to-destination 192.168.5.1:80
 """
@@ -75,6 +74,7 @@ def com_stop(args):
 iptables -F -t nat
 systemctl stop bootstrap_captive@server.service hostapd.service dnsmasq.service
 ip addr flush wlan0
+sleep 3
 systemctl restart networking dhcpcd
 """
     run(COM, shell=True)