fix: address clippy warnings

This commit is contained in:
beerpiss 2024-06-27 02:06:18 +07:00
parent 47bb748b3b
commit 852e27d47d
6 changed files with 49 additions and 48 deletions

View File

@ -15,6 +15,7 @@ pub enum DecryptError {
}
#[derive(Debug)]
#[allow(dead_code)]
pub struct MaybeDecompressError {
pub zlib_error: io::Error,
pub raw_error: io::Error,

View File

@ -66,18 +66,18 @@ pub enum HookError {
#[derive(Debug, Snafu)]
pub enum ProcessRequestError {
#[snafu(display("Could not read URL from HINTERNET handle"))]
UrlReadError { source: ReadStringFnError },
UrlRead { source: ReadStringFnError },
#[snafu(display("The URL does not have an endpoint"))]
UrlMissingEndpointError,
UrlMissingEndpoint,
#[snafu(display(
"Hooked function was called before all necessary state has been initialized"
))]
UninitializedError,
UninitializedState,
#[snafu(display("Could not read request body"))]
ReadBodyError { source: io::Error },
ReadBody { source: io::Error },
}
#[derive(Debug, Clone)]
@ -170,6 +170,7 @@ pub fn hook_release() -> Result<(), HookError> {
Ok(())
}
#[allow(clippy::missing_transmute_annotations)]
#[crochet::hook(compile_check, "winhttp.dll", "WinHttpWriteData")]
fn winhttpwritedata_hook(
hrequest: HINTERNET,
@ -201,10 +202,10 @@ fn process_request(
let endpoint = url
.split('/')
.last()
.ok_or(ProcessRequestError::UrlMissingEndpointError)?;
.ok_or(ProcessRequestError::UrlMissingEndpoint)?;
let upsert_user_all_endpoint = UPSERT_USER_ALL_API
.get()
.ok_or(ProcessRequestError::UninitializedError)?;
.ok_or(ProcessRequestError::UninitializedState)?;
if endpoint != upsert_user_all_endpoint {
return Ok(());
@ -248,7 +249,7 @@ fn process_request(
raw_body
};
let body = match maybe_decompress_buffer(&compressed_body) {
let body = match maybe_decompress_buffer(compressed_body) {
Ok(s) => s,
Err(e) => {
error!("Could not read request as DEFLATE-compressed or plaintext: {e:#?}");
@ -286,7 +287,7 @@ fn process_request(
config.general.fail_over_lamp,
);
if let Err(e) = execute_score_import(import, access_code, &tachi_api_key, &config) {
if let Err(e) = execute_score_import(import, access_code, tachi_api_key, config) {
error!("{e}");
}
});

View File

@ -70,7 +70,7 @@ pub fn execute_score_import(
&client,
"POST",
&import_url,
&api_key,
api_key,
Some(&import),
) {
Ok(r) => r,
@ -113,14 +113,14 @@ pub fn execute_score_import(
match response.body {
ImportResponse::Deferred(d) => {
info!("Import was queued for processing. Poll URL: {}", d.url);
poll_deferred_import(&client, &api_key, &d.url);
return Ok(());
poll_deferred_import(&client, api_key, &d.url);
}
ImportResponse::Completed(d) => {
log_tachi_import(&response.description, &d);
return Ok(());
}
}
Ok(())
}
fn saekawa_client(config: &SaekawaConfig) -> ureq::Agent {
@ -135,7 +135,7 @@ fn exponential_backoff(rand: &mut ThreadRng, attempt: u32) -> u64 {
// 0 | 2-4 seconds
// 1 | 8-16 seconds
// 2 | 32-64 seconds
return rand.gen_range(500..=1000) * 4_u64.pow(attempt + 1);
rand.gen_range(500..=1000) * 4_u64.pow(attempt + 1)
}
fn request_tachi<T, R>(
@ -215,9 +215,9 @@ where
.context(InvalidTachiResponseSnafu);
}
return Err(ScoreImportError::MaxRetriesExhausted {
Err(ScoreImportError::MaxRetriesExhausted {
max_retries: MAX_RETRY_COUNT,
});
})
}
fn log_tachi_import(description: &str, import: &ImportDocument) {
@ -236,7 +236,7 @@ fn log_tachi_import(description: &str, import: &ImportDocument) {
fn poll_deferred_import(client: &ureq::Agent, api_key: &str, poll_url: &str) {
loop {
let resp = match request_tachi::<_, ImportPollStatus>(
&client, "GET", &poll_url, &api_key, None::<()>,
client, "GET", poll_url, api_key, None::<()>,
) {
Ok(r) => r,
Err(e) => {
@ -253,12 +253,9 @@ fn poll_deferred_import(client: &ureq::Agent, api_key: &str, poll_url: &str) {
}
};
match resp.body {
ImportPollStatus::Completed { import } => {
log_tachi_import(&resp.description, &import);
return;
}
_ => {}
if let ImportPollStatus::Completed { import } = resp.body {
log_tachi_import(&resp.description, &import);
return;
}
thread::sleep(Duration::from_secs(1));

View File

@ -108,8 +108,7 @@ impl ToBatchManual for UpsertUserAllRequest {
};
let emblem = user_data
.class_emblem_base
.map(|b| ClassEmblem::try_from(b).ok())
.flatten();
.and_then(|b| ClassEmblem::try_from(b).ok());
Some(BatchManualClasses { dan, emblem })
} else {

View File

@ -55,12 +55,12 @@ pub struct ReplaceArgs {
pub unsafe extern "system" fn replace_with_new_library(parameter: *const c_void) -> u32 {
let args = parameter as *const ReplaceArgs;
let GetModuleFileNameA =
std::mem::transmute::<_, GetModuleFileNameAFn>(GET_MODULE_FILE_NAME_A_PTR);
let GetProcessHeap = std::mem::transmute::<_, GetProcessHeapFn>(GET_PROCESS_HEAP_PTR);
let ReplaceFileW = std::mem::transmute::<_, ReplaceFileWFn>(REPLCE_FILE_W_PTR);
let LoadLibraryW = std::mem::transmute::<_, LoadLibraryWFn>(LOAD_LIBRARY_W_POINTER);
let HeapFree = std::mem::transmute::<_, HeapFreeFn>(HEAP_FREE_PTR);
let Sleep = std::mem::transmute::<_, SleepFn>(SLEEP_PTR);
std::mem::transmute::<PROC, GetModuleFileNameAFn>(GET_MODULE_FILE_NAME_A_PTR);
let GetProcessHeap = std::mem::transmute::<PROC, GetProcessHeapFn>(GET_PROCESS_HEAP_PTR);
let ReplaceFileW = std::mem::transmute::<PROC, ReplaceFileWFn>(REPLCE_FILE_W_PTR);
let LoadLibraryW = std::mem::transmute::<PROC, LoadLibraryWFn>(LOAD_LIBRARY_W_POINTER);
let HeapFree = std::mem::transmute::<PROC, HeapFreeFn>(HEAP_FREE_PTR);
let Sleep = std::mem::transmute::<PROC, SleepFn>(SLEEP_PTR);
// Wait for the old library to be freed
let mut filename = 0;
@ -78,10 +78,10 @@ pub unsafe extern "system" fn replace_with_new_library(parameter: *const c_void)
let result = ReplaceFileW(
(*args).old.as_ptr(),
(*args).new.as_ptr(),
0 as *const _,
std::ptr::null(),
2,
0 as *mut c_void,
0 as *mut c_void,
std::ptr::null_mut(),
std::ptr::null_mut(),
);
if result > 0 {

View File

@ -92,6 +92,7 @@ extern "system" {
}
#[derive(Debug, Snafu)]
#[allow(clippy::large_enum_variant)]
pub enum SelfUpdateError {
#[snafu(display("Could not get the file name of the currently running hook"))]
FailedToGetFilename { source: ReadStringFnError },
@ -157,22 +158,22 @@ pub enum VerifySignatureError {
#[derive(Snafu, Debug)]
pub enum GetSignaturePubkeyError {
#[snafu(display("CertQueryObject failed: {errno}"))]
QueryObjectError { errno: u32 },
QueryObject { errno: u32 },
#[snafu(display("Could not obtain size of signer information: {errno}"))]
SignerInfoSizeError { errno: u32 },
SignerInfoSize { errno: u32 },
#[snafu(display("Could not allocate memory for signer information: {errno}"))]
SignerInfoAllocError { errno: u32 },
SignerInfoAlloc { errno: u32 },
#[snafu(display("Could not obtain signer information: {errno}"))]
SignerInfoObtainError { errno: u32 },
SignerInfoObtain { errno: u32 },
#[snafu(display("Could not look up certificate in certificate store: {errno}"))]
CertificateInStoreError { errno: u32 },
CertificateInStore { errno: u32 },
#[snafu(display("Could not read public key."))]
ReadPubkeyError { source: io::Error },
ReadPubkey { source: io::Error },
}
#[derive(Serialize, Deserialize, Debug, Clone)]
@ -184,6 +185,7 @@ struct UpdateInformation {
/// Checks if the hook has a newer version. Returns true if update was successful
/// and the hook should uninject itself so a newer version can load in.
#[allow(clippy::result_large_err)]
pub fn self_update(module: &LibraryHandle) -> Result<bool, SelfUpdateError> {
let agent = ureq::builder()
.user_agent(concat!("saekawa/", env!("CARGO_PKG_VERSION")))
@ -367,8 +369,8 @@ pub fn self_update(module: &LibraryHandle) -> Result<bool, SelfUpdateError> {
debug!("Allocated heap for updater code at {heap:p}");
(*heap).module = module.handle();
let old = U16CString::from_str_truncate(&module_filename);
let new = U16CString::from_str_truncate(&new_module_path.to_string_lossy());
let old = U16CString::from_str_truncate(module_filename);
let new = U16CString::from_str_truncate(new_module_filename);
std::ptr::copy_nonoverlapping(
old.as_ptr(),
(*heap).old.as_mut_ptr(),
@ -384,7 +386,7 @@ pub fn self_update(module: &LibraryHandle) -> Result<bool, SelfUpdateError> {
let handle = CreateThread(
ptr::null_mut(),
0,
Some(std::mem::transmute(updater_start_address)),
Some(std::mem::transmute::<PROC, unsafe extern "system" fn(*mut winapi::ctypes::c_void) -> u32>(updater_start_address)),
heap as *mut _,
0,
ptr::null_mut(),
@ -400,10 +402,11 @@ pub fn self_update(module: &LibraryHandle) -> Result<bool, SelfUpdateError> {
return Ok(true);
}
return Err(SelfUpdateError::NoUpdaterCodeSection);
Err(SelfUpdateError::NoUpdaterCodeSection)
}
}
#[allow(clippy::result_large_err)]
fn validate_sha256(data: &[u8], expected: &str) -> Result<(), SelfUpdateError> {
let mut hasher = Sha256::new();
@ -494,7 +497,7 @@ fn get_signature_pubkey(file: &str) -> Result<Vec<u8>, GetSignaturePubkeyError>
};
if result == 0 {
return Err(GetSignaturePubkeyError::QueryObjectError {
return Err(GetSignaturePubkeyError::QueryObject {
errno: unsafe { GetLastError() },
});
}
@ -511,7 +514,7 @@ fn get_signature_pubkey(file: &str) -> Result<Vec<u8>, GetSignaturePubkeyError>
};
if result == 0 {
return Err(GetSignaturePubkeyError::SignerInfoSizeError {
return Err(GetSignaturePubkeyError::SignerInfoSize {
errno: unsafe { GetLastError() },
});
}
@ -520,7 +523,7 @@ fn get_signature_pubkey(file: &str) -> Result<Vec<u8>, GetSignaturePubkeyError>
unsafe { LocalAlloc(LMEM_ZEROINIT, signer_info_length as usize) } as PCMSG_SIGNER_INFO;
if signer_info.is_null() {
return Err(GetSignaturePubkeyError::SignerInfoAllocError {
return Err(GetSignaturePubkeyError::SignerInfoAlloc {
errno: unsafe { GetLastError() },
});
}
@ -536,7 +539,7 @@ fn get_signature_pubkey(file: &str) -> Result<Vec<u8>, GetSignaturePubkeyError>
};
if result == 0 {
return Err(GetSignaturePubkeyError::SignerInfoObtainError {
return Err(GetSignaturePubkeyError::SignerInfoObtain {
errno: unsafe { GetLastError() },
});
}
@ -562,7 +565,7 @@ fn get_signature_pubkey(file: &str) -> Result<Vec<u8>, GetSignaturePubkeyError>
};
if cert.is_null() {
return Err(GetSignaturePubkeyError::CertificateInStoreError {
return Err(GetSignaturePubkeyError::CertificateInStore {
errno: unsafe { GetLastError() },
});
}