1use std::backtrace::Backtrace;
2use std::fmt::{self, Display, Formatter};
3use std::io;
4use std::panic::Location;
5use std::path::PathBuf;
6use std::sync::PoisonError;
7
8use aes_gcm::aead;
9use db_rs::errors::Error as DbError;
10use hmac::crypto_mac::MacError;
11use serde::ser::SerializeStruct;
12use serde::{Serialize, Serializer};
13use tracing::error;
14use uuid::Uuid;
15
16use crate::io::network::ApiError;
17use crate::model::ValidationFailure;
18
19use super::api;
20
21pub type LbResult<T> = Result<T, LbErr>;
22
23pub struct LbErr {
24 pub kind: LbErrKind,
25 pub backtrace: Option<Backtrace>,
26}
27
28impl fmt::Debug for LbErr {
29 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
30 write!(f, "{:?}", self.kind)?;
31 if let Some(backtrace) = &self.backtrace {
32 write!(f, "\n{}", backtrace.to_string().trim_end())?;
33 }
34 Ok(())
35 }
36}
37
38impl Display for LbErr {
42 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
43 write!(f, "{}", self.kind)
44 }
45}
46
47impl Display for LbErrKind {
54 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
55 match self {
56 LbErrKind::AccountExists => write!(f, "An account already exists"),
57 LbErrKind::AccountNonexistent => write!(f, "You need an account to do that"),
58 LbErrKind::AccountStringCorrupted => write!(f, "That account key is invalid"),
59 LbErrKind::AlreadyCanceled => write!(f, "Your subscription has already been cancelled"),
60 LbErrKind::AlreadyPremium => write!(f, "Your account is already premium"),
61 LbErrKind::AppStoreAccountAlreadyLinked => {
62 write!(f, "Your account is already linked to the App Store")
63 }
64 LbErrKind::CannotCancelSubscriptionForAppStore => {
65 write!(f, "You cannot cancel an app store subscription from here")
66 }
67 LbErrKind::ClientUpdateRequired => {
68 write!(f, "You must update your Lockbook to do that")
69 }
70 LbErrKind::CurrentUsageIsMoreThanNewTier => {
71 write!(f, "You need to delete some files before downgrading your usage")
72 }
73 LbErrKind::DiskPathInvalid => write!(f, "That disk path is invalid"),
74 LbErrKind::DiskPathTaken => write!(f, "That disk path is not available"),
75 LbErrKind::ExistingRequestPending => {
76 write!(f, "Existing billing request in progress, please wait and try again")
77 }
78 LbErrKind::FileNameContainsSlash => write!(f, "A file name cannot contain slashes"),
79 LbErrKind::FileNameTooLong => write!(f, "That file name is too long"),
80 LbErrKind::FileNameEmpty => write!(f, "A file name cannot be empty"),
81 LbErrKind::FileNonexistent => write!(f, "That file does not exist"),
82 LbErrKind::FileNotDocument => write!(f, "That file is not a document"),
83 LbErrKind::FileParentNonexistent => write!(f, "Could not find that file parent"),
84 LbErrKind::InsufficientPermission => {
85 write!(f, "You don't have the permission to do that")
86 }
87 LbErrKind::InvalidPurchaseToken => write!(f, "That purchase token is invalid"),
88 LbErrKind::InvalidAuthDetails => {
89 write!(f, "Our server failed to authenticate your request, please try again")
90 }
91 LbErrKind::KeyPhraseInvalid => {
92 write!(f, "Your private key phrase is wrong")
93 }
94 LbErrKind::NotPremium => write!(f, "You do not have a premium subscription"),
95 LbErrKind::UsageIsOverDataCap => {
96 write!(f, "You're out of space")
97 }
98 LbErrKind::UsageIsOverFreeTierDataCap => {
99 write!(f, "You're out of space, you can purchase additional space")
100 }
101 LbErrKind::PathContainsEmptyFileName => {
102 write!(f, "That path contains an empty file name")
103 }
104 LbErrKind::RootModificationInvalid => write!(f, "You cannot modify your root"),
105 LbErrKind::RootNonexistent => write!(f, "Could not find your root file"),
106 LbErrKind::ServerDisabled => write!(
107 f,
108 "The server is not accepting this action at the moment, please try again later"
109 ),
110 LbErrKind::ServerUnreachable => write!(f, "Could not reach server"),
111 LbErrKind::ShareAlreadyExists => write!(f, "That share already exists"),
112 LbErrKind::ShareNonexistent => write!(f, "That share does not exist"),
113 LbErrKind::TryAgain => write!(f, "Please try again"),
114 LbErrKind::UsernameInvalid => write!(f, "That username is invalid"),
115 LbErrKind::UsernameNotFound => write!(f, "That username is not found"),
116 LbErrKind::UsernamePublicKeyMismatch => {
117 write!(f, "That username doesn't match that public key")
118 }
119 LbErrKind::ImportFailed { paths, total } => {
120 let name = paths
121 .first()
122 .and_then(|p| p.file_name())
123 .unwrap_or_default()
124 .to_string_lossy();
125 match paths.len() {
126 1 => write!(f, "{name} couldn't be imported"),
127 n => write!(f, "{n} of {total} files couldn't be imported, including {name}"),
128 }
129 }
130 LbErrKind::UsernameTaken => write!(f, "That username is not available"),
131 LbErrKind::Unexpected(msg) => write!(f, "Unexpected error: {msg}"),
132 LbErrKind::AlreadySyncing => {
133 write!(f, "A sync is already in progress, cannot begin another sync at this time!")
134 }
135 LbErrKind::ReReadRequired => {
136 write!(f, "This document changed since you last read it, please re-read it!")
137 }
138 LbErrKind::AttachmentsFolderFixed => {
139 write!(f, "An attachments folder moves only with its document and keeps its name")
140 }
141 LbErrKind::Validation(validation_failure) => match validation_failure {
142 ValidationFailure::Cycle(_) => write!(f, "Cannot move a folder into itself"),
143 ValidationFailure::NonFolderWithChildren(_) => {
144 write!(f, "A document or a link was treated as a folder.")
145 }
146 ValidationFailure::PathConflict(_) => {
147 write!(f, "A file already exists at that path.")
148 }
149 ValidationFailure::DeletedFileUpdated(id) => {
150 write!(f, "this file has been deleted {id}")
151 }
152 ValidationFailure::FileNameTooLong(_) => write!(f, "this filename is too long!"),
153 ValidationFailure::OwnedLink(_) => {
154 write!(f, "you cannot have a link to a file you own")
155 }
156 ValidationFailure::BrokenLink(_) => write!(f, "that link target does not exist!"),
157 ValidationFailure::DuplicateLink { .. } => {
158 write!(f, "you already have a link to that file")
159 }
160 ValidationFailure::SharedLink { .. } => {
161 write!(f, "you cannot place a link inside a shared folder!")
162 }
163 ValidationFailure::SelfShare(_) => {
164 write!(f, "you cannot share a file with its owner or yourself")
165 }
166 _ => write!(f, "unexpected validation failure: {validation_failure:?}"),
167 },
168 LbErrKind::Diff(diff_error) => {
169 write!(f, "unexpected diff error: {diff_error:?}")
170 }
171 LbErrKind::Sign(sign_error) => {
172 write!(f, "unexpected signing error: {sign_error:?}")
173 }
174 LbErrKind::Crypto(crypto_error) => {
175 write!(f, "unexpected crypto error: {crypto_error:?}")
176 }
177 }
178 }
179}
180
181impl From<LbErrKind> for LbErr {
182 fn from(kind: LbErrKind) -> Self {
183 Self { kind, backtrace: Some(Backtrace::force_capture()) }
184 }
185}
186
187pub trait Unexpected<T> {
188 fn log_and_ignore(self) -> Option<T>;
189 fn map_unexpected(self) -> LbResult<T>;
190}
191
192impl<T, E: std::fmt::Debug> Unexpected<T> for Result<T, E> {
193 #[track_caller]
194 fn map_unexpected(self) -> LbResult<T> {
195 let location = Location::caller();
196 self.map_err(|err| {
197 LbErrKind::Unexpected(format!(
198 "unexpected error at {}:{} {err:?}",
199 location.file(),
200 location.line(),
201 ))
202 .into()
203 })
204 }
205
206 #[track_caller]
207 fn log_and_ignore(self) -> Option<T> {
208 let location = Location::caller();
209 if let Err(e) = &self {
210 error!("error ignored at {}:{} {e:?}", location.file(), location.line());
211 }
212
213 self.ok()
214 }
215}
216
217#[derive(Debug)]
218pub struct UnexpectedError {
219 pub msg: String,
220 pub backtrace: Option<Backtrace>,
221}
222
223impl UnexpectedError {
224 pub fn new(s: impl ToString) -> Self {
225 Self { msg: s.to_string(), backtrace: Some(Backtrace::force_capture()) }
226 }
227}
228
229impl fmt::Display for UnexpectedError {
230 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result {
231 write!(f, "unexpected error: {}", self.msg)
232 }
233}
234
235impl From<LbErr> for UnexpectedError {
236 fn from(err: LbErr) -> Self {
237 Self { msg: format!("{:?}", err.kind), backtrace: err.backtrace }
238 }
239}
240
241impl<T> From<PoisonError<T>> for UnexpectedError {
242 fn from(err: PoisonError<T>) -> Self {
243 Self::new(format!("{err:#?}"))
244 }
245}
246
247impl From<crossbeam::channel::RecvError> for UnexpectedError {
248 fn from(err: crossbeam::channel::RecvError) -> Self {
249 Self::new(format!("{err:#?}"))
250 }
251}
252
253impl From<crossbeam::channel::RecvTimeoutError> for UnexpectedError {
254 fn from(err: crossbeam::channel::RecvTimeoutError) -> Self {
255 Self::new(format!("{err:#?}"))
256 }
257}
258
259impl<T> From<crossbeam::channel::SendError<T>> for UnexpectedError {
260 fn from(err: crossbeam::channel::SendError<T>) -> Self {
261 Self::new(format!("{err:#?}"))
262 }
263}
264
265impl Serialize for UnexpectedError {
266 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
267 where
268 S: Serializer,
269 {
270 let mut state = serializer.serialize_struct("UnexpectedError", 2)?;
271 state.serialize_field("tag", "Unexpected")?;
272 state.serialize_field("content", &self.msg)?;
273 state.end()
274 }
275}
276
277#[macro_export]
278macro_rules! unexpected_only {
279 ($base:literal $(, $args:tt )*) => {{
280 debug!($base $(, $args )*);
281 debug!("{:?}", std::backtrace::Backtrace::force_capture());
282 debug!($base $(, $args )*);
283 UnexpectedError::new(format!($base $(, $args )*))
284 }};
285}
286
287#[derive(Debug, Clone, PartialEq, Eq)]
288pub enum LbErrKind {
289 AccountExists,
290 AccountNonexistent,
291 AccountStringCorrupted,
292 AlreadyCanceled,
293 AlreadyPremium,
294 AppStoreAccountAlreadyLinked,
295 AlreadySyncing,
296 CannotCancelSubscriptionForAppStore,
298 ClientUpdateRequired,
299 CurrentUsageIsMoreThanNewTier,
300 DiskPathInvalid,
301 DiskPathTaken,
302 ExistingRequestPending,
303 FileNameContainsSlash,
305 FileNameTooLong,
307 FileNameEmpty,
308 FileNonexistent,
309 FileNotDocument,
310 FileParentNonexistent,
311 ImportFailed {
313 paths: Vec<PathBuf>,
314 total: usize,
315 },
316 InsufficientPermission,
317 InvalidPurchaseToken,
318 InvalidAuthDetails,
319 KeyPhraseInvalid,
320 NotPremium,
321 UsageIsOverDataCap,
322 UsageIsOverFreeTierDataCap,
323 PathContainsEmptyFileName,
324 RootModificationInvalid,
325 RootNonexistent,
326 ServerDisabled,
327 ServerUnreachable,
328 ShareAlreadyExists,
329 ShareNonexistent,
330 TryAgain,
331 UsernameInvalid,
333 UsernameNotFound,
334 UsernamePublicKeyMismatch,
335 UsernameTaken,
336 ReReadRequired,
337 AttachmentsFolderFixed,
339 Diff(DiffError),
340
341 Validation(ValidationFailure),
343 Sign(SignError),
344 Crypto(CryptoError),
345
346 Unexpected(String),
351}
352
353#[derive(Debug, Clone, PartialEq, Eq)]
354pub enum DiffError {
355 OldVersionIncorrect,
356 OldFileNotFound,
357 OldVersionRequired,
358 DiffMalformed,
359 HmacModificationInvalid,
360 SizeModificationInvalid,
361}
362
363#[derive(Debug, Clone, PartialEq, Eq)]
364pub enum SignError {
365 SignatureInvalid,
366 SignatureParseError(libsecp256k1::Error),
368 WrongPublicKey,
369 SignatureInTheFuture(u64),
370 SignatureExpired(u64),
371}
372
373#[derive(Debug, Clone, PartialEq, Eq)]
374pub enum CryptoError {
375 Decryption(aead::Error),
376 HmacVerification(MacError),
377}
378
379impl From<bincode::Error> for LbErr {
380 fn from(err: bincode::Error) -> Self {
381 core_err_unexpected(err).into()
382 }
383}
384
385pub fn core_err_unexpected<T: fmt::Debug>(err: T) -> LbErrKind {
386 LbErrKind::Unexpected(format!("{err:?}"))
387}
388
389pub fn unexpected<T: fmt::Debug>(err: T) -> LbErr {
391 LbErrKind::Unexpected(format!("{err:?}")).into()
392}
393
394impl From<DbError> for LbErr {
395 fn from(err: DbError) -> Self {
396 core_err_unexpected(err).into()
397 }
398}
399
400impl<G> From<PoisonError<G>> for LbErr {
401 fn from(err: PoisonError<G>) -> Self {
402 core_err_unexpected(err).into()
403 }
404}
405
406impl From<io::Error> for LbErr {
407 fn from(e: io::Error) -> Self {
408 match e.kind() {
409 io::ErrorKind::NotFound
410 | io::ErrorKind::PermissionDenied
411 | io::ErrorKind::InvalidInput => LbErrKind::DiskPathInvalid,
412 io::ErrorKind::AlreadyExists => LbErrKind::DiskPathTaken,
413 _ => core_err_unexpected(e),
414 }
415 .into()
416 }
417}
418
419impl From<serde_json::Error> for LbErr {
420 fn from(err: serde_json::Error) -> Self {
421 LbErrKind::Unexpected(format!("{err}")).into()
422 }
423}
424
425impl From<ApiError<api::NewAccountError>> for LbErr {
426 fn from(err: ApiError<api::NewAccountError>) -> Self {
427 match err {
428 ApiError::SendFailed(_) => LbErrKind::ServerUnreachable,
429 ApiError::ClientUpdateRequired => LbErrKind::ClientUpdateRequired,
430 ApiError::Endpoint(api::NewAccountError::UsernameTaken) => LbErrKind::UsernameTaken,
431 ApiError::Endpoint(api::NewAccountError::InvalidUsername) => LbErrKind::UsernameInvalid,
432 ApiError::Endpoint(api::NewAccountError::Disabled) => LbErrKind::ServerDisabled,
433 e => core_err_unexpected(e),
434 }
435 .into()
436 }
437}
438
439impl From<ApiError<api::NewSubAccountError>> for LbErr {
440 fn from(err: ApiError<api::NewSubAccountError>) -> Self {
441 use api::NewSubAccountError::*;
442 match err {
443 ApiError::SendFailed(_) => LbErrKind::ServerUnreachable,
444 ApiError::ClientUpdateRequired => LbErrKind::ClientUpdateRequired,
445 ApiError::Endpoint(UsernameTaken) => LbErrKind::UsernameTaken,
446 ApiError::Endpoint(InvalidUsername) => LbErrKind::UsernameInvalid,
447 ApiError::Endpoint(Disabled) => LbErrKind::ServerDisabled,
448 ApiError::Endpoint(NotPremium) => LbErrKind::NotPremium,
449 ApiError::Endpoint(NotPermissioned) => LbErrKind::InsufficientPermission,
450 ApiError::Endpoint(CounterIncorrect) => LbErrKind::TryAgain,
451 e => core_err_unexpected(e),
452 }
453 .into()
454 }
455}
456
457impl From<ApiError<api::ListSubAccountsError>> for LbErr {
458 fn from(err: ApiError<api::ListSubAccountsError>) -> Self {
459 match err {
460 ApiError::SendFailed(_) => LbErrKind::ServerUnreachable,
461 ApiError::ClientUpdateRequired => LbErrKind::ClientUpdateRequired,
462 e => core_err_unexpected(e),
463 }
464 .into()
465 }
466}
467
468impl From<ApiError<api::DeleteSubAccountError>> for LbErr {
469 fn from(err: ApiError<api::DeleteSubAccountError>) -> Self {
470 match err {
471 ApiError::SendFailed(_) => LbErrKind::ServerUnreachable,
472 ApiError::ClientUpdateRequired => LbErrKind::ClientUpdateRequired,
473 ApiError::Endpoint(api::DeleteSubAccountError::UserNotFound) => {
474 LbErrKind::UsernameNotFound
475 }
476 e => core_err_unexpected(e),
477 }
478 .into()
479 }
480}
481
482impl From<ApiError<api::GetPublicKeyError>> for LbErr {
483 fn from(err: ApiError<api::GetPublicKeyError>) -> Self {
484 match err {
485 ApiError::SendFailed(_) => LbErrKind::ServerUnreachable,
486 ApiError::ClientUpdateRequired => LbErrKind::ClientUpdateRequired,
487 ApiError::Endpoint(api::GetPublicKeyError::UserNotFound) => {
488 LbErrKind::AccountNonexistent
489 }
490 e => core_err_unexpected(e),
491 }
492 .into()
493 }
494}
495
496impl From<ApiError<api::GetUsernameError>> for LbErr {
497 fn from(err: ApiError<api::GetUsernameError>) -> Self {
498 match err {
499 ApiError::SendFailed(_) => LbErrKind::ServerUnreachable,
500 ApiError::ClientUpdateRequired => LbErrKind::ClientUpdateRequired,
501 ApiError::Endpoint(api::GetUsernameError::UserNotFound) => {
502 LbErrKind::AccountNonexistent
503 }
504 e => core_err_unexpected(e),
505 }
506 .into()
507 }
508}
509
510impl From<ApiError<api::GetFileIdsError>> for LbErr {
511 fn from(e: ApiError<api::GetFileIdsError>) -> Self {
512 match e {
513 ApiError::SendFailed(_) => LbErrKind::ServerUnreachable,
514 ApiError::ClientUpdateRequired => LbErrKind::ClientUpdateRequired,
515 e => core_err_unexpected(e),
516 }
517 .into()
518 }
519}
520
521impl From<ApiError<api::GetUpdatesError>> for LbErr {
522 fn from(e: ApiError<api::GetUpdatesError>) -> Self {
523 match e {
524 ApiError::SendFailed(_) => LbErrKind::ServerUnreachable,
525 ApiError::ClientUpdateRequired => LbErrKind::ClientUpdateRequired,
526 e => core_err_unexpected(e),
527 }
528 .into()
529 }
530}
531
532impl From<ApiError<api::GetDocumentError>> for LbErr {
533 fn from(e: ApiError<api::GetDocumentError>) -> Self {
534 match e {
535 ApiError::SendFailed(_) => LbErrKind::ServerUnreachable,
536 ApiError::Endpoint(api::GetDocumentError::DocumentNotFound) => {
537 LbErrKind::FileNonexistent
538 }
539 ApiError::Endpoint(api::GetDocumentError::NotPermissioned) => {
540 LbErrKind::InsufficientPermission
541 }
542 ApiError::ClientUpdateRequired => LbErrKind::ClientUpdateRequired,
543 e => core_err_unexpected(e),
544 }
545 .into()
546 }
547}
548
549impl From<ApiError<api::UpsertError>> for LbErr {
550 fn from(e: ApiError<api::UpsertError>) -> Self {
551 match e {
552 ApiError::SendFailed(_) => LbErrKind::ServerUnreachable,
553 ApiError::Endpoint(api::UpsertError::UsageIsOverDataCap) => {
554 LbErrKind::UsageIsOverDataCap
555 }
556 ApiError::ClientUpdateRequired => LbErrKind::ClientUpdateRequired,
557 e => core_err_unexpected(e),
558 }
559 .into()
560 }
561}
562
563impl From<ApiError<api::UpsertDebugInfoError>> for LbErr {
564 fn from(e: ApiError<api::UpsertDebugInfoError>) -> Self {
565 match e {
566 ApiError::SendFailed(_) => LbErrKind::ServerUnreachable,
567 ApiError::ClientUpdateRequired => LbErrKind::ClientUpdateRequired,
568 e => core_err_unexpected(e),
569 }
570 .into()
571 }
572}
573
574impl From<ApiError<api::ChangeDocError>> for LbErr {
575 fn from(e: ApiError<api::ChangeDocError>) -> Self {
576 match e {
577 ApiError::SendFailed(_) => LbErrKind::ServerUnreachable,
578 ApiError::Endpoint(api::ChangeDocError::UsageIsOverDataCap) => {
579 LbErrKind::UsageIsOverDataCap
580 }
581 ApiError::ClientUpdateRequired => LbErrKind::ClientUpdateRequired,
582 e => core_err_unexpected(e),
583 }
584 .into()
585 }
586}
587
588impl From<ApiError<api::GetUsageError>> for LbErr {
589 fn from(e: ApiError<api::GetUsageError>) -> Self {
590 match e {
591 ApiError::SendFailed(_) => LbErrKind::ServerUnreachable,
592 ApiError::ClientUpdateRequired => LbErrKind::ClientUpdateRequired,
593 e => core_err_unexpected(e),
594 }
595 .into()
596 }
597}
598
599#[derive(Debug, Clone, Serialize)]
600pub enum Warning {
601 EmptyFile(Uuid),
602 InvalidUTF8(Uuid),
603}
604
605impl fmt::Display for Warning {
606 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
607 match self {
608 Self::EmptyFile(id) => write!(f, "empty file: {id}"),
609 Self::InvalidUTF8(id) => write!(f, "invalid utf8 in file: {id}"),
610 }
611 }
612}