1use std::borrow::Cow;
21
22pub mod tolerant;
23pub(crate) mod wire;
24
25#[derive(Debug, Clone, Copy)]
27pub struct QuirkContext<'a> {
28 pub hbci_version: &'a str,
30 pub dialog_id: &'a str,
32 pub message_number: u16,
34}
35
36pub trait Quirk: Send + Sync {
42 fn name(&self) -> &'static str;
44
45 fn incoming_raw<'a>(&self, msg: &'a [u8], _ctx: &QuirkContext<'_>) -> Cow<'a, [u8]> {
47 Cow::Borrowed(msg)
48 }
49
50 fn incoming<'a>(&self, msg: &'a [u8], _ctx: &QuirkContext<'_>) -> Cow<'a, [u8]> {
52 Cow::Borrowed(msg)
53 }
54
55 fn outgoing<'a>(&self, msg: &'a [u8], _ctx: &QuirkContext<'_>) -> Cow<'a, [u8]> {
57 Cow::Borrowed(msg)
58 }
59}
60
61pub struct QuirkChain {
63 quirks: Vec<Box<dyn Quirk>>,
64}
65
66#[derive(Debug, Clone, Copy)]
68enum Stage {
69 Raw,
70 ClearText,
71 Outgoing,
72}
73
74impl Stage {
75 fn apply<'a>(self, quirk: &dyn Quirk, msg: &'a [u8], ctx: &QuirkContext<'_>) -> Cow<'a, [u8]> {
76 match self {
77 Self::Raw => quirk.incoming_raw(msg, ctx),
78 Self::ClearText => quirk.incoming(msg, ctx),
79 Self::Outgoing => quirk.outgoing(msg, ctx),
80 }
81 }
82}
83
84impl std::fmt::Debug for QuirkChain {
85 fn fmt(&self, out: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86 out.debug_tuple("QuirkChain").field(&self.names()).finish()
87 }
88}
89
90impl Default for QuirkChain {
91 fn default() -> Self {
96 let mut chain = Self::none();
97 chain.quirks = vec![
98 Box::new(tolerant::MissingMessageReference),
99 Box::new(tolerant::HeaderVersion),
100 Box::new(tolerant::StatusSegmentOrder),
101 Box::new(tolerant::SegmentNumbering),
102 ];
103 chain
104 }
105}
106
107impl QuirkChain {
108 pub fn none() -> Self {
110 Self { quirks: Vec::new() }
111 }
112
113 pub fn with(mut self, quirk: impl Quirk + 'static) -> Self {
116 self.quirks.push(Box::new(quirk));
117 self
118 }
119
120 pub fn names(&self) -> Vec<&'static str> {
122 self.quirks.iter().map(|quirk| quirk.name()).collect()
123 }
124
125 pub fn incoming(&self, raw: &[u8], ctx: &QuirkContext<'_>) -> Vec<u8> {
127 let repaired = self.run(Stage::Raw, raw.to_vec(), ctx);
128 self.run(Stage::ClearText, unwrap_envelope(&repaired), ctx)
129 }
130
131 pub fn outgoing(&self, msg: &[u8], ctx: &QuirkContext<'_>) -> Vec<u8> {
133 self.run(Stage::Outgoing, msg.to_vec(), ctx)
134 }
135
136 fn run(&self, stage: Stage, mut msg: Vec<u8>, ctx: &QuirkContext<'_>) -> Vec<u8> {
137 for quirk in &self.quirks {
138 if let Cow::Owned(repaired) = stage.apply(quirk.as_ref(), &msg, ctx) {
139 tracing::warn!(
140 quirk = quirk.name(),
141 ?stage,
142 "[FinTS] bank message repaired"
143 );
144 msg = repaired;
145 }
146 }
147 msg
148 }
149}
150
151pub(crate) fn unwrap_envelope(msg: &[u8]) -> Vec<u8> {
155 let mut clear = Vec::with_capacity(msg.len());
156 for segment in wire::segments(msg).into_iter().map(|range| &msg[range]) {
157 let keep = match wire::segment_type(segment) {
158 b"HNVSK" => continue,
159 b"HNVSD" => encrypted_data(segment).unwrap_or(segment),
160 _ => segment,
161 };
162 clear.extend_from_slice(keep);
163 }
164 clear
165}
166
167fn encrypted_data(hnvsd: &[u8]) -> Option<&[u8]> {
169 let group = wire::degs(hnvsd).into_iter().nth(1)?;
170 wire::binary_payload(&hnvsd[group])
171}
172
173#[cfg(test)]
174mod tests {
175 use super::*;
176
177 const CTX: QuirkContext<'static> = QuirkContext {
178 hbci_version: "300",
179 dialog_id: "D-1",
180 message_number: 3,
181 };
182
183 const HEAD: &str = "HNHBK:1:3+000000000120+300+D-1+3+D-1:3'";
184
185 fn enveloped(inner: &str) -> Vec<u8> {
186 format!(
187 "{HEAD}HNVSK:998:3+PIN:2+998+1+2::sys+1:20260101:120000+2:2:13:@8@00000000:5:1+280:10000000:user:V:0:0+0'\
188 HNVSD:999:1+@{}@{inner}'HNHBS:5:1+3'",
189 inner.len()
190 )
191 .into_bytes()
192 }
193
194 #[test]
195 fn envelope_is_replaced_by_its_content() {
196 let inner =
197 "HIRMG:2:2+0010::Nachricht entgegengenommen.'HIRMS:3:2:3+0020::Auftrag ausgeführt.'";
198 let clear = format!("{HEAD}{inner}HNHBS:5:1+3'");
199 assert_eq!(unwrap_envelope(&enveloped(inner)), clear.as_bytes());
200 }
201
202 #[test]
203 fn answer_without_envelope_is_unchanged() {
204 let plain = format!("{HEAD}HIRMG:2:2+9800::Dialog abgebrochen.'HNHBS:3:1+3'");
205 assert_eq!(unwrap_envelope(plain.as_bytes()), plain.as_bytes());
206 }
207
208 #[test]
209 fn default_chain_leaves_a_sound_answer_alone() {
210 let inner = "HIRMG:2:2+0010::ok'HIRMS:3:2:3+0020::ok'HISAL:4:7:3+x'";
211 let clear = format!("{HEAD}{inner}HNHBS:5:1+3'");
212 let chain = QuirkChain::default();
213 assert_eq!(chain.incoming(&enveloped(inner), &CTX), clear.as_bytes());
214 assert_eq!(chain.outgoing(clear.as_bytes(), &CTX), clear.as_bytes());
215 }
216
217 struct XToY(Stage);
219
220 impl XToY {
221 fn swap<'a>(&self, stage: Stage, msg: &'a [u8]) -> Cow<'a, [u8]> {
222 let wanted = std::mem::discriminant(&self.0) == std::mem::discriminant(&stage);
223 if wanted && msg.contains(&b'x') {
224 Cow::Owned(
225 msg.iter()
226 .map(|&b| if b == b'x' { b'y' } else { b })
227 .collect(),
228 )
229 } else {
230 Cow::Borrowed(msg)
231 }
232 }
233 }
234
235 impl Quirk for XToY {
236 fn name(&self) -> &'static str {
237 "XToY"
238 }
239 fn incoming_raw<'a>(&self, msg: &'a [u8], _: &QuirkContext<'_>) -> Cow<'a, [u8]> {
240 self.swap(Stage::Raw, msg)
241 }
242 fn incoming<'a>(&self, msg: &'a [u8], _: &QuirkContext<'_>) -> Cow<'a, [u8]> {
243 self.swap(Stage::ClearText, msg)
244 }
245 fn outgoing<'a>(&self, msg: &'a [u8], _: &QuirkContext<'_>) -> Cow<'a, [u8]> {
246 self.swap(Stage::Outgoing, msg)
247 }
248 }
249
250 #[test]
251 fn each_stage_sees_its_own_form_of_the_message() {
252 let answer = enveloped("HIRMG:2:2+0010::x'");
253 let raw = QuirkChain::none()
256 .with(XToY(Stage::Raw))
257 .incoming(&answer, &CTX);
258 assert!(raw.windows(9).any(|w| w == b"0010::y'H"));
259 let clear = QuirkChain::none()
261 .with(XToY(Stage::ClearText))
262 .incoming(&answer, &CTX);
263 assert!(!clear.windows(5).any(|w| w == b"HNVSK"));
264 assert!(clear.windows(8).any(|w| w == b"0010::y'"));
265 let out_only = QuirkChain::none().with(XToY(Stage::Outgoing));
267 assert!(out_only.incoming(&answer, &CTX).contains(&b'x'));
268 assert_eq!(out_only.outgoing(b"x", &CTX), b"y");
269 }
270
271 #[test]
272 fn names_in_order() {
273 assert!(QuirkChain::none().names().is_empty());
274 let chain = QuirkChain::default().with(XToY(Stage::Raw));
275 let names = chain.names();
276 assert_eq!(names.len(), 5);
277 assert_eq!(names.first(), Some(&"MissingMessageReference"));
278 assert_eq!(names.last(), Some(&"XToY"));
279 }
280}