lib.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. #![cfg_attr(not(any(test, feature = "std")), no_std)]
  2. #![deny(unsafe_code)]
  3. //! The _smoltcp_ library is built in a layered structure, with the layers corresponding
  4. //! to the levels of API abstraction. Only the highest layers would be used by a typical
  5. //! application; however, the goal of _smoltcp_ is not just to provide a simple interface
  6. //! for writing applications but also to be a toolbox of networking primitives, so
  7. //! every layer is fully exposed and documented.
  8. //!
  9. //! When discussing networking stacks and layering, often the [OSI model][osi] is invoked.
  10. //! _smoltcp_ makes no effort to conform to the OSI model as it is not applicable to TCP/IP.
  11. //!
  12. //! # The socket layer
  13. //! The socket layer APIs are provided in the module [socket](socket/index.html); currently,
  14. //! raw, ICMP, TCP, and UDP sockets are provided. The socket API provides the usual primitives,
  15. //! but necessarily differs in many from the [Berkeley socket API][berk], as the latter was
  16. //! not designed to be used without heap allocation.
  17. //!
  18. //! The socket layer provides the buffering, packet construction and validation, and (for
  19. //! stateful sockets) the state machines, but it is interface-agnostic. An application must
  20. //! use sockets together with a network interface.
  21. //!
  22. //! # The interface layer
  23. //! The interface layer APIs are provided in the module [iface](iface/index.html); currently,
  24. //! Ethernet interface is provided.
  25. //!
  26. //! The interface layer handles the control messages, physical addressing and neighbor discovery.
  27. //! It routes packets to and from sockets.
  28. //!
  29. //! # The physical layer
  30. //! The physical layer APIs are provided in the module [phy](phy/index.html); currently,
  31. //! raw socket and TAP interface are provided. In addition, two _middleware_ interfaces
  32. //! are provided: the _tracer device_, which prints a human-readable representation of packets,
  33. //! and the _fault injector device_, which randomly introduces errors into the transmitted
  34. //! and received packet sequences.
  35. //!
  36. //! The physical layer handles interaction with a platform-specific network device.
  37. //!
  38. //! # The wire layers
  39. //! Unlike the higher layers, the wire layer APIs will not be used by a typical application.
  40. //! They however are the bedrock of _smoltcp_, and everything else is built on top of them.
  41. //!
  42. //! The wire layer APIs are designed by the principle "make illegal states ir-representable".
  43. //! If a wire layer object can be constructed, then it can also be parsed from or emitted to
  44. //! a lower level.
  45. //!
  46. //! The wire layer APIs also provide _tcpdump_-like pretty printing.
  47. //!
  48. //! ## The representation layer
  49. //! The representation layer APIs are provided in the module [wire].
  50. //!
  51. //! The representation layer exists to reduce the state space of raw packets. Raw packets
  52. //! may be nonsensical in a multitude of ways: invalid checksums, impossible combinations of flags,
  53. //! pointers to fields out of bounds, meaningless options... Representations shed all that,
  54. //! as well as any features not supported by _smoltcp_.
  55. //!
  56. //! ## The packet layer
  57. //! The packet layer APIs are also provided in the module [wire].
  58. //!
  59. //! The packet layer exists to provide a more structured way to work with packets than
  60. //! treating them as sequences of octets. It makes no judgement as to content of the packets,
  61. //! except where necessary to provide safe access to fields, and strives to implement every
  62. //! feature ever defined, to ensure that, when the representation layer is unable to make sense
  63. //! of a packet, it is still logged correctly and in full.
  64. //!
  65. //! # Minimum Supported Rust Version (MSRV)
  66. //!
  67. //! This crate is guaranteed to compile on stable Rust 1.60 and up with any valid set of features.
  68. //! It *might* compile on older versions but that may change in any new patch release.
  69. //!
  70. //! The exception is when using the `defmt` feature, in which case `defmt`'s MSRV applies, which
  71. //! is higher.
  72. //!
  73. //! [wire]: wire/index.html
  74. //! [osi]: https://en.wikipedia.org/wiki/OSI_model
  75. //! [berk]: https://en.wikipedia.org/wiki/Berkeley_sockets
  76. /* XXX compiler bug
  77. #![cfg(not(any(feature = "socket-raw",
  78. feature = "socket-udp",
  79. feature = "socket-tcp")))]
  80. compile_error!("at least one socket needs to be enabled"); */
  81. #![allow(clippy::match_like_matches_macro)]
  82. #![allow(clippy::redundant_field_names)]
  83. #![allow(clippy::identity_op)]
  84. #![allow(clippy::option_map_unit_fn)]
  85. #![allow(clippy::unit_arg)]
  86. #[cfg(any(feature = "std", feature = "alloc"))]
  87. extern crate alloc;
  88. #[cfg(not(any(
  89. feature = "proto-ipv4",
  90. feature = "proto-ipv6",
  91. feature = "proto-sixlowpan"
  92. )))]
  93. compile_error!("You must enable at least one of the following features: proto-ipv4, proto-ipv6, proto-sixlowpan");
  94. #[cfg(all(
  95. feature = "socket",
  96. not(any(
  97. feature = "socket-raw",
  98. feature = "socket-udp",
  99. feature = "socket-tcp",
  100. feature = "socket-icmp",
  101. feature = "socket-dhcpv4",
  102. feature = "socket-dns",
  103. ))
  104. ))]
  105. compile_error!("If you enable the socket feature, you must enable at least one of the following features: socket-raw, socket-udp, socket-tcp, socket-icmp, socket-dhcpv4, socket-dns");
  106. #[cfg(all(
  107. feature = "socket",
  108. not(any(
  109. feature = "medium-ethernet",
  110. feature = "medium-ip",
  111. feature = "medium-ieee802154",
  112. ))
  113. ))]
  114. compile_error!("If you enable the socket feature, you must enable at least one of the following features: medium-ip, medium-ethernet, medium-ieee802154");
  115. #[cfg(all(feature = "defmt", feature = "log"))]
  116. compile_error!("You must enable at most one of the following features: defmt, log");
  117. use core::fmt;
  118. #[macro_use]
  119. mod macros;
  120. mod parsers;
  121. mod rand;
  122. #[cfg(any(
  123. feature = "medium-ethernet",
  124. feature = "medium-ip",
  125. feature = "medium-ieee802154"
  126. ))]
  127. pub mod iface;
  128. pub mod phy;
  129. #[cfg(feature = "socket")]
  130. pub mod socket;
  131. pub mod storage;
  132. pub mod time;
  133. pub mod wire;
  134. /// The error type for the networking stack.
  135. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  136. #[non_exhaustive]
  137. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  138. pub enum Error {
  139. /// An operation cannot proceed because a buffer is empty or full.
  140. Exhausted,
  141. /// An operation is not permitted in the current state.
  142. Illegal,
  143. /// An endpoint or address of a remote host could not be translated to a lower level address.
  144. /// E.g. there was no an Ethernet address corresponding to an IPv4 address in the ARP cache,
  145. /// or a TCP connection attempt was made to an unspecified endpoint.
  146. Unaddressable,
  147. /// The operation is finished.
  148. /// E.g. when reading from a TCP socket, there's no more data to read because the remote
  149. /// has closed the connection.
  150. Finished,
  151. /// An incoming packet could not be parsed because some of its fields were out of bounds
  152. /// of the received data.
  153. Truncated,
  154. /// An incoming packet had an incorrect checksum and was dropped.
  155. Checksum,
  156. /// An incoming packet could not be recognized and was dropped.
  157. /// E.g. an Ethernet packet with an unknown EtherType.
  158. Unrecognized,
  159. /// An incoming IP packet has been split into several IP fragments and was dropped,
  160. /// since IP reassembly is not supported.
  161. Fragmented,
  162. /// An incoming packet was recognized but was self-contradictory.
  163. /// E.g. a TCP packet with both SYN and FIN flags set.
  164. Malformed,
  165. /// An incoming packet was recognized but contradicted internal state.
  166. /// E.g. a TCP packet addressed to a socket that doesn't exist.
  167. Dropped,
  168. /// An incoming fragment arrived too late.
  169. ReassemblyTimeout,
  170. /// The packet assembler is not initialized, thus it cannot know what the final size of the
  171. /// packet would be.
  172. PacketAssemblerNotInit,
  173. /// The buffer of the assembler is to small and thus the final packet wont fit into it.
  174. PacketAssemblerBufferTooSmall,
  175. /// The packet assembler did not receive all the fragments for assembling the final packet.
  176. PacketAssemblerIncomplete,
  177. /// There are too many holes in the packet assembler (should be fixed in the future?).
  178. PacketAssemblerTooManyHoles,
  179. /// There was an overlap when adding data to the packet assembler.
  180. PacketAssemblerOverlap,
  181. /// The packet assembler set has no place for assembling a new stream of fragments.
  182. PacketAssemblerSetFull,
  183. /// The key was not found in the packet assembler set.
  184. PacketAssemblerSetKeyNotFound,
  185. /// An incoming packet was recognized but some parts are not supported by smoltcp.
  186. /// E.g. some bit configuration in a packet header is not supported, but is defined in an RFC.
  187. NotSupported,
  188. }
  189. #[cfg(feature = "std")]
  190. impl std::error::Error for Error {}
  191. /// The result type for the networking stack.
  192. pub type Result<T> = core::result::Result<T, Error>;
  193. impl fmt::Display for Error {
  194. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  195. match *self {
  196. Error::Exhausted => write!(f, "buffer space exhausted"),
  197. Error::Illegal => write!(f, "illegal operation"),
  198. Error::Unaddressable => write!(f, "unaddressable destination"),
  199. Error::Finished => write!(f, "operation finished"),
  200. Error::Truncated => write!(f, "truncated packet"),
  201. Error::Checksum => write!(f, "checksum error"),
  202. Error::Unrecognized => write!(f, "unrecognized packet"),
  203. Error::Fragmented => write!(f, "fragmented packet"),
  204. Error::Malformed => write!(f, "malformed packet"),
  205. Error::Dropped => write!(f, "dropped by socket"),
  206. Error::ReassemblyTimeout => write!(f, "incoming fragment arrived too late"),
  207. Error::PacketAssemblerNotInit => write!(f, "packet assembler was not initialized"),
  208. Error::PacketAssemblerBufferTooSmall => {
  209. write!(f, "packet assembler buffer too small for final packet")
  210. }
  211. Error::PacketAssemblerIncomplete => write!(f, "packet assembler incomplete"),
  212. Error::PacketAssemblerTooManyHoles => write!(
  213. f,
  214. "packet assembler has too many holes (internal smoltcp error)"
  215. ),
  216. Error::PacketAssemblerOverlap => {
  217. write!(f, "overlap when adding data to packet assembler")
  218. }
  219. Error::PacketAssemblerSetFull => write!(f, "packet assembler set is full"),
  220. Error::PacketAssemblerSetKeyNotFound => {
  221. write!(f, "packet assembler set does not find key")
  222. }
  223. Error::NotSupported => write!(f, "not supported by smoltcp"),
  224. }
  225. }
  226. }
  227. impl From<wire::Error> for Error {
  228. fn from(_: wire::Error) -> Self {
  229. Error::Malformed
  230. }
  231. }