Refactoring

- Added print_banner macro
- Moved main logic into function
- More idiomatic code
This commit is contained in:
LinusDikomey 2022-03-18 18:07:08 +01:00
parent c7feeb0992
commit 39be1d684a
1 changed files with 186 additions and 232 deletions

View File

@ -1,249 +1,201 @@
use std::borrow::Cow;
use clap::Parser;
#[derive(Parser, Debug)]
#[clap(author, version, about, long_about = None)]
struct Args {
#[clap(short, long)]
hostname: String,
//example: "IServSAT=mvuvFvCZSlpvuwhk0mmNwF1NKEQypM4d; IServSession=xEPqyJO1a5nsVd34HEpbPqQGMMQKapvw; nav-show-additional-modules=true; PHPSESSID=mchbrl11epjnnp851q0i4rt8rc"
#[clap(short, long)]
session_cookie: String,
#[clap(long)]
target_ip: String,
#[clap(long)]
target_room: u16,
#[clap(long)]
target_compilation: Option<u16>,
}
macro_rules! print_banner {
($f: expr, $($arg: expr),*) => {
println!(concat!("-----------------------------------\n", $f, "\n-----------------------------------"), $($arg),*)
};
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args = Args::parse();
loop {
let params = [
("filter[controllable]", ""),
("filter[room][]", "__none"),
("filter[group]", ""),
("filter[search]", "iPad"),
];
let header = ("Cookie", args.session_cookie.to_owned());
let client = reqwest::blocking::Client::new();
loop { ipad(&args)?; }
}
let resp = client
.get(format!("https://{}/iserv/admin/hosts", args.hostname))
.header(header.0, header.to_owned().1)
.query(&params)
.send()?;
let status = &resp.status();
let plain = &resp.text()?;
let content = squeeze(
&plain,
"<script id=\"crud-data\" type=\"application/json\">",
"</script>",
);
let json: serde_json::Value = serde_json::from_str(content).expect("Bad Jason!");
let json_part = &json["data"][0]["name"]["rendered"]
.to_string()
.replace("\\", "");
// skip rest of loop when no entry appeared
if json_part == "null" {
println!("###################################");
println!("No new host: skipping (Retry in 5s)");
println!("###################################");
//sleep for 5 seconds
std::thread::sleep(std::time::Duration::from_secs(5));
continue;
}
let host_id = squeeze(json_part, "data-host-id=\"", "\"");
let device_name = squeeze(json_part, "</span>", "</a>");
println!("-----------------------------------");
println!("1/7 Found host");
println!("Host id: {}", host_id);
println!("Device name: {}", device_name);
println!("Received response status: {:?}", status);
let dest = format!("https://{}/iserv/admin/host/edit/{}", args.hostname, &host_id);
let resp = client.get(&dest).header(header.0, header.to_owned().1).send()?;
//TODO Check for non 200 response
let status = &resp.status();
let plain = &resp.text()?;
let mut form_ip: &str = &args.target_ip; //default
let form_name = squeeze_html_form(plain, "name=\"host[name]\"", "value=\"", "\"");
let form_tags = squeeze_html_form(plain, "name=\"host[tags][]\"", "value=\"", "\"");
let form_mac = squeeze_html_form(plain, "name=\"host[mac]\"", "value=\"", "\"");
let form_description = squeeze_html_form(plain, "name=\"host[description]\"", ">", "<");
let form_token = squeeze_html_form(plain, "name=\"host[_token]\"", "value=\"", "\"");
let mut form_data = [
("host[name]", form_name),
("host[tags][]", form_tags),
("host[room]", &args.target_room.to_string()),
("host[ip]", &form_ip),
("host[mac]", form_mac),
("host[internet]", "1"),
("host[proxyEnforce]", "0"),
("host[owner]", ""),
("host[controllable]", "0"),
("host[inventoryNumber]", ""),
("host[shutdown]", ""),
("host[description]", form_description),
("host[image][id]", ""),
("host[image][x]", ""),
("host[image][y]", ""),
("host[actions][submit]", ""),
("host[_token]", form_token),
];
println!("-----------------------------------");
println!("2/7 Received current host properties");
println!("Received response status: {:?}", status);
let resp = client
.post(&dest)
.header(header.0, header.to_owned().1)
.form(&form_data)
.send()?;
let status = &resp.status();
let plain = &resp.text()?;
form_ip = squeeze_html_form(plain, "name=\"host[ip]\"", "value=\"", "\"");
form_data[3] = ("host[ip]", form_ip);
println!("-----------------------------------");
println!("3/7 Received recommended ip: {}", form_ip);
println!("Received response status: {:?}", status);
let resp = client
.post(&dest)
.header(header.0, header.to_owned().1)
.form(&form_data)
.send()?;
let status = &resp.status();
println!("-----------------------------------");
println!("4/7 Sucessfully updated host");
println!("Received response status: {:?}", status);
println!("-----------------------------------");
if args.target_compilation.is_none() {
continue;
}
let resp = client
.get(format!("https://{}/iserv/admin/mdm/ios/compilation/edit/{}", args.hostname, args.target_compilation.unwrap()))
fn ipad(args: &Args) -> Result<(), Box<dyn std::error::Error>> {
let params = [
("filter[controllable]", ""),
("filter[room][]", "__none"),
("filter[group]", ""),
("filter[search]", "iPad"),
];
let header = ("Cookie", args.session_cookie.to_owned());
let client = reqwest::blocking::Client::new();
let resp = client
.get(format!("https://{}/iserv/admin/hosts", args.hostname))
.header(header.0, header.to_owned().1)
.query(&params)
.send()?;
//TODO Check for non 200 response
let status = &resp.status();
let plain = &resp.text()?;
println!("-----------------------------------");
println!("5/7 Received MDM compilation");
println!("Received response status: {:?}", status);
println!("-----------------------------------");
let csrf_token = squeeze_html_form(plain, "name=\"ioscompilation[_token]\"", "value=\"", "\"");
let mut form_data = Vec::from([
(
Cow::Borrowed("ioscompilation[name]"),
Cow::Borrowed(squeeze_html_form(plain, "name=\"ioscompilation[name]\"", "value=\"", "\"")),
),
(
Cow::Borrowed("ioscompilation[description]"),
Cow::Borrowed(squeeze_html_form(plain, "name=\"ioscompilation[description]\"", "value=\"", "\"")),
),
]);
// push apps (<option value="52" selected="selected">)
let plain_inner_applications = squeeze_html_form(plain, "name=\"ioscompilation[applications][]\"", ">", "</select>");
form_data.append(&mut squeeze_loop(plain_inner_applications, "<option value=\"", "\"", " selected=\"selected\"", 3, "ioscompilation[applications][]"));
// push profiles
let plain_inner_profiles = squeeze_html_form(plain, "name=\"ioscompilation[profiles][]\"", ">", "</select>");
form_data.append(&mut squeeze_loop(plain_inner_profiles, "<option value=\"", "\"", " selected=\"selected\"", 3, "ioscompilation[profiles][]"));
// push existing devices ([\s\n]* seems not needed)
let plain_inner_devices = squeeze_html_form(plain, "name=\"ioscompilation[devices][]\"", ">", "</select>");
form_data.append(&mut squeeze_loop(plain_inner_devices, "<option value=\"", "\"", " selected=\"selected\"", 3, "ioscompilation[devices][]"));
// push new device
let mdm_new_ipad_id = squeeze_right(plain_inner_devices, "<option value=\"", &format!("\">{}", form_name));
if plain_inner_devices.contains(form_name) {
form_data.push(("ioscompilation[devices][]".into(), mdm_new_ipad_id.into()));
} else {
eprintln!("Device not found in compilation edit.")
}
// push submit action
form_data.push(("ioscompilation[actions][submit]".into(), "".into()));
//push token
let form_token = squeeze_html_form(plain, "name=\"ioscompilation[_token]\"", "value=\"", "\"");
form_data.push(("ioscompilation[_token]".into(), form_token.into()));
let resp = client
.post(format!("https://{}/iserv/admin/mdm/ios/compilation/edit/{}", args.hostname, args.target_compilation.unwrap()))
.header(header.0, header.to_owned().1)
.form(&form_data)
.send()?;
let status = &resp.status();
let plain = &resp.text()?;
std::fs::write("device-add.out.html", plain).unwrap();
println!("-----------------------------------");
println!("6/7 Added device to MDM Compilation");
println!("Received response status: {:?}", status);
println!("-----------------------------------");
let form_data = [
("iserv_crud_multi_select[confirm]", "apply-changes"),
("iserv_crud_multi_select[multi][]", mdm_new_ipad_id),
("iserv_crud_multi_select[topReplacementActions][apply-changes]", ""),
//("iserv_crud_multi_select[_token]", csrf_token),
// seems to work with and without token :o (but without it iserv throws a csrf error) // example token: rqB8um_Y6sJ1hCFMeVlg9r3L0v__tH3GS5KcV4Lj_ug
];
let resp = client
.post(format!("https://{}/iserv/admin/mdm/ios/device/batch", args.hostname))
.header(header.0, header.to_owned().1)
.form(&form_data)
.send()?;
let status = &resp.status();
let plain = &resp.text()?;
std::fs::write("confirm.out.html", plain).unwrap();
println!("-----------------------------------");
println!("7/7 Confirmed device actions");
println!("Received response status: {:?}", status);
println!("-----------------------------------");
let status = &resp.status();
let plain = &resp.text()?;
let content = squeeze(
&plain,
"<script id=\"crud-data\" type=\"application/json\">",
"</script>",
);
let json: serde_json::Value = serde_json::from_str(content).expect("Bad Jason!");
let json_part = &json["data"][0]["name"]["rendered"]
.to_string()
.replace("\\", "");
// skip rest of loop when no entry appeared
if json_part == "null" {
println!(
"###################################
No new host: skipping (Retry in 5s)
###################################
");
//sleep for 5 seconds
std::thread::sleep(std::time::Duration::from_secs(5));
return Ok(());
}
//Ok(())
let host_id = squeeze(json_part, "data-host-id=\"", "\"");
let device_name = squeeze(json_part, "</span>", "</a>");
print_banner!("1/7 Found host\nHost id: {}\nDevice name: {}\nReceived response status: {:?}", host_id, device_name, status);
let dest = format!("https://{}/iserv/admin/host/edit/{}", args.hostname, &host_id);
let resp = client.get(&dest).header(header.0, header.to_owned().1).send()?;
//TODO Check for non 200 response
let status = &resp.status();
if !status.is_success() && *status != 300 {
eprintln!("WARN: Found invalid Status Code: {status}");
return Ok(())
}
let plain = &resp.text()?;
let mut form_ip: &str = &args.target_ip; //default
let form_name = squeeze_html_form(plain, "name=\"host[name]\"", "value=\"", "\"");
let form_tags = squeeze_html_form(plain, "name=\"host[tags][]\"", "value=\"", "\"");
let form_mac = squeeze_html_form(plain, "name=\"host[mac]\"", "value=\"", "\"");
let form_description = squeeze_html_form(plain, "name=\"host[description]\"", ">", "<");
let form_token = squeeze_html_form(plain, "name=\"host[_token]\"", "value=\"", "\"");
let mut form_data = [
("host[name]", form_name),
("host[tags][]", form_tags),
("host[room]", &args.target_room.to_string()),
("host[ip]", &form_ip),
("host[mac]", form_mac),
("host[internet]", "1"),
("host[proxyEnforce]", "0"),
("host[owner]", ""),
("host[controllable]", "0"),
("host[inventoryNumber]", ""),
("host[shutdown]", ""),
("host[description]", form_description),
("host[image][id]", ""),
("host[image][x]", ""),
("host[image][y]", ""),
("host[actions][submit]", ""),
("host[_token]", form_token),
];
print_banner!("2/7 Received current host properties\nReceived response status: {:?}", status);
let resp = client
.post(&dest)
.header(header.0, header.to_owned().1)
.form(&form_data)
.send()?;
let status = &resp.status();
let plain = &resp.text()?;
form_ip = squeeze_html_form(plain, "name=\"host[ip]\"", "value=\"", "\"");
form_data[3] = ("host[ip]", form_ip);
print_banner!("3/7 Received recommended ip: {}\nReceived response status: {:?}", form_ip, status);
let resp = client
.post(&dest)
.header(header.0, header.to_owned().1)
.form(&form_data)
.send()?;
let status = &resp.status();
print_banner!("4/7 Sucessfully updated host\nReceived response status: {:?}", status);
if args.target_compilation.is_none() { return Ok(()) }
let resp = client
.get(format!("https://{}/iserv/admin/mdm/ios/compilation/edit/{}", args.hostname, args.target_compilation.unwrap()))
.header(header.0, header.to_owned().1)
.send()?;
//TODO Check for non 200 response
let status = &resp.status();
let plain = &resp.text()?;
print_banner!("5/7 Received MDM compilation\nReceived response status: {:?}", status);
//let csrf_token = squeeze_html_form(plain, "name=\"ioscompilation[_token]\"", "value=\"", "\"");
let mut form_data = Vec::from([
(
"ioscompilation[name]",
squeeze_html_form(plain, "name=\"ioscompilation[name]\"", "value=\"", "\"")
),
(
"ioscompilation[description]",
squeeze_html_form(plain, "name=\"ioscompilation[description]\"", "value=\"", "\"")
),
].map(|(a, b)| (Cow::Borrowed(a), Cow::Borrowed(b))));
// push apps (<option value="52" selected="selected">)
let plain_inner_applications = squeeze_html_form(plain, "name=\"ioscompilation[applications][]\"", ">", "</select>");
squeeze_loop(&mut form_data, plain_inner_applications, "<option value=\"", "\"", " selected=\"selected\"", 3, "ioscompilation[applications][]");
// push profiles
let plain_inner_profiles = squeeze_html_form(plain, "name=\"ioscompilation[profiles][]\"", ">", "</select>");
squeeze_loop(&mut form_data, plain_inner_profiles, "<option value=\"", "\"", " selected=\"selected\"", 3, "ioscompilation[profiles][]");
// push existing devices ([\s\n]* seems not needed)
let plain_inner_devices = squeeze_html_form(plain, "name=\"ioscompilation[devices][]\"", ">", "</select>");
squeeze_loop(&mut form_data, plain_inner_devices, "<option value=\"", "\"", " selected=\"selected\"", 3, "ioscompilation[devices][]");
// push new device
let mdm_new_ipad_id = squeeze_right(plain_inner_devices, "<option value=\"", &format!("\">{}", form_name));
if plain_inner_devices.contains(form_name) {
form_data.push(("ioscompilation[devices][]".into(), mdm_new_ipad_id.into()));
} else {
eprintln!("Device not found in compilation edit.")
}
// push submit action
form_data.push(("ioscompilation[actions][submit]".into(), "".into()));
//push token
let form_token = squeeze_html_form(plain, "name=\"ioscompilation[_token]\"", "value=\"", "\"");
form_data.push(("ioscompilation[_token]".into(), form_token.into()));
let resp = client
.post(format!("https://{}/iserv/admin/mdm/ios/compilation/edit/{}", args.hostname, args.target_compilation.unwrap()))
.header(header.0, header.to_owned().1)
.form(&form_data)
.send()?;
let status = &resp.status();
let plain = &resp.text()?;
std::fs::write("device-add.out.html", plain).unwrap();
print_banner!("6/7 Added device to MDM Compilation\nReceived response status: {:?}", status);
let form_data = [
("iserv_crud_multi_select[confirm]", "apply-changes"),
("iserv_crud_multi_select[multi][]", mdm_new_ipad_id),
("iserv_crud_multi_select[topReplacementActions][apply-changes]", ""),
//("iserv_crud_multi_select[_token]", csrf_token),
// seems to work with and without token :o (but without it iserv throws a csrf error) // example token: rqB8um_Y6sJ1hCFMeVlg9r3L0v__tH3GS5KcV4Lj_ug
];
let resp = client
.post(format!("https://{}/iserv/admin/mdm/ios/device/batch", args.hostname))
.header(header.0, header.to_owned().1)
.form(&form_data)
.send()?;
let status = &resp.status();
let plain = &resp.text()?;
std::fs::write("confirm.out.html", plain).unwrap();
print_banner!("7/7 Confirmed device actions\nReceived response status: {:?}", status);
Ok(())
}
// helper functions
fn squeeze<'input>(input: &'input str, before: &str, after: &str) -> &'input str {
fn squeeze<'inp>(input: &'inp str, before: &str, after: &str) -> &'inp str {
//find before occurence (excluded from output)
if let Some(before_bytes) = input.find(before) {
let adjusted_before_bytes = before_bytes + before.len();
@ -257,13 +209,11 @@ fn squeeze<'input>(input: &'input str, before: &str, after: &str) -> &'input str
}
}
}
return "";
""
}
fn squeeze_right<'input>(input: &'input str, before: &str, after: &str) -> &'input str {
fn squeeze_right<'inp>(input: &'inp str, before: &str, after: &str) -> &'inp str {
//find before occurence (excluded from output)
if let Some(after_bytes) = input.find (after) {
// let adjusted_before_bytes = after_bytes + after.len();
let leftover = &input[..after_bytes];
//find after occurence (excluded from output)
if let Some(before_bytes) = leftover.rfind(before) {
@ -274,15 +224,14 @@ fn squeeze_right<'input>(input: &'input str, before: &str, after: &str) -> &'inp
}
}
}
return "";
""
}
fn squeeze_html_form<'input>(
input: &'input str,
fn squeeze_html_form<'inp>(
input: &'inp str,
first: &str,
second: &str,
last: &str,
) -> &'input str {
) -> &'inp str {
//find first occurence (broad search)
if let Some(from_first_bytes) = input.find(first) {
let after_first_bytes = from_first_bytes + first.len();
@ -298,11 +247,17 @@ fn squeeze_html_form<'input>(
}
}
}
return "";
""
}
fn squeeze_loop<'input, 'vec> (input: &'input str, before: &str, after: &str, must_include_after: &str, include_after_distance: usize, index_name: &'input str) -> Vec<(Cow<'input, str>, Cow<'input, str>)> {
let mut collector: Vec<(Cow<str>, Cow<str>)> = Vec::new();
fn squeeze_loop<'inp>(
collector: &mut Vec<(Cow<'inp, str>, Cow<'inp, str>)>,
input: &'inp str,
before: &str,
after: &str,
must_include_after: &str,
include_after_distance: usize,
index_name: &'inp str
) {
let mut leftover = input;
//find before occurence (excluded from output)
while let Some(before_bytes) = leftover.find(before) {
@ -321,5 +276,4 @@ fn squeeze_loop<'input, 'vec> (input: &'input str, before: &str, after: &str, mu
}
}
}
collector
}