iso14229-1 0.1.0

A ISO 14229-1 protocol.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! response of Service 38

use crate::{
    error::Error,
    response::{Code, Response, SubFunction},
    utils, DataFormatIdentifier, Configuration, LengthFormatIdentifier, ModeOfOperation,
    ResponseData, Service,
};
use std::{collections::HashSet, sync::LazyLock};

pub static REQUEST_FILE_TRANSFER_NEGATIVES: LazyLock<HashSet<Code>> = LazyLock::new(|| {
    HashSet::from([
        Code::IncorrectMessageLengthOrInvalidFormat,
        Code::ConditionsNotCorrect,
        #[cfg(any(feature = "std2020"))]
        Code::RequestSequenceError, // ResumeFile only
        Code::RequestOutOfRange,
        Code::SecurityAccessDenied,
        #[cfg(any(feature = "std2020"))]
        Code::AuthenticationRequired,
        Code::UploadDownloadNotAccepted,
    ])
});

/*
// Specifies the length (number of bytes) of the maxNumberOfBlockLength parameter.
// If the modeOfOperation parameter equals to 02 (DeleteFile) this parameter shall not be included in the
// response message.
// */
// lengthFormatIdentifier
/*
This parameter is used by the requestFileTransfer positive response message to inform the client how many
data bytes (maxNumberOfBlockLength) to include in each TransferData request message from the client or how
many data bytes the server will include in a TransferData positive response when uploading data. This length
reflects the complete message length, including the service identifier and the data parameters present in the
TransferData request message or positive response message. This parameter allows either the client to adapt to
the receive buffer size of the server before it starts transferring data to the server or to indicate how many data
bytes will be included in each TransferData positive response in the event that data is uploaded. A server is
required to accept transferData requests that are equal in length to its reported maxNumberOfBlockLength. It is
server specific what transferData request lengths less than maxNumberOfBlockLength are accepted (if any).
NOTE The last transferData request within a given block can be required to be less than
maxNumberOfBlockLength. It is not allowed for a server to write additional data bytes (i.e. pad bytes) not
contained within the transferData message (either in a compressed or uncompressed format), as this would
affect the memory address of where the subsequent transferData request data would be written.
If the modeOfOperation parameter equals to 02 (DeleteFile) this parameter shall be not be included in the
response message.
*/
// maxNumberOfBlockLength
/*
This is parameter echoes the value of the request.
If the modeOfOperation parameter equals to 02 (DeleteFile) this parameter shall not be included in the
response message.)
If the modeOfOperation parameter equals to 05 (ReadDir) the value of this parameter shall be equal to 00.
*/
// dataFormatIdentifier
/*
Specifies the length in bytes for both parameters fileSizeUncompressedOrDirInfoLength and fileSizeCompressed.
If the modeOfOperation parameter equals to 01 (AddFile), 02 (DeleteFile), 03 (ReplaceFile) or 06 (ResumeFile)
this parameter shall not be included in the response message.
*/
// fileSizeOrDirInfoParameterLength
/*
Specifies the length in bytes for both parameters fileSizeUncompressedOrDirInfoLength and fileSizeCompressed.
If the modeOfOperation parameter equals to 01 (AddFile), 02 (DeleteFile), 03 (ReplaceFile) or 06 ResumeFile)
this parameter shall not be included in the response message.
*/
// fileSizeUncompressedOrDirInfoLength
/*
Specifies the size of the compressed file in bytes.
If the modeOfOperation parameter equals to 01 (AddFile), 02 (DeleteFile, 03 (ReplaceFile)), 05 (ReadDir)
or 06 (ResumeFile) this parameter shall not be included in the response message.
*/
// fileSizeCompressed
/*
Specifies the byte position within the file at which the Tester will resume downloading after an initial download
is suspended. A download is suspended when the ECU stops receiving TransferData requests and does not
receive the RequestTransferExit request before returning to the defaultSession.
The filePosition is relative to the compressed size or uncompressed size, depending if the file was originally sent
compressed or uncompressed during the initiating ModeOfOperation = AddFile or ReplaceFile.
If the modeOfOperation parameter equals to 01 (AddFile), 02 (DeleteFile), 03 (ReplaceFile), 04 (ReadFile),
or 05 (ReadDir) this parameter shall not be included in the request.
*/
// filePosition
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum RequestFileTransfer {
    AddFile {
        // 1 modeOfOperation
        lfi: LengthFormatIdentifier,
        max_block_len: u128,
        dfi: DataFormatIdentifier,
    },
    DeleteFile, // 2 modeOfOperation
    ReplaceFile {
        // 3 modeOfOperation
        lfi: LengthFormatIdentifier,
        max_block_len: u128,
        dfi: DataFormatIdentifier,
    },
    ReadFile {
        // 4 modeOfOperation
        lfi: LengthFormatIdentifier,
        max_block_len: u128,
        dfi: DataFormatIdentifier,
        filesize_or_dir_param_len: u16,
        uncompressed_size_or_dir_len: u128,
        compressed_size: u128,
    },
    ReadDir {
        // 5 modeOfOperation
        lfi: LengthFormatIdentifier,
        max_block_len: u128,
        dfi: DataFormatIdentifier, // always 0x00
        filesize_or_dir_param_len: u16,
        uncompressed_size_or_dir_len: u128,
    },
    ResumeFile {
        // 6 modeOfOperation
        lfi: LengthFormatIdentifier,
        max_block_len: u128,
        dfi: DataFormatIdentifier,
        file_pos: [u8; 8],
    },
}

impl From<RequestFileTransfer> for Vec<u8> {
    fn from(v: RequestFileTransfer) -> Self {
        let mut result = Vec::new();
        match v {
            RequestFileTransfer::AddFile {
                lfi,
                max_block_len,
                dfi,
            } => {
                result.push(lfi.into());
                result.extend(utils::u128_to_vec(
                    max_block_len,
                    lfi.max_number_of_block_length(),
                ));
                result.push(dfi.into());
            }
            RequestFileTransfer::DeleteFile => {}
            RequestFileTransfer::ReplaceFile {
                lfi,
                max_block_len,
                dfi,
            } => {
                result.push(lfi.into());
                result.extend(utils::u128_to_vec(
                    max_block_len,
                    lfi.max_number_of_block_length(),
                ));
                result.push(dfi.into());
            }
            RequestFileTransfer::ReadFile {
                lfi,
                max_block_len,
                dfi,
                filesize_or_dir_param_len,
                uncompressed_size_or_dir_len,
                compressed_size,
            } => {
                result.push(lfi.into());
                result.extend(utils::u128_to_vec(
                    max_block_len,
                    lfi.max_number_of_block_length(),
                ));
                result.push(dfi.into());
                result.extend(filesize_or_dir_param_len.to_be_bytes());
                result.extend(utils::u128_to_vec_fix(uncompressed_size_or_dir_len));
                result.extend(utils::u128_to_vec_fix(compressed_size));
            }
            RequestFileTransfer::ReadDir {
                lfi,
                max_block_len,
                dfi,
                filesize_or_dir_param_len,
                uncompressed_size_or_dir_len,
            } => {
                result.push(lfi.into());
                result.extend(utils::u128_to_vec(
                    max_block_len,
                    lfi.max_number_of_block_length(),
                ));
                result.push(dfi.into());
                result.extend(filesize_or_dir_param_len.to_be_bytes());
                result.extend(utils::u128_to_vec_fix(uncompressed_size_or_dir_len));
            }
            RequestFileTransfer::ResumeFile {
                lfi,
                max_block_len,
                dfi,
                file_pos,
            } => {
                result.push(lfi.into());
                result.extend(utils::u128_to_vec(
                    max_block_len,
                    lfi.max_number_of_block_length(),
                ));
                result.push(dfi.into());
                result.extend(file_pos);
            }
        }

        result
    }
}

impl ResponseData for RequestFileTransfer {
    fn new_response<T: AsRef<[u8]>>(
        data: T,
        sub_func: Option<u8>,
        _: &Configuration,
    ) -> Result<Response, Error> {
        let data = data.as_ref();
        match sub_func {
            Some(sub_func) => {
                let data_len = data.len();
                match ModeOfOperation::try_from(sub_func)? {
                    ModeOfOperation::AddFile => utils::data_length_check(data_len, 2, false)?,
                    ModeOfOperation::DeleteFile => utils::data_length_check(data_len, 1, true)?,
                    ModeOfOperation::ReplaceFile => utils::data_length_check(data_len, 2, false)?,
                    ModeOfOperation::ReadFile => utils::data_length_check(data_len, 2, false)?,
                    ModeOfOperation::ReadDir => utils::data_length_check(data_len, 2, false)?,
                    ModeOfOperation::ResumeFile => utils::data_length_check(data_len, 2, false)?,
                }

                Ok(Response {
                    service: Service::RequestFileTransfer,
                    negative: false,
                    sub_func: Some(SubFunction::new(sub_func)),
                    data: data.to_vec(),
                })
            }
            None => Err(Error::SubFunctionError(Service::RequestFileTransfer)),
        }
    }
}

impl TryFrom<(&Response, &Configuration)> for RequestFileTransfer {
    type Error = Error;
    fn try_from((resp, _): (&Response, &Configuration)) -> Result<Self, Self::Error> {
        let service = resp.service();
        if service != Service::RequestFileTransfer || resp.sub_func.is_none() {
            return Err(Error::ServiceError(service));
        }

        let sub_func: ModeOfOperation = resp.sub_function().unwrap().function()?;
        let data = &resp.data;
        let data_len = data.len();
        let mut offset = 0;
        match sub_func {
            ModeOfOperation::AddFile => {
                utils::data_length_check(data_len, offset + 1, false)?;

                let lfi = LengthFormatIdentifier::try_from(data[offset])?;
                offset += 1;
                utils::data_length_check(
                    data_len,
                    offset + lfi.max_number_of_block_length() + 1,
                    true,
                )?;

                let max_block_len =
                    utils::slice_to_u128(&data[offset..offset + lfi.max_number_of_block_length()]);
                offset += lfi.max_number_of_block_length();
                let dfi = DataFormatIdentifier::from(data[offset]);
                Ok(Self::AddFile {
                    lfi,
                    max_block_len,
                    dfi,
                })
            }
            ModeOfOperation::DeleteFile => Ok(Self::DeleteFile),
            ModeOfOperation::ReplaceFile => {
                utils::data_length_check(data_len, offset + 1, false)?;

                let lfi = LengthFormatIdentifier::try_from(data[offset])?;
                offset += 1;
                utils::data_length_check(
                    data_len,
                    offset + lfi.max_number_of_block_length() + 1,
                    true,
                )?;

                let max_block_len =
                    utils::slice_to_u128(&data[offset..offset + lfi.max_number_of_block_length()]);
                offset += lfi.max_number_of_block_length();
                let dfi = DataFormatIdentifier::from(data[offset]);
                Ok(Self::ReplaceFile {
                    lfi,
                    max_block_len,
                    dfi,
                })
            }
            ModeOfOperation::ReadFile => {
                utils::data_length_check(data_len, offset + 1, false)?;

                let lfi = LengthFormatIdentifier::try_from(data[offset])?;
                offset += 1;
                utils::data_length_check(
                    data_len,
                    offset + lfi.max_number_of_block_length() + 4,
                    false,
                )?;

                let max_block_len =
                    utils::slice_to_u128(&data[offset..offset + lfi.max_number_of_block_length()]);
                offset += lfi.max_number_of_block_length();

                let dfi = DataFormatIdentifier::from(data[offset]);
                offset += 1;

                let filesize_or_dir_param_len =
                    u16::from_be_bytes([data[offset], data[offset + 1]]);
                offset += 2;

                utils::data_length_check(
                    data_len,
                    offset + filesize_or_dir_param_len as usize + 1,
                    false,
                )?;

                let uncompressed_size_or_dir_len = utils::slice_to_u128(
                    &data[offset..offset + filesize_or_dir_param_len as usize],
                );
                offset += filesize_or_dir_param_len as usize;

                let compressed_size = utils::slice_to_u128(&data[offset..]);

                Ok(Self::ReadFile {
                    lfi,
                    max_block_len,
                    dfi,
                    filesize_or_dir_param_len,
                    uncompressed_size_or_dir_len,
                    compressed_size,
                })
            }
            ModeOfOperation::ReadDir => {
                utils::data_length_check(data_len, offset + 1, false)?;

                let lfi = LengthFormatIdentifier::try_from(data[offset])?;
                offset += 1;
                utils::data_length_check(
                    data_len,
                    offset + lfi.max_number_of_block_length() + 4,
                    false,
                )?;

                let max_block_len =
                    utils::slice_to_u128(&data[offset..offset + lfi.max_number_of_block_length()]);
                offset += lfi.max_number_of_block_length();

                let dfi = data[offset];
                offset += 1;
                if dfi != 0x00 {
                    return Err(Error::InvalidData(hex::encode(data)));
                }
                let dfi = DataFormatIdentifier(dfi);

                let filesize_or_dir_param_len =
                    u16::from_be_bytes([data[offset], data[offset + 1]]);
                offset += 2;
                let uncompressed_size_or_dir_len = utils::slice_to_u128(
                    &data[offset..offset + filesize_or_dir_param_len as usize],
                );

                Ok(Self::ReadDir {
                    lfi,
                    max_block_len,
                    dfi,
                    filesize_or_dir_param_len,
                    uncompressed_size_or_dir_len,
                })
            }
            ModeOfOperation::ResumeFile => {
                utils::data_length_check(data_len, offset + 1, false)?;

                let lfi = LengthFormatIdentifier::try_from(data[offset])?;
                offset += 1;
                utils::data_length_check(
                    data_len,
                    offset + lfi.max_number_of_block_length() + 9,
                    true,
                )?;

                let max_block_len =
                    utils::slice_to_u128(&data[offset..offset + lfi.max_number_of_block_length()]);
                offset += lfi.max_number_of_block_length();
                let dfi = DataFormatIdentifier::from(data[offset]);
                offset += 1;
                let file_pos = <[u8; 8]>::try_from(&data[offset..])
                    .map_err(|_| Error::InvalidData(hex::encode(data)))?;

                Ok(Self::ResumeFile {
                    lfi,
                    max_block_len,
                    dfi,
                    file_pos,
                })
            }
        }
    }
}