fix wifi for raspios (#1207)

* Wip: Fix most of the wifi and 80% of initialization.sh

* fix wifi

* reorganize code

Co-authored-by: J M <mogulslayer@gmail.com>
This commit is contained in:
Aiden McClelland
2022-02-15 10:27:25 -07:00
committed by GitHub
parent fd37bbf712
commit 1837e719b6
3 changed files with 71 additions and 55 deletions

View File

@@ -105,7 +105,7 @@ pub async fn connect(#[context] ctx: RpcContext, #[arg] ssid: String) -> Result<
let current = wpa_supplicant.get_current_network().await?; let current = wpa_supplicant.get_current_network().await?;
drop(wpa_supplicant); drop(wpa_supplicant);
let mut wpa_supplicant = wifi_manager.write().await; let mut wpa_supplicant = wifi_manager.write().await;
let connected = wpa_supplicant.select_network(&mut db, &ssid).await?; let connected = wpa_supplicant.select_network(&mut db, ssid).await?;
if connected { if connected {
tracing::info!("Successfully connected to WiFi: '{}'", ssid.0); tracing::info!("Successfully connected to WiFi: '{}'", ssid.0);
} else { } else {
@@ -205,13 +205,13 @@ fn display_wifi_info(info: WiFiInfo, matches: &ArgMatches<'_>) {
&info &info
.connected .connected
.as_ref() .as_ref()
.map_or("[N/A]".to_owned(), |c| format!("{}", c.0)), .map_or("[N/A]".to_owned(), |c| c.0.clone()),
&info &info
.connected .connected
.as_ref() .as_ref()
.and_then(|x| info.ssids.get(x)) .and_then(|x| info.ssids.get(x))
.map_or("[N/A]".to_owned(), |ss| format!("{}", ss.0)), .map_or("[N/A]".to_owned(), |ss| format!("{}", ss.0)),
&format!("{}", info.country.alpha2()), &info.country.alpha2(),
&format!("{}", info.ethernet) &format!("{}", info.ethernet)
]); ]);
table_global.print_tty(false); table_global.print_tty(false);
@@ -244,7 +244,7 @@ fn display_wifi_info(info: WiFiInfo, matches: &ArgMatches<'_>) {
table_global.add_row(row![ table_global.add_row(row![
&table_info.ssid.0, &table_info.ssid.0,
&format!("{}", table_info.strength.0), &format!("{}", table_info.strength.0),
&format!("{}", table_info.security.join(" ")) &table_info.security.join(" ")
]); ]);
} }
@@ -268,7 +268,7 @@ fn display_wifi_list(info: Vec<WifiListOut>, matches: &ArgMatches<'_>) {
table_global.add_row(row![ table_global.add_row(row![
&table_info.ssid.0, &table_info.ssid.0,
&format!("{}", table_info.strength.0), &format!("{}", table_info.strength.0),
&format!("{}", table_info.security.join(" ")) &table_info.security.join(" ")
]); ]);
} }
@@ -321,7 +321,7 @@ pub async fn get(
let current = current_res?; let current = current_res?;
Ok(WiFiInfo { Ok(WiFiInfo {
ssids, ssids,
connected: current.map(|x| x), connected: current,
country: country_res?, country: country_res?,
ethernet: ethernet_res?, ethernet: ethernet_res?,
available_wifi, available_wifi,
@@ -394,7 +394,17 @@ pub struct Ssid(String);
/// So a signal strength is a number between 0-100, I want the null option to be 0 since there is no signal /// So a signal strength is a number between 0-100, I want the null option to be 0 since there is no signal
#[derive( #[derive(
Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize, Clone,
Copy,
Debug,
Default,
PartialEq,
Eq,
PartialOrd,
Ord,
Hash,
serde::Serialize,
serde::Deserialize,
)] )]
pub struct SignalStrength(u8); pub struct SignalStrength(u8);
@@ -411,11 +421,6 @@ impl SignalStrength {
} }
} }
impl Default for SignalStrength {
fn default() -> Self {
Self(0)
}
}
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct Psk(String); pub struct Psk(String);
impl WpaCli { impl WpaCli {
@@ -492,26 +497,24 @@ impl WpaCli {
lazy_static! { lazy_static! {
static ref RE: Regex = Regex::new("country (\\w+):").unwrap(); static ref RE: Regex = Regex::new("country (\\w+):").unwrap();
} }
let first_country = r let first_country = r.lines().find(|s| s.contains("country")).ok_or_else(|| {
.lines() Error::new(
.filter(|s| s.contains("country")) color_eyre::eyre::eyre!("Could not find a country config lines"),
.next() ErrorKind::Wifi,
.ok_or_else(|| { )
Error::new( })?;
color_eyre::eyre::eyre!("Could not find a country config lines"),
ErrorKind::Wifi,
)
})?;
let country = &RE.captures(first_country).ok_or_else(|| { let country = &RE.captures(first_country).ok_or_else(|| {
Error::new( Error::new(
color_eyre::eyre::eyre!("Could not find a country config with regex"), color_eyre::eyre::eyre!("Could not find a country config with regex"),
ErrorKind::Wifi, ErrorKind::Wifi,
) )
})?[1]; })?[1];
Ok(CountryCode::for_alpha2(country).or(Err(Error::new( Ok(CountryCode::for_alpha2(country).map_err(|_| {
color_eyre::eyre::eyre!("Invalid Country Code: {}", country), Error::new(
ErrorKind::Wifi, color_eyre::eyre::eyre!("Invalid Country Code: {}", country),
)))?) ErrorKind::Wifi,
)
})?)
} }
pub async fn remove_network_low(&mut self, id: NetworkId) -> Result<(), Error> { pub async fn remove_network_low(&mut self, id: NetworkId) -> Result<(), Error> {
let _ = Command::new("nmcli") let _ = Command::new("nmcli")
@@ -533,11 +536,14 @@ impl WpaCli {
Ok(String::from_utf8(r)? Ok(String::from_utf8(r)?
.lines() .lines()
.filter_map(|l| { .filter_map(|l| {
let mut cs = l.split(":"); let mut cs = l.split(':');
let name = Ssid(cs.next()?.to_owned()); let name = Ssid(cs.next()?.to_owned());
let uuid = NetworkId(cs.next()?.to_owned()); let uuid = NetworkId(cs.next()?.to_owned());
let _connection_type = cs.next()?; let connection_type = cs.next()?;
let _device = cs.next()?; let device = cs.next()?;
if !device.contains("wlan0") || !connection_type.contains("wireless") {
return None;
}
Some((name, uuid)) Some((name, uuid))
}) })
.collect::<BTreeMap<Ssid, NetworkId>>()) .collect::<BTreeMap<Ssid, NetworkId>>())
@@ -556,11 +562,11 @@ impl WpaCli {
Ok(String::from_utf8(r)? Ok(String::from_utf8(r)?
.lines() .lines()
.filter_map(|l| { .filter_map(|l| {
let mut values = l.split(":"); let mut values = l.split(':');
let ssid = Ssid(values.next()?.to_owned()); let ssid = Ssid(values.next()?.to_owned());
let signal = SignalStrength::new(std::str::FromStr::from_str(values.next()?).ok()); let signal = SignalStrength::new(std::str::FromStr::from_str(values.next()?).ok());
let security: Vec<String> = let security: Vec<String> =
values.next()?.split(" ").map(|x| x.to_owned()).collect(); values.next()?.split(' ').map(|x| x.to_owned()).collect();
Some(( Some((
ssid, ssid,
WifiListInfo { WifiListInfo {
@@ -618,12 +624,9 @@ impl WpaCli {
let mut current; let mut current;
loop { loop {
current = self.get_current_network().await; current = self.get_current_network().await;
match &current { if let Ok(Some(ssid)) = &current {
Ok(Some(ssid)) => { tracing::debug!("Connected to: {}", ssid.0);
tracing::debug!("Connected to: {}", ssid.0); break;
break;
}
_ => {}
} }
tokio::time::sleep(Duration::from_millis(500)).await; tokio::time::sleep(Duration::from_millis(500)).await;
tracing::debug!("Retrying..."); tracing::debug!("Retrying...");
@@ -677,7 +680,7 @@ impl WpaCli {
psk: &Psk, psk: &Psk,
priority: isize, priority: isize,
) -> Result<(), Error> { ) -> Result<(), Error> {
self.set_add_network_low(&ssid, &psk).await?; self.set_add_network_low(ssid, psk).await?;
self.save_config(db).await?; self.save_config(db).await?;
Ok(()) Ok(())
} }
@@ -689,7 +692,7 @@ impl WpaCli {
psk: &Psk, psk: &Psk,
priority: isize, priority: isize,
) -> Result<(), Error> { ) -> Result<(), Error> {
self.add_network_low(&ssid, &psk).await?; self.add_network_low(ssid, psk).await?;
self.save_config(db).await?; self.save_config(db).await?;
Ok(()) Ok(())
} }
@@ -703,16 +706,17 @@ pub async fn interface_connected(interface: &str) -> Result<bool, Error> {
.await?; .await?;
let v = std::str::from_utf8(&out)? let v = std::str::from_utf8(&out)?
.lines() .lines()
.filter(|s| s.contains("inet")) .find(|s| s.contains("inet"));
.next(); Ok(v.is_some())
Ok(!v.is_none())
} }
pub fn country_code_parse(code: &str, _matches: &ArgMatches<'_>) -> Result<CountryCode, Error> { pub fn country_code_parse(code: &str, _matches: &ArgMatches<'_>) -> Result<CountryCode, Error> {
CountryCode::for_alpha2(code).or(Err(Error::new( CountryCode::for_alpha2(code).map_err(|_| {
color_eyre::eyre::eyre!("Invalid Country Code: {}", code), Error::new(
ErrorKind::Wifi, color_eyre::eyre::eyre!("Invalid Country Code: {}", code),
))) ErrorKind::Wifi,
)
})
} }
#[instrument(skip(main_datadir))] #[instrument(skip(main_datadir))]
@@ -722,16 +726,16 @@ pub async fn synchronize_wpa_supplicant_conf<P: AsRef<Path>>(
) -> Result<(), Error> { ) -> Result<(), Error> {
let persistent = main_datadir.as_ref().join("system-connections"); let persistent = main_datadir.as_ref().join("system-connections");
tracing::debug!("persistent: {:?}", persistent); tracing::debug!("persistent: {:?}", persistent);
let supplicant = Path::new("/etc/wpa_supplicant.conf"); // let supplicant = Path::new("/etc/wpa_supplicant.conf");
if tokio::fs::metadata(&persistent).await.is_err() { if tokio::fs::metadata(&persistent).await.is_err() {
tokio::fs::create_dir_all(&persistent).await?; tokio::fs::create_dir_all(&persistent).await?;
} }
crate::disk::mount::util::bind(&persistent, "/etc/NetworkManager/system-connections", false) crate::disk::mount::util::bind(&persistent, "/etc/NetworkManager/system-connections", false)
.await?; .await?;
if tokio::fs::metadata(&supplicant).await.is_err() { // if tokio::fs::metadata(&supplicant).await.is_err() {
tokio::fs::write(&supplicant, include_str!("wpa_supplicant.conf.base")).await?; // tokio::fs::write(&supplicant, include_str!("wpa_supplicant.conf.base")).await?;
} // }
Command::new("systemctl") Command::new("systemctl")
.arg("restart") .arg("restart")
@@ -752,6 +756,14 @@ pub async fn synchronize_wpa_supplicant_conf<P: AsRef<Path>>(
.arg(last_country_code.alpha2()) .arg(last_country_code.alpha2())
.invoke(ErrorKind::Wifi) .invoke(ErrorKind::Wifi)
.await?; .await?;
} else {
tracing::info!("Setting the region fallback");
let _ = Command::new("iw")
.arg("reg")
.arg("set")
.arg("US")
.invoke(ErrorKind::Wifi)
.await?;
} }
Ok(()) Ok(())
} }

View File

@@ -6,8 +6,6 @@ set -e
! test -f /etc/docker/daemon.json || rm /etc/docker/daemon.json ! test -f /etc/docker/daemon.json || rm /etc/docker/daemon.json
mount -o remount,rw /boot mount -o remount,rw /boot
curl -fsSL https://get.docker.com | sh # TODO: commit this script into git instead of live fetching it
apt-get update apt-get update
apt-get install -y \ apt-get install -y \
tor \ tor \
@@ -28,16 +26,21 @@ apt-get install -y \
samba-common-bin \ samba-common-bin \
ntp \ ntp \
network-manager network-manager
curl -fsSL https://get.docker.com | sh # TODO: commit this script into git instead of live fetching it
apt-get purge openresolv dhcpcd5 -y
systemctl disable wpa_supplicant.service
apt-get autoremove -y apt-get autoremove -y
apt-get upgrade -y apt-get upgrade -y
sed -i 's/Restart=on-failure/Restart=always/g' /lib/systemd/system/tor@default.service sed -i 's/Restart=on-failure/Restart=always/g' /lib/systemd/system/tor@default.service
sed -i '/}/i \ \ \ \ application\/wasm \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ wasm;' /etc/nginx/mime.types sed -i '/}/i \ \ \ \ application\/wasm \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ wasm;' /etc/nginx/mime.types
sed -i 's/# server_names_hash_bucket_size 64;/server_names_hash_bucket_size 128;/g' /etc/nginx/nginx.conf sed -i 's/# server_names_hash_bucket_size 64;/server_names_hash_bucket_size 128;/g' /etc/nginx/nginx.conf
sed -i 's/ExecStart=\/sbin\/wpa_supplicant -u -s -O \/run\/wpa_supplicant/ExecStart=\/sbin\/wpa_supplicant -u -s -O \/run\/wpa_supplicant -c \/etc\/wpa_supplicant.conf -i wlan0/g' /lib/systemd/system/wpa_supplicant.service # sed -i 's/ExecStart=\/sbin\/wpa_supplicant -u -s -O \/run\/wpa_supplicant/ExecStart=\/sbin\/wpa_supplicant -u -s -O \/run\/wpa_supplicant -c \/etc\/wpa_supplicant.conf -i wlan0/g' /lib/systemd/system/wpa_supplicant.service
sed -i 's/#allow-interfaces=eth0/allow-interfaces=eth0,wlan0/g' /etc/avahi/avahi-daemon.conf sed -i 's/#allow-interfaces=eth0/allow-interfaces=eth0,wlan0/g' /etc/avahi/avahi-daemon.conf
echo "auto wlan0" > /etc/network/interfaces echo "#" > /etc/network/interfaces
echo "iface wlan0 inet dhcp" >> /etc/network/interfaces
mkdir -p /etc/nginx/ssl mkdir -p /etc/nginx/ssl
# fix to suppress docker warning, fixed in 21.xx release of docker cli: https://github.com/docker/cli/pull/2934 # fix to suppress docker warning, fixed in 21.xx release of docker cli: https://github.com/docker/cli/pull/2934

View File

@@ -17,6 +17,7 @@ if [ -z "$OUTPUT_DEVICE" ]; then
export DETACH_OUTPUT_DEVICE=1 export DETACH_OUTPUT_DEVICE=1
else else
export DETACH_OUTPUT_DEVICE=0 export DETACH_OUTPUT_DEVICE=0
sudo dd if=/dev/zero of=$OUTPUT_DEVICE bs=1M count=1
fi fi
export LOOPDEV=$(sudo losetup --show -fP raspios.img) export LOOPDEV=$(sudo losetup --show -fP raspios.img)
./build/partitioning.sh ./build/partitioning.sh