Debian Codegraph @

src/nitrokey/trussed/_bootloader/nrf52_upload/dfu/dfu_transport.py

raw
1 # Copyright (c) 2016 - 2019 Nordic Semiconductor ASA
2 # All rights reserved.
3 #
4 # Redistribution and use in source and binary forms, with or without modification,
5 # are permitted provided that the following conditions are met:
6 #
7 # 1. Redistributions of source code must retain the above copyright notice, this
8 # list of conditions and the following disclaimer.
9 #
10 # 2. Redistributions in binary form must reproduce the above copyright notice, this
11 # list of conditions and the following disclaimer in the documentation and/or
12 # other materials provided with the distribution.
13 #
14 # 3. Neither the name of Nordic Semiconductor ASA nor the names of other
15 # contributors to this software may be used to endorse or promote products
16 # derived from this software without specific prior written permission.
17 #
18 # 4. This software must only be used in or with a processor manufactured by Nordic
19 # Semiconductor ASA, or in or with a processor manufactured by a third party that
20 # is used in combination with a processor manufactured by Nordic Semiconductor.
21 #
22 # 5. Any software provided in binary or object form under this license must not be
23 # reverse engineered, decompiled, modified and/or disassembled.
24 #
25 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
26 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
27 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
28 # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
29 # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
30 # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
32 # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
34 # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35
36 import logging
37 from abc import ABC, abstractmethod
38 from typing import Any, Callable
39
40 # Nordic Semiconductor imports
41
42 logger = logging.getLogger(__name__)
43
44
45 # Custom logging level for logging all transport events, including all bytes
46 # being transported over the wire or over the air.
47 # Note that this logging level is more verbose than logging.DEBUG.
48 TRANSPORT_LOGGING_LEVEL = 5
49
50
51 class DfuEvent:
52 PROGRESS_EVENT = 1
53
54
55 class DfuTransport(ABC):
56 """
57 This class as an abstract base class inherited from when implementing transports.
58
59 The class is generic in nature, the underlying implementation may have missing semantic
60 than this class describes. But the intent is that the implementer shall follow the semantic as
61 best as she can.
62 """
63
64 OP_CODE = {
65 "CreateObject": 0x01,
66 "SetPRN": 0x02,
67 "CalcChecSum": 0x03,
68 "Execute": 0x04,
69 "ReadObject": 0x06,
70 "Response": 0x60,
71 }
72
73 RES_CODE = {
74 "InvalidCode": 0x00,
75 "Success": 0x01,
76 "NotSupported": 0x02,
77 "InvalidParameter": 0x03,
78 "InsufficientResources": 0x04,
79 "InvalidObject": 0x05,
80 "InvalidSignature": 0x06,
81 "UnsupportedType": 0x07,
82 "OperationNotPermitted": 0x08,
83 "OperationFailed": 0x0A,
84 "ExtendedError": 0x0B,
85 }
86
87 EXT_ERROR_CODE = [
88 "No extended error code has been set. This error indicates an implementation problem.",
89 "Invalid error code. This error code should never be used outside of development.",
90 "The format of the command was incorrect. This error code is not used in the current implementation, because @ref NRF_DFU_RES_CODE_OP_CODE_NOT_SUPPORTED and @ref NRF_DFU_RES_CODE_INVALID_PARAMETER cover all possible format errors.",
91 "The command was successfully parsed, but it is not supported or unknown.",
92 "The init command is invalid. The init packet either has an invalid update type or it is missing required fields for the update type (for example, the init packet for a SoftDevice update is missing the SoftDevice size field).",
93 "The firmware version is too low. For an application, the version must be greater than or equal to the current application. For a bootloader, it must be greater than the current version. This requirement prevents downgrade attacks."
94 "",
95 "The hardware version of the device does not match the required hardware version for the update.",
96 "The array of supported SoftDevices for the update does not contain the FWID of the current SoftDevice.",
97 "The init packet does not contain a signature, but this bootloader requires all updates to have one.",
98 "The hash type that is specified by the init packet is not supported by the DFU bootloader.",
99 "The hash of the firmware image cannot be calculated.",
100 "The type of the signature is unknown or not supported by the DFU bootloader.",
101 "The hash of the received firmware image does not match the hash in the init packet.",
102 "The available space on the device is insufficient to hold the firmware.",
103 "The requested firmware to update was already present on the system.",
104 ]
105
106 @abstractmethod
107 def __init__(self) -> None:
108 self.callbacks: dict[int, list[Callable[..., None]]] = {}
109
110 @abstractmethod
111 def open(self) -> None:
112 """
113 Open a port if appropriate for the transport.
114 :return:
115 """
116 pass
117
118 @abstractmethod
119 def close(self) -> None:
120 """
121 Close a port if appropriate for the transport.
122 :return:
123 """
124 pass
125
126 @abstractmethod
127 def send_init_packet(self, init_packet: bytes) -> None:
128 """
129 Send init_packet to device.
130
131 This call will block until init_packet is sent and transfer of packet is complete.
132
133 :param init_packet: Init packet as a str.
134 :return:
135 """
136 pass
137
138 @abstractmethod
139 def send_firmware(self, firmware: bytes) -> None:
140 """
141 Start sending firmware to device.
142
143 This call will block until transfer of firmware is complete.
144
145 :param firmware:
146 :return:
147 """
148 pass
149
150 def register_events_callback(self, event_type: int, callback: Callable[..., None]) -> None:
151 """
152 Register a callback.
153
154 :param DfuEvent callback:
155 :return: None
156 """
157 if event_type not in self.callbacks:
158 self.callbacks[event_type] = []
159
160 self.callbacks[event_type].append(callback)
161
162 def _send_event(self, event_type: int, **kwargs: Any) -> None:
163 """
164 Method for sending events to registered callbacks.
165
166 If callbacks throws exceptions event propagation will stop and this method be part of the track trace.
167
168 :param DfuEvent event_type:
169 :param kwargs: Arguments to callback function
170 :return:
171 """
172 if event_type in list(self.callbacks.keys()):
173 for callback in self.callbacks[event_type]:
174 callback(**kwargs)