Skip to main content

rtci_shared/
error.rs

1//! The error type shared across the stack.
2//!
3//! One [`Error`](crate::error::Error) enum spans every layer — buffers, UDP, ICE, DTLS, SCTP, SRTP, RTP/RTCP, SDP and
4//! the data channel — so a value can propagate from the innermost codec to the application
5//! without conversion at each boundary. The higher-level crates re-export it, which is why an
6//! application only ever imports one error type.
7#![allow(dead_code)]
8
9use std::io;
10use std::net;
11use std::net::SocketAddr;
12use std::num::ParseIntError;
13use std::string::FromUtf8Error;
14use std::time::SystemTimeError;
15use substring::Substring;
16use thiserror::Error;
17
18/// A type alias for `std::result::Result` with this crate's [`enum@Error`] type.
19pub type Result<T> = std::result::Result<T, Error>;
20
21/// Unified error type for all WebRTC sub-protocols.
22///
23/// Aggregates errors from every layer of the WebRTC stack — buffers, RTP/RTCP,
24/// SRTP, STUN, TURN, ICE, DTLS, SCTP, data channels, SDP, mDNS, and the
25/// top-level peer connection — into a single enum so callers only need to
26/// handle one error type.
27///
28/// The enum is `#[non_exhaustive]`: new variants may be added in future
29/// releases without a semver-breaking change.
30#[derive(Error, Debug, PartialEq)]
31#[non_exhaustive]
32pub enum Error {
33    /// Buffer: full.
34    #[error("buffer: full")]
35    ErrBufferFull,
36    /// Buffer: closed.
37    #[error("buffer: closed")]
38    ErrBufferClosed,
39    /// Buffer: short.
40    #[error("buffer: short")]
41    ErrBufferShort,
42    /// Packet too big.
43    #[error("packet too big")]
44    ErrPacketTooBig,
45    /// I/O timeout.
46    #[error("i/o timeout")]
47    ErrTimeout,
48    /// UDP: listener closed.
49    #[error("udp: listener closed")]
50    ErrClosedListener,
51    /// UDP: listen queue exceeded.
52    #[error("udp: listen queue exceeded")]
53    ErrListenQueueExceeded,
54    /// UDP: listener accept ch closed.
55    #[error("udp: listener accept ch closed")]
56    ErrClosedListenerAcceptCh,
57    /// Obs cannot be nil.
58    #[error("obs cannot be nil")]
59    ErrObsCannotBeNil,
60    /// Se of closed network connection.
61    #[error("se of closed network connection")]
62    ErrUseClosedNetworkConn,
63    /// Addr is not a net.UDPAddr.
64    #[error("addr is not a net.UDPAddr")]
65    ErrAddrNotUdpAddr,
66    /// Something went wrong with locAddr.
67    #[error("something went wrong with locAddr")]
68    ErrLocAddr,
69    /// Already closed.
70    #[error("already closed")]
71    ErrAlreadyClosed,
72    /// No remAddr defined.
73    #[error("no remAddr defined")]
74    ErrNoRemAddr,
75    /// Address already in use.
76    #[error("address already in use")]
77    ErrAddressAlreadyInUse,
78    /// No such UDPConn.
79    #[error("no such UDPConn")]
80    ErrNoSuchUdpConn,
81    /// Cannot remove unspecified IP by the specified IP.
82    #[error("cannot remove unspecified IP by the specified IP")]
83    ErrCannotRemoveUnspecifiedIp,
84    /// No address assigned.
85    #[error("no address assigned")]
86    ErrNoAddressAssigned,
87    /// 1:1 NAT requires more than one mapping.
88    #[error("1:1 NAT requires more than one mapping")]
89    ErrNatRequriesMapping,
90    /// Length mismtach between mappedIPs and localIPs.
91    #[error("length mismtach between mappedIPs and localIPs")]
92    ErrMismatchLengthIp,
93    /// Non-udp translation is not supported yet.
94    #[error("non-udp translation is not supported yet")]
95    ErrNonUdpTranslationNotSupported,
96    /// No associated local address.
97    #[error("no associated local address")]
98    ErrNoAssociatedLocalAddress,
99    /// No NAT binding found.
100    #[error("no NAT binding found")]
101    ErrNoNatBindingFound,
102    /// Has no permission.
103    #[error("has no permission")]
104    ErrHasNoPermission,
105    /// Host name must not be empty.
106    #[error("host name must not be empty")]
107    ErrHostnameEmpty,
108    /// Failed to parse IP address.
109    #[error("failed to parse IP address")]
110    ErrFailedToParseIpaddr,
111    /// No interface is available.
112    #[error("no interface is available")]
113    ErrNoInterface,
114    /// Not found.
115    #[error("not found")]
116    ErrNotFound,
117    /// Unexpected network.
118    #[error("unexpected network")]
119    ErrUnexpectedNetwork,
120    /// Can't assign requested address.
121    #[error("can't assign requested address")]
122    ErrCantAssignRequestedAddr,
123    /// Unknown network.
124    #[error("unknown network")]
125    ErrUnknownNetwork,
126    /// No router linked.
127    #[error("no router linked")]
128    ErrNoRouterLinked,
129    /// Invalid port number.
130    #[error("invalid port number")]
131    ErrInvalidPortNumber,
132    /// Unexpected type-switch failure.
133    #[error("unexpected type-switch failure")]
134    ErrUnexpectedTypeSwitchFailure,
135    /// Bind failed.
136    #[error("bind failed")]
137    ErrBindFailed,
138    /// End port is less than the start.
139    #[error("end port is less than the start")]
140    ErrEndPortLessThanStart,
141    /// Port space exhausted.
142    #[error("port space exhausted")]
143    ErrPortSpaceExhausted,
144    /// Vnet is not enabled.
145    #[error("vnet is not enabled")]
146    ErrVnetDisabled,
147    /// Invalid local IP in static_ips.
148    #[error("invalid local IP in static_ips")]
149    ErrInvalidLocalIpInStaticIps,
150    /// Mapped in static_ips is beyond subnet.
151    #[error("mapped in static_ips is beyond subnet")]
152    ErrLocalIpBeyondStaticIpsSubset,
153    /// All static_ips must have associated local IPs.
154    #[error("all static_ips must have associated local IPs")]
155    ErrLocalIpNoStaticsIpsAssociated,
156    /// Router already started.
157    #[error("router already started")]
158    ErrRouterAlreadyStarted,
159    /// Router already stopped.
160    #[error("router already stopped")]
161    ErrRouterAlreadyStopped,
162    /// Static IP is beyond subnet.
163    #[error("static IP is beyond subnet")]
164    ErrStaticIpIsBeyondSubnet,
165    /// Address space exhausted.
166    #[error("address space exhausted")]
167    ErrAddressSpaceExhausted,
168    /// No IP address is assigned for eth0.
169    #[error("no IP address is assigned for eth0")]
170    ErrNoIpaddrEth0,
171    /// Invalid mask.
172    #[error("Invalid mask")]
173    ErrInvalidMask,
174
175    //ExportKeyingMaterial errors
176    /// TLS handshake is in progress.
177    #[error("tls handshake is in progress")]
178    HandshakeInProgress,
179    /// Context is not supported for export_keying_material.
180    #[error("context is not supported for export_keying_material")]
181    ContextUnsupported,
182    /// Export_keying_material can not be used with a reserved label.
183    #[error("export_keying_material can not be used with a reserved label")]
184    ReservedExportKeyingMaterial,
185    /// No cipher suite for export_keying_material.
186    #[error("no cipher suite for export_keying_material")]
187    CipherSuiteUnset,
188    /// The association's exporter secret was erased once no more exports were needed
189    /// (RFC 8446 appendix E.1.4): nothing more can be exported from it.
190    #[error("the exporter secret was erased: nothing more can be exported")]
191    ExporterSecretForgotten,
192    /// Export_keying_material hash.
193    #[error("export_keying_material hash: {0}")]
194    Hash(String),
195    /// Mutex poison.
196    #[error("mutex poison: {0}")]
197    PoisonError(String),
198
199    //RTCP errors
200    /// Wrong marshal size.
201    #[error("Wrong marshal size")]
202    WrongMarshalSize,
203    /// Packet lost exceeds maximum amount of packets
204    /// that can possibly be lost.
205    #[error("Invalid total lost count")]
206    InvalidTotalLost,
207    /// Packet contains an invalid header.
208    #[error("Invalid header")]
209    InvalidHeader,
210    /// Packet contains empty compound.
211    #[error("Empty compound packet")]
212    EmptyCompound,
213    /// Invalid first packet in compound packets. First packet
214    /// should either be a SenderReport packet or ReceiverReport
215    #[error("First packet in compound must be SR or RR")]
216    BadFirstPacket,
217    /// CNAME was not defined.
218    #[error("Compound missing SourceDescription with CNAME")]
219    MissingCname,
220    /// Packet was defined before CNAME.
221    #[error("Feedback packet seen before CNAME")]
222    PacketBeforeCname,
223    /// Too many reports.
224    #[error("Too many reports")]
225    TooManyReports,
226    /// Too many chunks.
227    #[error("Too many chunks")]
228    TooManyChunks,
229    /// Too many sources.
230    #[error("too many sources")]
231    TooManySources,
232    /// Packet received is too short.
233    #[error("Packet too short to be read")]
234    PacketTooShort,
235    /// Buffer is too short.
236    #[error("Buffer too short to be written")]
237    BufferTooShort,
238    /// Wrong packet type.
239    #[error("Wrong packet type")]
240    WrongType,
241    /// SDES received is too long.
242    #[error("SDES must be < 255 octets long")]
243    SdesTextTooLong,
244    /// SDES type is missing.
245    #[error("SDES item missing type")]
246    SdesMissingType,
247    /// An RTCP CNAME given to a connection that is not 1 to 255 octets (RFC 3550 section 6.5:
248    /// an SDES item's text has an 8-bit length; RFC 7022: a CNAME names its source).
249    #[error("an RTCP CNAME must be 1 to 255 octets long")]
250    ErrRtcpCnameLength,
251    /// Reason is too long.
252    #[error("Reason must be < 255 octets long")]
253    ReasonTooLong,
254    /// Invalid packet version.
255    #[error("Invalid packet version")]
256    BadVersion,
257    /// Invalid padding value.
258    #[error("Invalid padding value")]
259    WrongPadding,
260    /// Wrong feedback message type.
261    #[error("Wrong feedback message type")]
262    WrongFeedbackType,
263    /// Wrong payload type.
264    #[error("Wrong payload type")]
265    WrongPayloadType,
266    /// Header length is too small.
267    #[error("Header length is too small")]
268    HeaderTooSmall,
269    /// Media ssrc was defined as zero.
270    #[error("Media SSRC must be 0")]
271    SsrcMustBeZero,
272    /// Missing REMB identifier.
273    #[error("Missing REMB identifier")]
274    MissingRembIdentifier,
275    /// SSRC number and length mismatches.
276    #[error("SSRC num and length do not match")]
277    SsrcNumAndLengthMismatch,
278    /// Invalid size or start index.
279    #[error("Invalid size or startIndex")]
280    InvalidSizeOrStartIndex,
281    /// Delta exceeds limit.
282    #[error("Delta exceed limit")]
283    DeltaExceedLimit,
284    /// Packet status chunk is not 2 bytes.
285    #[error("Packet status chunk must be 2 bytes")]
286    PacketStatusChunkLength,
287    /// Invalid bitrate.
288    #[error("Invalid bitrate")]
289    InvalidBitrate,
290    /// Wrong chunk type.
291    #[error("Wrong chunk type")]
292    WrongChunkType,
293    /// Struct contains unexpected member type.
294    #[error("Struct contains unexpected member type")]
295    BadStructMemberType,
296    /// Cannot read into non-pointer.
297    #[error("Cannot read into non-pointer")]
298    BadReadParameter,
299    /// Invalid block size.
300    #[error("Invalid block size")]
301    InvalidBlockSize,
302
303    //RTP errors
304    /// RTP header size insufficient.
305    #[error("RTP header size insufficient")]
306    ErrHeaderSizeInsufficient,
307    /// RTP header size insufficient for extension.
308    #[error("RTP header size insufficient for extension")]
309    ErrHeaderSizeInsufficientForExtension,
310    /// Buffer too small.
311    #[error("buffer too small")]
312    ErrBufferTooSmall,
313    /// Extension not enabled.
314    #[error("extension not enabled")]
315    ErrHeaderExtensionsNotEnabled,
316    /// Extension not found.
317    #[error("extension not found")]
318    ErrHeaderExtensionNotFound,
319
320    /// Header extension id must be between 1 and 14 for RFC 5285 extensions.
321    #[error("header extension id must be between 1 and 14 for RFC 5285 extensions")]
322    ErrRfc8285oneByteHeaderIdrange,
323    /// Header extension payload must be 16bytes or less for RFC 5285 one byte extensions.
324    #[error("header extension payload must be 16bytes or less for RFC 5285 one byte extensions")]
325    ErrRfc8285oneByteHeaderSize,
326
327    /// Header extension id must be between 1 and 255 for RFC 5285 extensions.
328    #[error("header extension id must be between 1 and 255 for RFC 5285 extensions")]
329    ErrRfc8285twoByteHeaderIdrange,
330    /// Header extension payload must be 255bytes or less for RFC 5285 two byte extensions.
331    #[error("header extension payload must be 255bytes or less for RFC 5285 two byte extensions")]
332    ErrRfc8285twoByteHeaderSize,
333
334    /// Header extension id must be 0 for none RFC 5285 extensions.
335    #[error("header extension id must be 0 for none RFC 5285 extensions")]
336    ErrRfc3550headerIdrange,
337
338    /// Packet is not large enough.
339    #[error("packet is not large enough")]
340    ErrShortPacket,
341    /// Invalid nil packet.
342    #[error("invalid nil packet")]
343    ErrNilPacket,
344    /// Too many PDiff.
345    #[error("too many PDiff")]
346    ErrTooManyPDiff,
347    /// Too many spatial layers.
348    #[error("too many spatial layers")]
349    ErrTooManySpatialLayers,
350    /// NALU Type is unhandled.
351    #[error("NALU Type is unhandled")]
352    ErrUnhandledNaluType,
353
354    /// Corrupted H265 packet.
355    #[error("corrupted h265 packet")]
356    ErrH265CorruptedPacket,
357    /// Invalid H265 packet type.
358    #[error("invalid h265 packet type")]
359    ErrInvalidH265PacketType,
360
361    /// Payload is too small for OBU extension header.
362    #[error("payload is too small for OBU extension header")]
363    ErrPayloadTooSmallForObuExtensionHeader,
364    /// Payload is too small for OBU payload size.
365    #[error("payload is too small for OBU payload size")]
366    ErrPayloadTooSmallForObuPayloadSize,
367
368    /// Extension_payload must be in 32-bit words.
369    #[error("extension_payload must be in 32-bit words")]
370    HeaderExtensionPayloadNot32BitWords,
371    /// Too many CSRCs for the 4-bit CC field.
372    #[error("too many CSRCs: {0} exceeds the 4-bit CC field maximum of 15")]
373    TooManyCSRCs(usize),
374    /// One-byte header extension payload length outside 1-16 bytes.
375    #[error(
376        "one-byte header extension payload length {0} is outside the RFC 8285 valid range of 1-16 bytes"
377    )]
378    OneByteHeaderExtensionPayloadOutOfRange(usize),
379    /// Two-byte header extension payload longer than 255 bytes.
380    #[error(
381        "two-byte header extension payload length {0} exceeds the RFC 8285 maximum of 255 bytes"
382    )]
383    TwoByteHeaderExtensionPayloadTooLarge(usize),
384    /// Total extension payload length exceeds u16::MAX.
385    #[error("total extension payload length {0} exceeds u16::MAX (65535 bytes)")]
386    ExtensionPayloadTotalOverflow(usize),
387    /// NALU length exceeds u16::MAX.
388    #[error("NALU length {0} exceeds u16::MAX (65535 bytes)")]
389    NaluTooLarge(usize),
390    /// Audio level overflow.
391    #[error("audio level overflow")]
392    AudioLevelOverflow,
393    /// Playout delay overflow.
394    #[error("playout delay overflow")]
395    PlayoutDelayOverflow,
396    /// Payload is not large enough.
397    #[error("payload is not large enough")]
398    PayloadIsNotLargeEnough,
399    /// STAP-A declared size is larger than buffer.
400    #[error("STAP-A declared size({0}) is larger than buffer({1})")]
401    StapASizeLargerThanBuffer(usize, usize),
402    /// NALU type is currently not handled.
403    #[error("nalu type {0} is currently not handled")]
404    NaluTypeIsNotHandled(u8),
405
406    //SRTP
407    /// Duplicated packet.
408    #[error("duplicated packet")]
409    ErrDuplicated,
410    /// SRTP master key is not long enough.
411    #[error("SRTP master key is not long enough")]
412    ErrShortSrtpMasterKey,
413    /// SRTP master salt is not long enough.
414    #[error("SRTP master salt is not long enough")]
415    ErrShortSrtpMasterSalt,
416    /// No such SRTP Profile.
417    #[error("no such SRTP Profile")]
418    ErrNoSuchSrtpProfile,
419    /// IndexOverKdr > 0 is not supported yet.
420    #[error("indexOverKdr > 0 is not supported yet")]
421    ErrNonZeroKdrNotSupported,
422    /// Exporter called with wrong label.
423    #[error("exporter called with wrong label")]
424    ErrExporterWrongLabel,
425    /// No config provided.
426    #[error("no config provided")]
427    ErrNoConfig,
428    /// No conn provided.
429    #[error("no conn provided")]
430    ErrNoConn,
431    /// Failed to verify auth tag.
432    #[error("failed to verify auth tag")]
433    ErrFailedToVerifyAuthTag,
434    /// Packet is too short to be RTP packet.
435    #[error("packet is too short to be RTP packet")]
436    ErrTooShortRtp,
437    /// Packet is too short to be RTCP packet.
438    #[error("packet is too short to be RTCP packet")]
439    ErrTooShortRtcp,
440    /// Payload differs.
441    #[error("payload differs")]
442    ErrPayloadDiffers,
443    /// Started channel used incorrectly, should only be closed.
444    #[error("started channel used incorrectly, should only be closed")]
445    ErrStartedChannelUsedIncorrectly,
446    /// Stream has not been inited, unable to close.
447    #[error("stream has not been inited, unable to close")]
448    ErrStreamNotInited,
449    /// Stream is already closed.
450    #[error("stream is already closed")]
451    ErrStreamAlreadyClosed,
452    /// Stream is already inited.
453    #[error("stream is already inited")]
454    ErrStreamAlreadyInited,
455    /// Failed to cast child.
456    #[error("failed to cast child")]
457    ErrFailedTypeAssertion,
458    /// Exceeded the maximum number of packets.
459    #[error("exceeded the maximum number of packets")]
460    ErrExceededMaxPackets,
461
462    /// Index_over_kdr > 0 is not supported yet.
463    #[error("index_over_kdr > 0 is not supported yet")]
464    UnsupportedIndexOverKdr,
465    /// Invalid master key length for AES_256_cm.
466    #[error("invalid master key length for aes_256_cm")]
467    InvalidMasterKeyLength,
468    /// Invalid master salt length for AES_256_cm.
469    #[error("invalid master salt length for aes_256_cm")]
470    InvalidMasterSaltLength,
471    /// Out_len > 32 is not supported for AES_256_cm.
472    #[error("out_len > 32 is not supported for aes_256_cm")]
473    UnsupportedOutLength,
474    /// SRTP Master Key must be len , got.
475    #[error("SRTP Master Key must be len {0}, got {1}")]
476    SrtpMasterKeyLength(usize, usize),
477    /// SRTP Salt must be len , got.
478    #[error("SRTP Salt must be len {0}, got {1}")]
479    SrtpSaltLength(usize, usize),
480    /// SyntaxError.
481    #[error("SyntaxError: {0}")]
482    ExtMapParse(String),
483    /// SSRC not exist in SRTP_SSRC_state.
484    #[error("ssrc {0} not exist in srtp_ssrc_state")]
485    SsrcMissingFromSrtp(u32),
486    /// SRTP SSRC= index=: duplicated.
487    #[error("srtp ssrc={0} index={1}: duplicated")]
488    SrtpSsrcDuplicated(u32, u16),
489    /// SRTP SSRC= seq=: this packet index was already used to encrypt (RFC 3711 Section 3.3.1).
490    #[error("srtp ssrc={0} seq={1}: packet index already used for encryption")]
491    SrtpIndexReused(u32, u16),
492    /// SRTP/SRTCP SSRC refused: the context already holds state for the maximum number of SSRCs.
493    #[error("srtp ssrc={0}: refused, the context already tracks {1} SSRCs")]
494    SrtpTooManySsrcs(u32, usize),
495    /// Srtcp SSRC= index=: duplicated.
496    #[error("srtcp ssrc={0} index={1}: duplicated")]
497    SrtcpSsrcDuplicated(u32, usize),
498    /// SSRC not exist in srtcp_SSRC_state.
499    #[error("ssrc {0} not exist in srtcp_ssrc_state")]
500    SsrcMissingFromSrtcp(u32),
501    /// Stream with SSRC exists.
502    #[error("Stream with ssrc {0} exists")]
503    StreamWithSsrcExists(u32),
504    /// Session RTP/RTCP type must be same as input buffer.
505    #[error("Session RTP/RTCP type must be same as input buffer")]
506    SessionRtpRtcpTypeMismatch,
507    /// Session EOF.
508    #[error("Session EOF")]
509    SessionEof,
510    /// Too short SRTP packet: only bytes, expected > bytes.
511    #[error("too short SRTP packet: only {0} bytes, expected > {1} bytes")]
512    SrtpTooSmall(usize, usize),
513    /// Too short SRTCP packet: only bytes, expected > bytes.
514    #[error("too short SRTCP packet: only {0} bytes, expected > {1} bytes")]
515    SrtcpTooSmall(usize, usize),
516    /// Failed to verify RTP auth tag.
517    #[error("failed to verify rtp auth tag")]
518    RtpFailedToVerifyAuthTag,
519    /// Too short auth tag: only bytes, expected > bytes.
520    #[error("too short auth tag: only {0} bytes, expected > {1} bytes")]
521    RtcpInvalidLengthAuthTag(usize, usize),
522    /// Failed to verify RTCP auth tag.
523    #[error("failed to verify rtcp auth tag")]
524    RtcpFailedToVerifyAuthTag,
525    /// SessionSRTP has been closed.
526    #[error("SessionSRTP has been closed")]
527    SessionSrtpAlreadyClosed,
528    /// This stream is not a RTPStream.
529    #[error("this stream is not a RTPStream")]
530    InvalidRtpStream,
531    /// This stream is not a RTCPStream.
532    #[error("this stream is not a RTCPStream")]
533    InvalidRtcpStream,
534
535    //STUN errors
536    /// Attribute not found.
537    #[error("attribute not found")]
538    ErrAttributeNotFound,
539    /// Transaction is stopped.
540    #[error("transaction is stopped")]
541    ErrTransactionStopped,
542    /// Transaction not exists.
543    #[error("transaction not exists")]
544    ErrTransactionNotExists,
545    /// Transaction exists with same id.
546    #[error("transaction exists with same id")]
547    ErrTransactionExists,
548    /// Agent is closed.
549    #[error("agent is closed")]
550    ErrAgentClosed,
551    /// Transaction is timed out.
552    #[error("transaction is timed out")]
553    ErrTransactionTimeOut,
554    /// No default reason for ErrorCode.
555    #[error("no default reason for ErrorCode")]
556    ErrNoDefaultReason,
557    /// Unexpected EOF.
558    #[error("unexpected EOF")]
559    ErrUnexpectedEof,
560    /// Attribute size is invalid.
561    #[error("attribute size is invalid")]
562    ErrAttributeSizeInvalid,
563    /// Attribute size overflow.
564    #[error("attribute size overflow")]
565    ErrAttributeSizeOverflow,
566    /// Attempt to decode to nil message.
567    #[error("attempt to decode to nil message")]
568    ErrDecodeToNil,
569    /// Unexpected EOF: not enough bytes to read header.
570    #[error("unexpected EOF: not enough bytes to read header")]
571    ErrUnexpectedHeaderEof,
572    /// Integrity check failed.
573    #[error("integrity check failed")]
574    ErrIntegrityMismatch,
575    /// Fingerprint check failed.
576    #[error("fingerprint check failed")]
577    ErrFingerprintMismatch,
578    /// FINGERPRINT before MESSAGE-INTEGRITY attribute.
579    #[error("FINGERPRINT before MESSAGE-INTEGRITY attribute")]
580    ErrFingerprintBeforeIntegrity,
581    /// Bad UNKNOWN-ATTRIBUTES size.
582    #[error("bad UNKNOWN-ATTRIBUTES size")]
583    ErrBadUnknownAttrsSize,
584    /// Invalid length of IP value.
585    #[error("invalid length of IP value")]
586    ErrBadIpLength,
587    /// No connection provided.
588    #[error("no connection provided")]
589    ErrNoConnection,
590    /// Client is closed.
591    #[error("client is closed")]
592    ErrClientClosed,
593    /// No agent is set.
594    #[error("no agent is set")]
595    ErrNoAgent,
596    /// Collector is closed.
597    #[error("collector is closed")]
598    ErrCollectorClosed,
599    /// Unsupported network.
600    #[error("unsupported network")]
601    ErrUnsupportedNetwork,
602    /// Invalid URL.
603    #[error("invalid url")]
604    ErrInvalidUrl,
605    /// Unknown scheme type.
606    #[error("unknown scheme type")]
607    ErrSchemeType,
608    /// Invalid hostname.
609    #[error("invalid hostname")]
610    ErrHost,
611
612    // TURN errors
613    /// TURN: RelayAddress must be valid IP to use RelayAddressGeneratorStatic.
614    #[error("turn: RelayAddress must be valid IP to use RelayAddressGeneratorStatic")]
615    ErrRelayAddressInvalid,
616    /// TURN: PacketConnConfigs and ConnConfigs are empty, unable to proceed.
617    #[error("turn: PacketConnConfigs and ConnConfigs are empty, unable to proceed")]
618    ErrNoAvailableConns,
619    /// TURN: PacketConnConfig must have a non-nil Conn.
620    #[error("turn: PacketConnConfig must have a non-nil Conn")]
621    ErrConnUnset,
622    /// TURN: ListenerConfig must have a non-nil Listener.
623    #[error("turn: ListenerConfig must have a non-nil Listener")]
624    ErrListenerUnset,
625    /// TURN: RelayAddressGenerator has invalid ListeningAddress.
626    #[error("turn: RelayAddressGenerator has invalid ListeningAddress")]
627    ErrListeningAddressInvalid,
628    /// TURN: RelayAddressGenerator in RelayConfig is unset.
629    #[error("turn: RelayAddressGenerator in RelayConfig is unset")]
630    ErrRelayAddressGeneratorUnset,
631    /// TURN: max retries exceeded.
632    #[error("turn: max retries exceeded")]
633    ErrMaxRetriesExceeded,
634    /// TURN: MaxPort must be not 0.
635    #[error("turn: MaxPort must be not 0")]
636    ErrMaxPortNotZero,
637    /// TURN: MaxPort must be not 0.
638    #[error("turn: MaxPort must be not 0")]
639    ErrMinPortNotZero,
640    /// TURN: MaxPort less than MinPort.
641    #[error("turn: MaxPort less than MinPort")]
642    ErrMaxPortLessThanMinPort,
643    /// TURN: relay_conn cannot not be nil.
644    #[error("turn: relay_conn cannot not be nil")]
645    ErrNilConn,
646    /// TURN: TODO.
647    #[error("turn: TODO")]
648    ErrTodo,
649    /// TURN: already listening.
650    #[error("turn: already listening")]
651    ErrAlreadyListening,
652    /// TURN: Server failed to close.
653    #[error("turn: Server failed to close")]
654    ErrFailedToClose,
655    /// TURN: failed to retransmit transaction.
656    #[error("turn: failed to retransmit transaction")]
657    ErrFailedToRetransmitTransaction,
658    /// All retransmissions failed.
659    #[error("all retransmissions failed")]
660    ErrAllRetransmissionsFailed,
661    /// No binding found for channel.
662    #[error("no binding found for channel")]
663    ErrChannelBindNotFound,
664    /// STUN server address is not set for the client.
665    #[error("STUN server address is not set for the client")]
666    ErrStunserverAddressNotSet,
667    /// Only one Allocate caller is allowed.
668    #[error("only one Allocate() caller is allowed")]
669    ErrOneAllocateOnly,
670    /// Already allocated.
671    #[error("already allocated")]
672    ErrAlreadyAllocated,
673    /// Non-STUN message from STUN server.
674    #[error("non-STUN message from STUN server")]
675    ErrNonStunmessage,
676    /// Failed to decode STUN message.
677    #[error("failed to decode STUN message")]
678    ErrFailedToDecodeStun,
679    /// Unexpected STUN request message.
680    #[error("unexpected STUN request message")]
681    ErrUnexpectedStunrequestMessage,
682    /// Channel number not in [0x4000, 0x7FFF].
683    #[error("channel number not in [0x4000, 0x7FFF]")]
684    ErrInvalidChannelNumber,
685    /// ChannelData length != len(Data).
686    #[error("channelData length != len(Data)")]
687    ErrBadChannelDataLength,
688    /// Invalid value for requested family attribute.
689    #[error("invalid value for requested family attribute")]
690    ErrInvalidRequestedFamilyValue,
691    /// Fake error.
692    #[error("fake error")]
693    ErrFakeErr,
694    /// Use of closed network connection.
695    #[error("use of closed network connection")]
696    ErrClosed,
697    /// Addr is not a net.UDPAddr.
698    #[error("addr is not a net.UDPAddr")]
699    ErrUdpaddrCast,
700    /// Try-lock is already locked.
701    #[error("try-lock is already locked")]
702    ErrDoubleLock,
703    /// Transaction closed.
704    #[error("transaction closed")]
705    ErrTransactionClosed,
706    /// Wait_for_result called on non-result transaction.
707    #[error("wait_for_result called on non-result transaction")]
708    ErrWaitForResultOnNonResultTransaction,
709    /// Failed to build refresh request.
710    #[error("failed to build refresh request")]
711    ErrFailedToBuildRefreshRequest,
712    /// Failed to refresh allocation.
713    #[error("failed to refresh allocation")]
714    ErrFailedToRefreshAllocation,
715    /// Failed to get lifetime from refresh response.
716    #[error("failed to get lifetime from refresh response")]
717    ErrFailedToGetLifetime,
718    /// Too short buffer.
719    #[error("too short buffer")]
720    ErrShortBuffer,
721    /// Unexpected response type.
722    #[error("unexpected response type")]
723    ErrUnexpectedResponse,
724    /// AllocatePacketConn must be set.
725    #[error("AllocatePacketConn must be set")]
726    ErrAllocatePacketConnMustBeSet,
727    /// AllocateConn must be set.
728    #[error("AllocateConn must be set")]
729    ErrAllocateConnMustBeSet,
730    /// LeveledLogger must be set.
731    #[error("LeveledLogger must be set")]
732    ErrLeveledLoggerMustBeSet,
733    /// You cannot use the same channel number with different peer.
734    #[error("you cannot use the same channel number with different peer")]
735    ErrSameChannelDifferentPeer,
736    /// Allocations must not be created with nil FivTuple.
737    #[error("allocations must not be created with nil FivTuple")]
738    ErrNilFiveTuple,
739    /// Allocations must not be created with nil FiveTuple.src_addr.
740    #[error("allocations must not be created with nil FiveTuple.src_addr")]
741    ErrNilFiveTupleSrcAddr,
742    /// Allocations must not be created with nil FiveTuple.dst_addr.
743    #[error("allocations must not be created with nil FiveTuple.dst_addr")]
744    ErrNilFiveTupleDstAddr,
745    /// Allocations must not be created with nil turnSocket.
746    #[error("allocations must not be created with nil turnSocket")]
747    ErrNilTurnSocket,
748    /// Allocations must not be created with a lifetime of 0.
749    #[error("allocations must not be created with a lifetime of 0")]
750    ErrLifetimeZero,
751    /// Allocation attempt created with duplicate FiveTuple.
752    #[error("allocation attempt created with duplicate FiveTuple")]
753    ErrDupeFiveTuple,
754    /// Failed to cast net.Addr to *net.UDPAddr.
755    #[error("failed to cast net.Addr to *net.UDPAddr")]
756    ErrFailedToCastUdpaddr,
757    /// Failed to generate nonce.
758    #[error("failed to generate nonce")]
759    ErrFailedToGenerateNonce,
760    /// Failed to send error message.
761    #[error("failed to send error message")]
762    ErrFailedToSendError,
763    /// Duplicated Nonce generated, discarding request.
764    #[error("duplicated Nonce generated, discarding request")]
765    ErrDuplicatedNonce,
766    /// No such user exists.
767    #[error("no such user exists")]
768    ErrNoSuchUser,
769    /// Unexpected class.
770    #[error("unexpected class")]
771    ErrUnexpectedClass,
772    /// Unexpected method.
773    #[error("unexpected method")]
774    ErrUnexpectedMethod,
775    /// Failed to handle.
776    #[error("failed to handle")]
777    ErrFailedToHandle,
778    /// Unhandled STUN packet.
779    #[error("unhandled STUN packet")]
780    ErrUnhandledStunpacket,
781    /// Unable to handle ChannelData.
782    #[error("unable to handle ChannelData")]
783    ErrUnableToHandleChannelData,
784    /// Failed to create STUN message from packet.
785    #[error("failed to create stun message from packet")]
786    ErrFailedToCreateStunpacket,
787    /// Failed to create channel data from packet.
788    #[error("failed to create channel data from packet")]
789    ErrFailedToCreateChannelData,
790    /// Relay already allocated for 5-TUPLE.
791    #[error("relay already allocated for 5-TUPLE")]
792    ErrRelayAlreadyAllocatedForFiveTuple,
793    /// RequestedTransport must be UDP.
794    #[error("RequestedTransport must be UDP")]
795    ErrRequestedTransportMustBeUdp,
796    /// No support for DONT-FRAGMENT.
797    #[error("no support for DONT-FRAGMENT")]
798    ErrNoDontFragmentSupport,
799    /// Request must not contain RESERVATION-TOKEN and EVEN-PORT.
800    #[error("Request must not contain RESERVATION-TOKEN and EVEN-PORT")]
801    ErrRequestWithReservationTokenAndEvenPort,
802    /// No allocation found.
803    #[error("no allocation found")]
804    ErrNoAllocationFound,
805    /// Unable to handle send-indication, no permission added.
806    #[error("unable to handle send-indication, no permission added")]
807    ErrNoPermission,
808    /// Packet write smaller than packet.
809    #[error("packet write smaller than packet")]
810    ErrShortWrite,
811    /// No such channel bind.
812    #[error("no such channel bind")]
813    ErrNoSuchChannelBind,
814    /// Failed writing to socket.
815    #[error("failed writing to socket")]
816    ErrFailedWriteSocket,
817
818    // ICE errors
819    /// Indicates an error with Unknown info.
820    #[error("Unknown type")]
821    ErrUnknownType,
822
823    /// Indicates query arguments are provided in a STUN URL.
824    #[error("queries not supported in stun address")]
825    ErrStunQuery,
826
827    /// Indicates an malformed query is provided.
828    #[error("invalid query")]
829    ErrInvalidQuery,
830
831    /// Indicates malformed port is provided.
832    #[error("url parse: invalid port number")]
833    ErrPort,
834
835    /// Indicates local username fragment insufficient bits are provided.
836    /// Have to be at least 24 bits long.
837    #[error("local username fragment is less than 24 bits long")]
838    ErrLocalUfragInsufficientBits,
839
840    /// Indicates local passoword insufficient bits are provided.
841    /// Have to be at least 128 bits long.
842    #[error("local password is less than 128 bits long")]
843    ErrLocalPwdInsufficientBits,
844
845    /// A local username fragment longer than 32 characters (RFC 8839 section 5.4: "MUST NOT
846    /// send") or with a character that is not an `ice-char` (letters, digits, `+`, `/`).
847    #[error("local username fragment is longer than 32 characters or not made of ice-chars")]
848    ErrLocalUfragInvalid,
849
850    /// A local password longer than 256 characters or with a character that is not an
851    /// `ice-char` (RFC 8839 section 5.4).
852    #[error("local password is longer than 256 characters or not made of ice-chars")]
853    ErrLocalPwdInvalid,
854
855    /// A local server-reflexive, peer-reflexive or relayed candidate without its related
856    /// address (RFC 8839 section 5.1: `raddr` and `rport` "MUST be present" for them).
857    #[error("a local srflx, prflx or relay candidate has no related address")]
858    ErrLocalCandidateWithoutRelatedAddress,
859
860    /// Indicates an unsupported transport type was provided.
861    #[error("invalid transport protocol type")]
862    ErrProtoType,
863
864    /// Indicates agent does not have a valid candidate pair.
865    #[error("no candidate pairs available")]
866    ErrNoCandidatePairs,
867
868    /// Indicates agent connection was canceled by the caller.
869    #[error("connecting canceled by caller")]
870    ErrCanceledByCaller,
871
872    /// Indicates agent was started twice.
873    #[error("attempted to start agent twice")]
874    ErrMultipleStart,
875
876    /// Indicates agent was started with an empty remote ufrag.
877    #[error("remote ufrag is empty")]
878    ErrRemoteUfragEmpty,
879
880    /// Indicates agent was started with an empty remote pwd.
881    #[error("remote pwd is empty")]
882    ErrRemotePwdEmpty,
883
884    /// Indicates agent was started without on_candidate.
885    #[error("no on_candidate provided")]
886    ErrNoOnCandidateHandler,
887
888    /// Indicates GatherCandidates has been called multiple times.
889    #[error("attempting to gather candidates during gathering state")]
890    ErrMultipleGatherAttempted,
891
892    /// Indicates agent was give TURN URL with an empty Username.
893    #[error("username is empty")]
894    ErrUsernameEmpty,
895
896    /// Indicates agent was give TURN URL with an empty Password.
897    #[error("password is empty")]
898    ErrPasswordEmpty,
899
900    /// Indicates we were unable to parse a candidate address.
901    #[error("failed to parse address")]
902    ErrAddressParseFailed,
903
904    /// Indicates that non host candidates were selected for a lite agent.
905    #[error("lite agents must only use host candidates")]
906    ErrLiteUsingNonHostCandidates,
907
908    /// Indicates that current ice agent supports Lite only
909    #[error("lite support only")]
910    ErrLiteSupportOnly,
911
912    /// Indicates that one or more URL was provided to the agent but no host candidate required them.
913    #[error("agent does not need URL with selected candidate types")]
914    ErrUselessUrlsProvided,
915
916    /// Indicates that the specified NAT1To1IPCandidateType is unsupported.
917    #[error("unsupported 1:1 NAT IP candidate type")]
918    ErrUnsupportedNat1to1IpCandidateType,
919
920    /// Indicates that the given 1:1 NAT IP mapping is invalid.
921    #[error("invalid 1:1 NAT IP mapping")]
922    ErrInvalidNat1to1IpMapping,
923
924    /// IPNotFound in NAT1To1IPMapping.
925    #[error("external mapped IP not found")]
926    ErrExternalMappedIpNotFound,
927
928    /// Indicates that the mDNS gathering cannot be used along with 1:1 NAT IP mapping for host
929    /// candidate.
930    #[error("mDNS gathering cannot be used with 1:1 NAT IP mapping for host candidate")]
931    ErrMulticastDnsWithNat1to1IpMapping,
932
933    /// Indicates that 1:1 NAT IP mapping for host candidate is requested, but the host candidate
934    /// type is disabled.
935    #[error("1:1 NAT IP mapping for host candidate ineffective")]
936    ErrIneffectiveNat1to1IpMappingHost,
937
938    /// Indicates that 1:1 NAT IP mapping for srflx candidate is requested, but the srflx candidate
939    /// type is disabled.
940    #[error("1:1 NAT IP mapping for srflx candidate ineffective")]
941    ErrIneffectiveNat1to1IpMappingSrflx,
942
943    /// Indicates an invalid MulticastDNSHostName.
944    #[error("invalid mDNS HostName, must end with .local and can only contain a single '.'")]
945    ErrInvalidMulticastDnshostName,
946
947    /// Indicates mdns is not supported.
948    #[error("mdns is not supported")]
949    ErrMulticastDnsNotSupported,
950
951    /// Indicates Restart was called when Agent is in GatheringStateGathering.
952    #[error("ICE Agent can not be restarted when gathering")]
953    ErrRestartWhenGathering,
954
955    /// Indicates a run operation was canceled by its individual done.
956    #[error("run was canceled by done")]
957    ErrRunCanceled,
958
959    /// Initialized Indicates TCPMux is not initialized and that invalidTCPMux is used.
960    #[error("TCPMux is not initialized")]
961    ErrTcpMuxNotInitialized,
962
963    /// Indicates we already have the connection with same remote addr.
964    #[error("conn with same remote addr already exists")]
965    ErrTcpRemoteAddrAlreadyExists,
966
967    /// Failed to send packet.
968    #[error("failed to send packet")]
969    ErrSendPacket,
970    /// Attribute not long enough to be ICE candidate.
971    #[error("attribute not long enough to be ICE candidate")]
972    ErrAttributeTooShortIceCandidate,
973    /// Could not parse component.
974    #[error("could not parse component")]
975    ErrParseComponent,
976    /// Could not parse priority.
977    #[error("could not parse priority")]
978    ErrParsePriority,
979    /// Could not parse port.
980    #[error("could not parse port")]
981    ErrParsePort,
982    /// Could not parse related addresses.
983    #[error("could not parse related addresses")]
984    ErrParseRelatedAddr,
985    /// Could not parse type.
986    #[error("could not parse type")]
987    ErrParseType,
988    /// Unknown candidate type.
989    #[error("unknown candidate type")]
990    ErrUnknownCandidateType,
991    /// Failed to get XOR-MAPPED-ADDRESS response.
992    #[error("failed to get XOR-MAPPED-ADDRESS response")]
993    ErrGetXorMappedAddrResponse,
994    /// Connection with same remote address already exists.
995    #[error("connection with same remote address already exists")]
996    ErrConnectionAddrAlreadyExist,
997    /// Error reading streaming packet.
998    #[error("error reading streaming packet")]
999    ErrReadingStreamingPacket,
1000    /// Error writing to.
1001    #[error("error writing to")]
1002    ErrWriting,
1003    /// Error closing connection.
1004    #[error("error closing connection")]
1005    ErrClosingConnection,
1006    /// Unable to determine networkType.
1007    #[error("unable to determine networkType")]
1008    ErrDetermineNetworkType,
1009    /// Missing protocol scheme.
1010    #[error("missing protocol scheme")]
1011    ErrMissingProtocolScheme,
1012    /// Too many colons in address.
1013    #[error("too many colons in address")]
1014    ErrTooManyColonsAddr,
1015    /// Unexpected error trying to read.
1016    #[error("unexpected error trying to read")]
1017    ErrRead,
1018    /// Unknown role.
1019    #[error("unknown role")]
1020    ErrUnknownRole,
1021    /// Username mismatch.
1022    #[error("username mismatch")]
1023    ErrMismatchUsername,
1024    /// The ICE conn can't write STUN messages.
1025    #[error("the ICE conn can't write STUN messages")]
1026    ErrIceWriteStunMessage,
1027    /// URL parse: relative URL without a base.
1028    #[error("url parse: relative URL without a base")]
1029    ErrUrlParse,
1030    /// Candidate IP could not be found.
1031    #[error("Candidate IP could not be found")]
1032    ErrCandidateIpNotFound,
1033
1034    // DTLS errors
1035    /// Conn is closed.
1036    #[error("conn is closed")]
1037    ErrConnClosed,
1038    /// Read/write timeout.
1039    #[error("read/write timeout")]
1040    ErrDeadlineExceeded,
1041    /// Context is not supported for export_keying_material.
1042    #[error("context is not supported for export_keying_material")]
1043    ErrContextUnsupported,
1044    /// Packet is too short.
1045    #[error("packet is too short")]
1046    ErrDtlspacketInvalidLength,
1047    /// Handshake is in progress.
1048    #[error("handshake is in progress")]
1049    ErrHandshakeInProgress,
1050    /// Invalid content type.
1051    #[error("invalid content type")]
1052    ErrInvalidContentType,
1053    /// Invalid mac.
1054    #[error("invalid mac")]
1055    ErrInvalidMac,
1056    /// Packet length and declared length do not match.
1057    #[error("packet length and declared length do not match")]
1058    ErrInvalidPacketLength,
1059    /// Export_keying_material can not be used with a reserved label.
1060    #[error("export_keying_material can not be used with a reserved label")]
1061    ErrReservedExportKeyingMaterial,
1062    /// Client sent certificate verify but we have no certificate to verify.
1063    #[error("client sent certificate verify but we have no certificate to verify")]
1064    ErrCertificateVerifyNoCertificate,
1065    /// A handshake message arrived where another was required: sent early, sent twice, or in
1066    /// place of one left out (RFC 5246 7.4).
1067    #[error("handshake message out of order")]
1068    ErrHandshakeMessageOutOfOrder,
1069    /// Client+server do not support any shared cipher suites.
1070    #[error("client+server do not support any shared cipher suites")]
1071    ErrCipherSuiteNoIntersection,
1072    /// Server hello can not be created without a cipher suite.
1073    #[error("server hello can not be created without a cipher suite")]
1074    ErrCipherSuiteUnset,
1075    /// Client sent certificate but did not verify it.
1076    #[error("client sent certificate but did not verify it")]
1077    ErrClientCertificateNotVerified,
1078    /// Server required client verification, but got none.
1079    #[error("server required client verification, but got none")]
1080    ErrClientCertificateRequired,
1081    /// Server responded with SRTP Profile we do not support.
1082    #[error("server responded with SRTP Profile we do not support")]
1083    ErrClientNoMatchingSrtpProfile,
1084    /// Client required Extended Master Secret extension, but server does not support it.
1085    #[error("client required Extended Master Secret extension, but server does not support it")]
1086    ErrClientRequiredButNoServerEms,
1087    /// Server hello can not be created without a compression method.
1088    #[error("server hello can not be created without a compression method")]
1089    ErrCompressionMethodUnset,
1090    /// Client+server cookie does not match.
1091    #[error("client+server cookie does not match")]
1092    ErrCookieMismatch,
1093    /// Cookie must not be longer then 255 bytes.
1094    #[error("cookie must not be longer then 255 bytes")]
1095    ErrCookieTooLong,
1096    /// PSK Identity Hint provided but PSK is nil.
1097    #[error("PSK Identity Hint provided but PSK is nil")]
1098    ErrIdentityNoPsk,
1099    /// No certificate provided.
1100    #[error("no certificate provided")]
1101    ErrInvalidCertificate,
1102    /// Cipher spec invalid.
1103    #[error("cipher spec invalid")]
1104    ErrInvalidCipherSpec,
1105    /// Invalid or unknown cipher suite.
1106    #[error("invalid or unknown cipher suite")]
1107    ErrInvalidCipherSuite,
1108    /// Unable to determine if ClientKeyExchange is a public key or PSK Identity.
1109    #[error("unable to determine if ClientKeyExchange is a public key or PSK Identity")]
1110    ErrInvalidClientKeyExchange,
1111    /// Invalid or unknown compression method.
1112    #[error("invalid or unknown compression method")]
1113    ErrInvalidCompressionMethod,
1114    /// ECDSA signature contained zero or negative values.
1115    #[error("ECDSA signature contained zero or negative values")]
1116    ErrInvalidEcdsasignature,
1117    /// Invalid or unknown elliptic curve type.
1118    #[error("invalid or unknown elliptic curve type")]
1119    ErrInvalidEllipticCurveType,
1120    /// Invalid extension type.
1121    #[error("invalid extension type")]
1122    ErrInvalidExtensionType,
1123    /// Invalid hash algorithm.
1124    #[error("invalid hash algorithm")]
1125    ErrInvalidHashAlgorithm,
1126    /// Invalid named curve.
1127    #[error("invalid named curve")]
1128    ErrInvalidNamedCurve,
1129    /// Invalid private key type.
1130    #[error("invalid private key type")]
1131    ErrInvalidPrivateKey,
1132    /// Named curve and private key type does not match.
1133    #[error("named curve and private key type does not match")]
1134    ErrNamedCurveAndPrivateKeyMismatch,
1135    /// Invalid server name format.
1136    #[error("invalid server name format")]
1137    ErrInvalidSniFormat,
1138    /// Invalid signature algorithm.
1139    #[error("invalid signature algorithm")]
1140    ErrInvalidSignatureAlgorithm,
1141    /// Expected and actual key signature do not match.
1142    #[error("expected and actual key signature do not match")]
1143    ErrKeySignatureMismatch,
1144    /// Conn can not be created with a nil nextConn.
1145    #[error("Conn can not be created with a nil nextConn")]
1146    ErrNilNextConn,
1147    /// Connection can not be created, no CipherSuites satisfy this Config.
1148    #[error("connection can not be created, no CipherSuites satisfy this Config")]
1149    ErrNoAvailableCipherSuites,
1150    /// Connection can not be created, no SignatureScheme satisfy this Config.
1151    #[error("connection can not be created, no SignatureScheme satisfy this Config")]
1152    ErrNoAvailableSignatureSchemes,
1153    /// No certificates configured.
1154    #[error("no certificates configured")]
1155    ErrNoCertificates,
1156    /// No config provided.
1157    #[error("no config provided")]
1158    ErrNoConfigProvided,
1159    /// Client requested zero or more elliptic curves that are not supported by the server.
1160    #[error("client requested zero or more elliptic curves that are not supported by the server")]
1161    ErrNoSupportedEllipticCurves,
1162    /// Unsupported protocol version.
1163    #[error("unsupported protocol version")]
1164    ErrUnsupportedProtocolVersion,
1165    /// Certificate and PSK provided.
1166    #[error("Certificate and PSK provided")]
1167    ErrPskAndCertificate,
1168    /// PSK and PSK Identity Hint must both be set for client.
1169    #[error("PSK and PSK Identity Hint must both be set for client")]
1170    ErrPskAndIdentityMustBeSetForClient,
1171    /// SRTP support was requested but server did not respond with use_SRTP extension.
1172    #[error("SRTP support was requested but server did not respond with use_srtp extension")]
1173    ErrRequestedButNoSrtpExtension,
1174    /// Certificate is mandatory for server.
1175    #[error("Certificate is mandatory for server")]
1176    ErrServerMustHaveCertificate,
1177    /// Client requested SRTP but we have no matching profiles.
1178    #[error("client requested SRTP but we have no matching profiles")]
1179    ErrServerNoMatchingSrtpProfile,
1180    /// Server requires the Extended Master Secret extension, but the client does not support it.
1181    #[error(
1182        "server requires the Extended Master Secret extension, but the client does not support it"
1183    )]
1184    ErrServerRequiredButNoClientEms,
1185    /// Expected and actual verify data does not match.
1186    #[error("expected and actual verify data does not match")]
1187    ErrVerifyDataMismatch,
1188    /// Handshake message unset, unable to marshal.
1189    #[error("handshake message unset, unable to marshal")]
1190    ErrHandshakeMessageUnset,
1191    /// Invalid flight number.
1192    #[error("invalid flight number")]
1193    ErrInvalidFlight,
1194    /// Unable to generate key signature, unimplemented.
1195    #[error("unable to generate key signature, unimplemented")]
1196    ErrKeySignatureGenerateUnimplemented,
1197    /// Unable to verify key signature, unimplemented.
1198    #[error("unable to verify key signature, unimplemented")]
1199    ErrKeySignatureVerifyUnimplemented,
1200    /// Data length and declared length do not match.
1201    #[error("data length and declared length do not match")]
1202    ErrLengthMismatch,
1203    /// Buffer not long enough to contain nonce.
1204    #[error("buffer not long enough to contain nonce")]
1205    ErrNotEnoughRoomForNonce,
1206    /// Feature has not been implemented yet.
1207    #[error("feature has not been implemented yet")]
1208    ErrNotImplemented,
1209    /// Sequence number overflow.
1210    #[error("sequence number overflow")]
1211    ErrSequenceNumberOverflow,
1212    /// Unable to marshal fragmented handshakes.
1213    #[error("unable to marshal fragmented handshakes")]
1214    ErrUnableToMarshalFragmented,
1215    /// Invalid state machine transition.
1216    #[error("invalid state machine transition")]
1217    ErrInvalidFsmTransition,
1218    /// ApplicationData with epoch of 0.
1219    #[error("ApplicationData with epoch of 0")]
1220    ErrApplicationDataEpochZero,
1221    /// Unhandled contentType.
1222    #[error("unhandled contentType")]
1223    ErrUnhandledContextType,
1224    /// Context canceled.
1225    #[error("context canceled")]
1226    ErrContextCanceled,
1227    /// Empty fragment.
1228    #[error("empty fragment")]
1229    ErrEmptyFragment,
1230    /// Alert is Fatal or Close Notify.
1231    #[error("Alert is Fatal or Close Notify")]
1232    ErrAlertFatalOrClose,
1233    /// A hello's renegotiation_info was not empty in an initial handshake (RFC 5746 3.4, 3.6).
1234    #[error("renegotiation_info is not empty in an initial handshake")]
1235    ErrRenegotiationInfoNotEmpty,
1236    /// The ServerHello carried an extension the ClientHello did not offer (RFC 5246 7.4.1.4).
1237    #[error("server sent an extension the client did not offer")]
1238    ErrUnsolicitedExtension,
1239    /// The ServerHello selected a compression method the ClientHello did not offer.
1240    #[error("server selected a compression method the client did not offer")]
1241    ErrCompressionMethodNotOffered,
1242    /// The ClientHello did not offer the null compression method (RFC 5246 7.4.1.2).
1243    #[error("client did not offer the null compression method")]
1244    ErrNoNullCompressionMethod,
1245    /// The server's use_srtp held an MKI the client did not offer, or not exactly one profile
1246    /// (RFC 5764 4.1.1, 4.1.3).
1247    #[error("server's use_srtp extension is not a valid answer to the client's")]
1248    ErrInvalidUseSrtpAnswer,
1249    /// Key material was asked of a session without the extended master secret (RFC 7627 5.4).
1250    #[error("no keying material is exported without the extended master secret")]
1251    ErrExportWithoutExtendedMasterSecret,
1252    /// The handshake did not complete within the configured time.
1253    #[error("handshake did not complete in time")]
1254    ErrHandshakeTimeout,
1255    /// A record's payload is longer than the 2^14 bytes a record may carry (RFC 5246 6.2.1).
1256    #[error("record payload exceeds 2^14 bytes")]
1257    ErrRecordOverflow,
1258    /// A hello carried two extensions of one type (RFC 5246 7.4.1.4).
1259    #[error("hello carries an extension type twice")]
1260    ErrDuplicateExtension,
1261    /// Fragment buffer overflow. New size is greater than specified max.
1262    #[error(
1263        "Fragment buffer overflow. New size {new_size} is greater than specified max {max_size}"
1264    )]
1265    ErrFragmentBufferOverflow {
1266        /// The size the buffer would have grown to.
1267        new_size: usize,
1268        /// The configured maximum.
1269        max_size: usize,
1270    },
1271    /// Client transport is not set yet.
1272    #[error("Client transport is not set yet")]
1273    ErrClientTransportNotSet,
1274
1275    /// The endpoint can no longer create new connections
1276    ///
1277    /// Indicates that a necessary component of the endpoint has been dropped or otherwise disabled.
1278    #[error("endpoint stopping")]
1279    EndpointStopping,
1280    /// The number of active connections on the local endpoint is at the limit
1281    ///
1282    /// Try using longer connection IDs.
1283    #[error("too many connections")]
1284    TooManyConnections,
1285    /// The domain name supplied was malformed
1286    #[error("invalid DNS name: {0}")]
1287    InvalidDnsName(String),
1288    /// The remote [`SocketAddr`] supplied was malformed
1289    ///
1290    /// Examples include attempting to connect to port 0, or using an inappropriate address family.
1291    #[error("invalid remote address: {0}")]
1292    InvalidRemoteAddress(SocketAddr),
1293    /// No client configuration was set up
1294    #[error("no client config")]
1295    NoClientConfig,
1296    /// No server configuration was set up
1297    #[error("no server config")]
1298    NoServerConfig,
1299
1300    //SCTP errors
1301    /// Raw is too small for a SCTP chunk.
1302    #[error("raw is too small for a SCTP chunk")]
1303    ErrChunkHeaderTooSmall,
1304    /// Not enough data left in SCTP packet to satisfy requested length.
1305    #[error("not enough data left in SCTP packet to satisfy requested length")]
1306    ErrChunkHeaderNotEnoughSpace,
1307    /// Chunk PADDING is non-zero at offset.
1308    #[error("chunk PADDING is non-zero at offset")]
1309    ErrChunkHeaderPaddingNonZero,
1310    /// Chunk has invalid length.
1311    #[error("chunk has invalid length")]
1312    ErrChunkHeaderInvalidLength,
1313
1314    /// ChunkType is not of type ABORT.
1315    #[error("ChunkType is not of type ABORT")]
1316    ErrChunkTypeNotAbort,
1317    /// Failed build Abort Chunk.
1318    #[error("failed build Abort Chunk")]
1319    ErrBuildAbortChunkFailed,
1320    /// ChunkType is not of type COOKIEACK.
1321    #[error("ChunkType is not of type COOKIEACK")]
1322    ErrChunkTypeNotCookieAck,
1323    /// ChunkType is not of type COOKIEECHO.
1324    #[error("ChunkType is not of type COOKIEECHO")]
1325    ErrChunkTypeNotCookieEcho,
1326    /// ChunkType is not of type ctError.
1327    #[error("ChunkType is not of type ctError")]
1328    ErrChunkTypeNotCt,
1329    /// Failed build Error Chunk.
1330    #[error("failed build Error Chunk")]
1331    ErrBuildErrorChunkFailed,
1332    /// Failed to marshal stream.
1333    #[error("failed to marshal stream")]
1334    ErrMarshalStreamFailed,
1335    /// Chunk too short.
1336    #[error("chunk too short")]
1337    ErrChunkTooShort,
1338    /// ChunkType is not of type ForwardTsn.
1339    #[error("ChunkType is not of type ForwardTsn")]
1340    ErrChunkTypeNotForwardTsn,
1341    /// ChunkType is not of type HEARTBEAT.
1342    #[error("ChunkType is not of type HEARTBEAT")]
1343    ErrChunkTypeNotHeartbeat,
1344    /// ChunkType is not of type HEARTBEATACK.
1345    #[error("ChunkType is not of type HEARTBEATACK")]
1346    ErrChunkTypeNotHeartbeatAck,
1347    /// Heartbeat is not long enough to contain Heartbeat Info.
1348    #[error("heartbeat is not long enough to contain Heartbeat Info")]
1349    ErrHeartbeatNotLongEnoughInfo,
1350    /// Failed to parse param type.
1351    #[error("failed to parse param type")]
1352    ErrParseParamTypeFailed,
1353    /// Heartbeat should only have HEARTBEAT param.
1354    #[error("heartbeat should only have HEARTBEAT param")]
1355    ErrHeartbeatParam,
1356    /// Failed unmarshalling param in Heartbeat Chunk.
1357    #[error("failed unmarshalling param in Heartbeat Chunk")]
1358    ErrHeartbeatChunkUnmarshal,
1359    /// Unimplemented.
1360    #[error("unimplemented")]
1361    ErrUnimplemented,
1362    /// Heartbeat Ack must have one param.
1363    #[error("heartbeat Ack must have one param")]
1364    ErrHeartbeatAckParams,
1365    /// Heartbeat Ack must have one param, and it should be a HeartbeatInfo.
1366    #[error("heartbeat Ack must have one param, and it should be a HeartbeatInfo")]
1367    ErrHeartbeatAckNotHeartbeatInfo,
1368    /// Unable to marshal parameter for Heartbeat Ack.
1369    #[error("unable to marshal parameter for Heartbeat Ack")]
1370    ErrHeartbeatAckMarshalParam,
1371
1372    /// Raw is too small for error cause.
1373    #[error("raw is too small for error cause")]
1374    ErrErrorCauseTooSmall,
1375
1376    /// Unhandled ParamType.
1377    #[error("unhandled ParamType: {typ}")]
1378    ErrParamTypeUnhandled {
1379        /// The raw parameter type that was not recognised.
1380        typ: u16,
1381    },
1382
1383    /// Unexpected ParamType.
1384    #[error("unexpected ParamType")]
1385    ErrParamTypeUnexpected,
1386
1387    /// Param header too short.
1388    #[error("param header too short")]
1389    ErrParamHeaderTooShort,
1390    /// Param self reported length is shorter than header length.
1391    #[error("param self reported length is shorter than header length")]
1392    ErrParamHeaderSelfReportedLengthShorter,
1393    /// Param self reported length is longer than header length.
1394    #[error("param self reported length is longer than header length")]
1395    ErrParamHeaderSelfReportedLengthLonger,
1396    /// Failed to parse param type.
1397    #[error("failed to parse param type")]
1398    ErrParamHeaderParseFailed,
1399
1400    /// Packet to short.
1401    #[error("packet to short")]
1402    ErrParamPacketTooShort,
1403    /// Outgoing SSN reset request parameter too short.
1404    #[error("outgoing SSN reset request parameter too short")]
1405    ErrSsnResetRequestParamTooShort,
1406    /// Failed unmarshalling SSN reset request parameter in RE-CONFIG chunk.
1407    #[error("failed unmarshalling SSN reset request parameter in RE-CONFIG chunk")]
1408    ErrUnmarshalSsnResetRequestParam,
1409    /// Reconfig response parameter too short.
1410    #[error("reconfig response parameter too short")]
1411    ErrReconfigRespParamTooShort,
1412    /// Failed unmarshalling re-configuration response parameter in RE-CONFIG chunk.
1413    #[error("failed unmarshalling re-configuration response parameter in RE-CONFIG chunk")]
1414    ErrUnmarshalReconfigRespParam,
1415    /// Invalid algorithm type.
1416    #[error("invalid algorithm type")]
1417    ErrInvalidAlgorithmType,
1418
1419    /// Failed to parse param type.
1420    #[error("failed to parse param type")]
1421    ErrInitChunkParseParamTypeFailed,
1422    /// Failed unmarshalling param in Init Chunk.
1423    #[error("failed unmarshalling param in Init Chunk")]
1424    ErrInitChunkUnmarshalParam,
1425    /// Unable to marshal parameter for INIT/INITACK.
1426    #[error("unable to marshal parameter for INIT/INITACK")]
1427    ErrInitAckMarshalParam,
1428
1429    /// ChunkType is not of type INIT.
1430    #[error("ChunkType is not of type INIT")]
1431    ErrChunkTypeNotTypeInit,
1432    /// Chunk Value isn't long enough for mandatory parameters exp.
1433    #[error("chunk Value isn't long enough for mandatory parameters exp")]
1434    ErrChunkValueNotLongEnough,
1435    /// ChunkType of type INIT flags must be all 0.
1436    #[error("ChunkType of type INIT flags must be all 0")]
1437    ErrChunkTypeInitFlagZero,
1438    /// Failed to unmarshal INIT body.
1439    #[error("failed to unmarshal INIT body")]
1440    ErrChunkTypeInitUnmarshalFailed,
1441    /// Failed marshaling INIT common data.
1442    #[error("failed marshaling INIT common data")]
1443    ErrChunkTypeInitMarshalFailed,
1444    /// ChunkType of type INIT ACK InitiateTag must not be 0.
1445    #[error("ChunkType of type INIT ACK InitiateTag must not be 0")]
1446    ErrChunkTypeInitInitiateTagZero,
1447    /// INIT ACK inbound stream request must be > 0.
1448    #[error("INIT ACK inbound stream request must be > 0")]
1449    ErrInitInboundStreamRequestZero,
1450    /// INIT ACK outbound stream request must be > 0.
1451    #[error("INIT ACK outbound stream request must be > 0")]
1452    ErrInitOutboundStreamRequestZero,
1453    /// INIT ACK Advertised Receiver Window Credit (a_rwnd) must be >= 1500.
1454    #[error("INIT ACK Advertised Receiver Window Credit (a_rwnd) must be >= 1500")]
1455    ErrInitAdvertisedReceiver1500,
1456
1457    /// Packet is smaller than the header size.
1458    #[error("packet is smaller than the header size")]
1459    ErrChunkPayloadSmall,
1460    /// ChunkType is not of type PayloadData.
1461    #[error("ChunkType is not of type PayloadData")]
1462    ErrChunkTypeNotPayloadData,
1463    /// Failed unmarshalling payload data chunk.
1464    #[error("failed unmarshalling payload data chunk")]
1465    ErrChunkUnmarshalPayloadData,
1466    /// ChunkType is not of type Reconfig.
1467    #[error("ChunkType is not of type Reconfig")]
1468    ErrChunkTypeNotReconfig,
1469    /// ChunkReconfig has invalid ParamA.
1470    #[error("ChunkReconfig has invalid ParamA")]
1471    ErrChunkReconfigInvalidParamA,
1472
1473    /// Failed to parse param type.
1474    #[error("failed to parse param type")]
1475    ErrChunkParseParamTypeFailed,
1476    /// Unable to marshal parameter A for reconfig.
1477    #[error("unable to marshal parameter A for reconfig")]
1478    ErrChunkMarshalParamAReconfigFailed,
1479    /// Unable to marshal parameter B for reconfig.
1480    #[error("unable to marshal parameter B for reconfig")]
1481    ErrChunkMarshalParamBReconfigFailed,
1482
1483    /// ChunkType is not of type SACK.
1484    #[error("ChunkType is not of type SACK")]
1485    ErrChunkTypeNotSack,
1486    /// SACK Chunk size is not large enough to contain header.
1487    #[error("SACK Chunk size is not large enough to contain header")]
1488    ErrSackSizeNotLargeEnoughInfo,
1489    /// Failed unmarshalling SACK chunk.
1490    #[error("failed unmarshalling SACK chunk")]
1491    ErrChunkUnmarshalSack,
1492
1493    /// Invalid chunk size.
1494    #[error("invalid chunk size")]
1495    ErrInvalidChunkSize,
1496    /// ChunkType is not of type SHUTDOWN.
1497    #[error("ChunkType is not of type SHUTDOWN")]
1498    ErrChunkTypeNotShutdown,
1499    /// Failed unmarshalling shutdown chunk.
1500    #[error("failed unmarshalling shutdown chunk")]
1501    ErrChunkUnmarshalShutdown,
1502
1503    /// ChunkType is not of type SHUTDOWN-ACK.
1504    #[error("ChunkType is not of type SHUTDOWN-ACK")]
1505    ErrChunkTypeNotShutdownAck,
1506    /// ChunkType is not of type SHUTDOWN-COMPLETE.
1507    #[error("ChunkType is not of type SHUTDOWN-COMPLETE")]
1508    ErrChunkTypeNotShutdownComplete,
1509
1510    /// Raw is smaller than the minimum length for a SCTP packet.
1511    #[error("raw is smaller than the minimum length for a SCTP packet")]
1512    ErrPacketRawTooSmall,
1513    /// Unable to parse SCTP chunk, not enough data for complete header.
1514    #[error("unable to parse SCTP chunk, not enough data for complete header")]
1515    ErrParseSctpChunkNotEnoughData,
1516    /// Failed to unmarshal, contains unknown chunk type.
1517    #[error("failed to unmarshal, contains unknown chunk type")]
1518    ErrUnmarshalUnknownChunkType,
1519    /// Checksum mismatch theirs.
1520    #[error("checksum mismatch theirs")]
1521    ErrChecksumMismatch,
1522
1523    /// Unexpected chunk popped (unordered).
1524    #[error("unexpected chunk popped (unordered)")]
1525    ErrUnexpectedChuckPoppedUnordered,
1526    /// Unexpected chunk popped (ordered).
1527    #[error("unexpected chunk popped (ordered)")]
1528    ErrUnexpectedChuckPoppedOrdered,
1529    /// Unexpected q state (should've been selected).
1530    #[error("unexpected q state (should've been selected)")]
1531    ErrUnexpectedQState,
1532    /// Try again.
1533    #[error("try again")]
1534    ErrTryAgain,
1535
1536    /// Abort chunk, with following errors.
1537    #[error("abort chunk, with following errors: {0}")]
1538    ErrAbortChunk(String),
1539    /// Shutdown called in non-Established state.
1540    #[error("shutdown called in non-Established state")]
1541    ErrShutdownNonEstablished,
1542    /// Association closed before connecting.
1543    #[error("association closed before connecting")]
1544    ErrAssociationClosedBeforeConn,
1545    /// Association init failed.
1546    #[error("association init failed")]
1547    ErrAssociationInitFailed,
1548    /// Association handshake closed.
1549    #[error("association handshake closed")]
1550    ErrAssociationHandshakeClosed,
1551    /// Silently discard.
1552    #[error("silently discard")]
1553    ErrSilentlyDiscard,
1554    /// The init not stored to send.
1555    #[error("the init not stored to send")]
1556    ErrInitNotStoredToSend,
1557    /// CookieEcho not stored to send.
1558    #[error("cookieEcho not stored to send")]
1559    ErrCookieEchoNotStoredToSend,
1560    /// SCTP packet must not have a source port of 0.
1561    #[error("sctp packet must not have a source port of 0")]
1562    ErrSctpPacketSourcePortZero,
1563    /// SCTP packet must not have a destination port of 0.
1564    #[error("sctp packet must not have a destination port of 0")]
1565    ErrSctpPacketDestinationPortZero,
1566    /// Init chunk must not be bundled with any other chunk.
1567    #[error("init chunk must not be bundled with any other chunk")]
1568    ErrInitChunkBundled,
1569    /// A SHUTDOWN COMPLETE chunk must not be bundled with any other chunk (RFC 9260 3.1,
1570    /// 6.10).
1571    #[error("shutdown complete chunk must not be bundled with any other chunk")]
1572    ErrShutdownCompleteChunkBundled,
1573    /// Init chunk expects a verification tag of 0 on the packet when out-of-the-blue.
1574    #[error("init chunk expects a verification tag of 0 on the packet when out-of-the-blue")]
1575    ErrInitChunkVerifyTagNotZero,
1576    /// Todo: handle Init when in state.
1577    #[error("todo: handle Init when in state")]
1578    ErrHandleInitState,
1579    /// No cookie in InitAck.
1580    #[error("no cookie in InitAck")]
1581    ErrInitAckNoCookie,
1582    /// There already exists a stream with identifier.
1583    #[error("there already exists a stream with identifier")]
1584    ErrStreamAlreadyExist,
1585    /// Failed to create a stream with identifier.
1586    #[error("Failed to create a stream with identifier")]
1587    ErrStreamCreateFailed,
1588    /// Unable to be popped from inflight queue TSN.
1589    #[error("unable to be popped from inflight queue TSN")]
1590    ErrInflightQueueTsnPop,
1591    /// Requested non-existent TSN.
1592    #[error("requested non-existent TSN")]
1593    ErrTsnRequestNotExist,
1594    /// Sending reset packet in non-Established state.
1595    #[error("sending reset packet in non-Established state")]
1596    ErrResetPacketInStateNotExist,
1597    /// Unexpected parameter type.
1598    #[error("unexpected parameter type")]
1599    ErrParameterType,
1600    /// Sending payload data in non-Established state.
1601    #[error("sending payload data in non-Established state")]
1602    ErrPayloadDataStateNotExist,
1603    /// Unhandled chunk type.
1604    #[error("unhandled chunk type")]
1605    ErrChunkTypeUnhandled,
1606    /// Handshake failed (INIT ACK).
1607    #[error("handshake failed (INIT ACK)")]
1608    ErrHandshakeInitAck,
1609    /// Handshake failed (COOKIE ECHO).
1610    #[error("handshake failed (COOKIE ECHO)")]
1611    ErrHandshakeCookieEcho,
1612
1613    /// Outbound packet larger than maximum message size.
1614    #[error("outbound packet larger than maximum message size")]
1615    ErrOutboundPacketTooLarge,
1616    /// A data channel message over the 16 KB a sender keeps to on an SCTP association without
1617    /// user message interleaving (RFC 8831 section 6.6), which is every association with a
1618    /// peer that does not announce I-DATA (RFC 8260), current browsers among them.
1619    #[error(
1620        "a {size} byte message is over the {limit} byte limit of an SCTP association without \
1621         message interleaving (RFC 8831 section 6.6: the peer did not announce I-DATA); \
1622         SettingEngineBuilder::with_sctp_message_size_limit_without_interleaving(false) lifts it \
1623         up to the peer's max-message-size"
1624    )]
1625    ErrMessageTooLargeWithoutInterleaving {
1626        /// The size of the message refused.
1627        size: usize,
1628        /// The limit, `maxMessageSize` (16384).
1629        limit: u32,
1630    },
1631    /// Stream closed.
1632    #[error("Stream closed")]
1633    ErrStreamClosed,
1634    /// Stream not existed.
1635    #[error("Stream not existed")]
1636    ErrStreamNotExisted,
1637    /// Association not existed.
1638    #[error("Association not existed")]
1639    ErrAssociationNotExisted,
1640    /// Transport not existed.
1641    #[error("Transport not existed")]
1642    ErrTransportNoExisted,
1643    /// Io EOF.
1644    #[error("Io EOF")]
1645    ErrEof,
1646    /// Invalid SystemTime.
1647    #[error("Invalid SystemTime")]
1648    ErrInvalidSystemTime,
1649    /// Net Conn read error.
1650    #[error("Net Conn read error")]
1651    ErrNetConnRead,
1652    /// Max Data Channel ID.
1653    #[error("Max Data Channel ID")]
1654    ErrMaxDataChannelID,
1655
1656    //Data Channel
1657    /// DataChannel message is not long enough to determine type: (expected: , actual: ).
1658    #[error(
1659        "DataChannel message is not long enough to determine type: (expected: {expected}, actual: {actual})"
1660    )]
1661    UnexpectedEndOfBuffer {
1662        /// The number of bytes the parser required.
1663        expected: usize,
1664        /// The number of bytes actually available.
1665        actual: usize,
1666    },
1667    /// Unknown MessageType.
1668    #[error("Unknown MessageType {0}")]
1669    InvalidMessageType(u8),
1670    /// Unknown ChannelType.
1671    #[error("Unknown ChannelType {0}")]
1672    InvalidChannelType(u8),
1673    /// Unknown PayloadProtocolIdentifier.
1674    #[error("Unknown PayloadProtocolIdentifier {0}")]
1675    InvalidPayloadProtocolIdentifier(u8),
1676    /// Unknow Protocol.
1677    #[error("Unknow Protocol")]
1678    UnknownProtocol,
1679
1680    //Media
1681    /// Stream is nil.
1682    #[error("stream is nil")]
1683    ErrNilStream,
1684    /// Incomplete frame header.
1685    #[error("incomplete frame header")]
1686    ErrIncompleteFrameHeader,
1687    /// Incomplete frame data.
1688    #[error("incomplete frame data")]
1689    ErrIncompleteFrameData,
1690    /// Incomplete file header.
1691    #[error("incomplete file header")]
1692    ErrIncompleteFileHeader,
1693    /// IVF signature mismatch.
1694    #[error("IVF signature mismatch")]
1695    ErrSignatureMismatch,
1696    /// IVF version unknown, parser may not parse correctly.
1697    #[error("IVF version unknown, parser may not parse correctly")]
1698    ErrUnknownIVFVersion,
1699
1700    /// File not opened.
1701    #[error("file not opened")]
1702    ErrFileNotOpened,
1703    /// Invalid nil packet.
1704    #[error("invalid nil packet")]
1705    ErrInvalidNilPacket,
1706
1707    /// Bad header signature.
1708    #[error("bad header signature")]
1709    ErrBadIDPageSignature,
1710    /// Wrong header, expected beginning of stream.
1711    #[error("wrong header, expected beginning of stream")]
1712    ErrBadIDPageType,
1713    /// Payload for id page must be 19 bytes.
1714    #[error("payload for id page must be 19 bytes")]
1715    ErrBadIDPageLength,
1716    /// Bad payload signature.
1717    #[error("bad payload signature")]
1718    ErrBadIDPagePayloadSignature,
1719    /// Not enough data for payload header.
1720    #[error("not enough data for payload header")]
1721    ErrShortPageHeader,
1722    /// Bad OpusTags signature.
1723    #[error("bad OpusTags signature")]
1724    ErrBadOpusTagsSignature,
1725    /// Unsupported channel mapping family.
1726    #[error("unsupported channel mapping family")]
1727    ErrUnsupportedChannelMappingFamily,
1728
1729    /// Data is not a H264 bitstream.
1730    #[error("data is not a H264 bitstream")]
1731    ErrDataIsNotH264Stream,
1732    /// Data is not a H265 bitstream.
1733    #[error("data is not a H265 bitstream")]
1734    ErrDataIsNotH265Stream,
1735    /// Io EOF.
1736    #[error("Io EOF")]
1737    ErrIoEOF,
1738
1739    // mDNS
1740    /// MDNS: port not support, only 5353 is supported.
1741    #[error("mDNS: port not support, only 5353 is supported")]
1742    ErrMDNSPortNotSupported,
1743    /// MDNS: connection is closed.
1744    #[error("mDNS: connection is closed")]
1745    ErrMDNSConnectionClosed,
1746    /// MDNS: query not found.
1747    #[error("mDNS: query not found")]
1748    ErrMDNSQueryNotFound,
1749    /// MDNS: parsing/packing of this type isn't available yet.
1750    #[error("mDNS: parsing/packing of this type isn't available yet")]
1751    ErrNotStarted,
1752    /// MDNS: parsing/packing of this section has completed.
1753    #[error("mDNS: parsing/packing of this section has completed")]
1754    ErrSectionDone,
1755    /// MDNS: parsing/packing of this section is header.
1756    #[error("mDNS: parsing/packing of this section is header")]
1757    ErrSectionHeader,
1758    /// MDNS: insufficient data for base length type.
1759    #[error("mDNS: insufficient data for base length type")]
1760    ErrBaseLen,
1761    /// MDNS: insufficient data for calculated length type.
1762    #[error("mDNS: insufficient data for calculated length type")]
1763    ErrCalcLen,
1764    /// MDNS: segment prefix is reserved.
1765    #[error("mDNS: segment prefix is reserved")]
1766    ErrReserved,
1767    /// MDNS: too many pointers (>10).
1768    #[error("mDNS: too many pointers (>10)")]
1769    ErrTooManyPtr,
1770    /// MDNS: invalid pointer.
1771    #[error("mDNS: invalid pointer")]
1772    ErrInvalidPtr,
1773    /// MDNS: nil resource body.
1774    #[error("mDNS: nil resource body")]
1775    ErrNilResourceBody,
1776    /// MDNS: insufficient data for resource body length.
1777    #[error("mDNS: insufficient data for resource body length")]
1778    ErrResourceLen,
1779    /// MDNS: segment length too long.
1780    #[error("mDNS: segment length too long")]
1781    ErrSegTooLong,
1782    /// MDNS: zero length segment.
1783    #[error("mDNS: zero length segment")]
1784    ErrZeroSegLen,
1785    /// MDNS: resource length too long.
1786    #[error("mDNS: resource length too long")]
1787    ErrResTooLong,
1788    /// MDNS: too many Questions to pack (>65535).
1789    #[error("mDNS: too many Questions to pack (>65535)")]
1790    ErrTooManyQuestions,
1791    /// MDNS: too many Answers to pack (>65535).
1792    #[error("mDNS: too many Answers to pack (>65535)")]
1793    ErrTooManyAnswers,
1794    /// MDNS: too many Authorities to pack (>65535).
1795    #[error("mDNS: too many Authorities to pack (>65535)")]
1796    ErrTooManyAuthorities,
1797    /// MDNS: too many Additionals to pack (>65535).
1798    #[error("mDNS: too many Additionals to pack (>65535)")]
1799    ErrTooManyAdditionals,
1800    /// MDNS: name is not in canonical format (it must end with a .).
1801    #[error("mDNS: name is not in canonical format (it must end with a .)")]
1802    ErrNonCanonicalName,
1803    /// MDNS: character string exceeds maximum length (255).
1804    #[error("mDNS: character string exceeds maximum length (255)")]
1805    ErrStringTooLong,
1806    /// MDNS: compressed name in SRV resource data.
1807    #[error("mDNS: compressed name in SRV resource data")]
1808    ErrCompressedSrv,
1809    /// MDNS: empty builder msg.
1810    #[error("mDNS: empty builder msg")]
1811    ErrEmptyBuilderMsg,
1812
1813    //RTC
1814    /// ErrConnectionClosed indicates an operation executed after connection
1815    /// has already been closed.
1816    #[error("connection closed")]
1817    ErrConnectionClosed,
1818
1819    /// ErrDataChannelClosed indicates an operation executed when the data
1820    /// channel is not (yet) open or closed.
1821    #[error("data channel closed")]
1822    ErrDataChannelClosed,
1823
1824    /// ErrDataChannelNotOpen indicates a send was attempted on a data channel
1825    /// whose underlying SCTP stream has not been established yet — its
1826    /// `ready_state` is still `connecting`. Wait for the channel to open.
1827    #[error("data channel is not open yet")]
1828    ErrDataChannelNotOpen,
1829
1830    /// ErrDataChannelStreamIdNotAssigned indicates an operation that needs the channel's SCTP
1831    /// stream identifier ran before one was assigned.
1832    ///
1833    /// A data channel announced in-band has no stream identifier until the SCTP connected
1834    /// procedure assigns one, because RFC 8832 section 6 ties its parity to the DTLS role:
1835    /// even for the client, odd for the server. Until that role is resolved there is no
1836    /// correct identifier to pick, so the channel carries none rather than a guess.
1837    #[error("data channel stream identifier has not been assigned yet")]
1838    ErrDataChannelStreamIdNotAssigned,
1839
1840    /// ErrDataChannelNonExist indicates an operation executed when the data
1841    /// channel not existed.
1842    #[error("data channel not existed")]
1843    ErrDataChannelNotExisted,
1844
1845    /// ErrSendBufferFull indicates that a data-channel send was rejected because
1846    /// the channel's outstanding send buffer exceeded the configured hard ceiling
1847    /// (back-pressure). Retry after the buffer drains (e.g. on OnBufferedAmountLow).
1848    #[error("data channel send buffer full")]
1849    ErrSendBufferFull,
1850
1851    /// ErrCertificateExpired indicates that an x509 certificate has expired.
1852    #[error("x509Cert expired")]
1853    ErrCertificateExpired,
1854
1855    /// An ICE server with no url (W3C "set a configuration": "If urls is empty, throw a
1856    /// SyntaxError").
1857    #[error("an ICE server has no url")]
1858    ErrNoIceServerUrls,
1859
1860    /// ErrNoTurnCredentials indicates that a TURN server URL was provided
1861    /// without required credentials.
1862    #[error("turn server credentials required")]
1863    ErrNoTurnCredentials,
1864
1865    /// ErrTurnCredentials indicates that provided TURN credentials are partial
1866    /// or malformed.
1867    #[error("invalid turn server credentials")]
1868    ErrTurnCredentials,
1869
1870    /// ErrExistingTrack indicates that a track already exists.
1871    #[error("track already exists")]
1872    ErrExistingTrack,
1873
1874    /// ErrExistingTrack indicates that a track already exists.
1875    #[error("track not existed")]
1876    ErrTrackNotExisted,
1877
1878    /// ErrPrivateKeyType indicates that a particular private key encryption
1879    /// chosen to generate a certificate is not supported.
1880    #[error("private key type not supported")]
1881    ErrPrivateKeyType,
1882
1883    /// ErrModifyingPeerIdentity indicates that an attempt to modify
1884    /// PeerIdentity was made after PeerConnection has been initialized.
1885    #[error("peerIdentity cannot be modified")]
1886    ErrModifyingPeerIdentity,
1887
1888    /// ErrModifyingCertificates indicates that an attempt to modify
1889    /// Certificates was made after PeerConnection has been initialized.
1890    #[error("certificates cannot be modified")]
1891    ErrModifyingCertificates,
1892
1893    /// ErrNonCertificate indicates that there is no certificate
1894    #[error("no certificate")]
1895    ErrNonCertificate,
1896
1897    /// ErrModifyingBundlePolicy indicates that an attempt to modify
1898    /// BundlePolicy was made after PeerConnection has been initialized.
1899    #[error("bundle policy cannot be modified")]
1900    ErrModifyingBundlePolicy,
1901
1902    /// ErrModifyingRTCPMuxPolicy indicates that an attempt to modify
1903    /// RTCPMuxPolicy was made after PeerConnection has been initialized.
1904    #[error("rtcp mux policy cannot be modified")]
1905    ErrModifyingRTCPMuxPolicy,
1906
1907    /// ErrModifyingICECandidatePoolSize indicates that an attempt to modify
1908    /// ICECandidatePoolSize was made after PeerConnection has been initialized.
1909    #[error("ice candidate pool size cannot be modified")]
1910    ErrModifyingICECandidatePoolSize,
1911
1912    /// ErrStringSizeLimit indicates that the character size limit of string is
1913    /// exceeded. The limit is hardcoded to 65535 according to specifications.
1914    #[error("data channel label exceeds size limit")]
1915    ErrStringSizeLimit,
1916
1917    /// ErrNegotiatedWithoutID indicates that an attempt to create a data channel
1918    /// was made while setting the negotiated option to true without providing
1919    /// the negotiated channel ID.
1920    #[error("negotiated set without channel id")]
1921    ErrNegotiatedWithoutID,
1922
1923    /// ErrRetransmitsOrPacketLifeTime indicates that an attempt to create a data
1924    /// channel was made with both options max_packet_life_time and max_retransmits
1925    /// set together. Such configuration is not supported by the specification
1926    /// and is mutually exclusive.
1927    #[error("both max_packet_life_time and max_retransmits was set")]
1928    ErrRetransmitsOrPacketLifeTime,
1929
1930    /// ErrCodecNotFound is returned when a codec search to the Media Engine fails
1931    #[error("codec not found")]
1932    ErrCodecNotFound,
1933
1934    /// ErrNoRemoteDescription indicates that an operation was rejected because
1935    /// the remote description is not set
1936    #[error("remote description is not set")]
1937    ErrNoRemoteDescription,
1938
1939    /// ErrIceCandidateMediaSectionNotFound indicates that the sdpMid or sdpMLineIndex of a
1940    /// remote candidate names no media section of the remote description
1941    #[error(
1942        "no media section of the remote description matches the candidate's sdpMid or sdpMLineIndex"
1943    )]
1944    ErrIceCandidateMediaSectionNotFound,
1945
1946    /// ErrIceCandidateUsernameFragmentMismatch indicates that the usernameFragment of a remote
1947    /// candidate is not the ice-ufrag of its media section in the remote description
1948    #[error("the candidate's usernameFragment is not its media section's ice-ufrag")]
1949    ErrIceCandidateUsernameFragmentMismatch,
1950
1951    /// ErrSessionDescriptionInvalidIceCredentials indicates set_remote_description was called
1952    /// with an ice-ufrag or ice-pwd that is not RFC 8839 §5.4 syntax (4 to 256, or 22 to 256,
1953    /// ice-chars: ALPHA, DIGIT, "+" and "/")
1954    #[error(
1955        "set_remote_description called with an ice-ufrag or ice-pwd that isn't RFC 8839 syntax"
1956    )]
1957    ErrSessionDescriptionInvalidIceCredentials,
1958
1959    /// ErrIncorrectSDPSemantics indicates that the PeerConnection was configured to
1960    /// generate SDP Answers with different SDP Semantics than the received Offer
1961    #[error("offer SDP semantics does not match configuration")]
1962    ErrIncorrectSDPSemantics,
1963
1964    /// ErrIncorrectSignalingState indicates that the signaling state of PeerConnection is not correct
1965    #[error("operation can not be run in current signaling state")]
1966    ErrIncorrectSignalingState,
1967
1968    /// ErrProtocolTooLarge indicates that value given for a DataChannelInit protocol is
1969    /// longer then 65535 bytes
1970    #[error("protocol is larger then 65535 bytes")]
1971    ErrProtocolTooLarge,
1972
1973    /// ErrLabelTooLarge indicates that the label given for a data channel is longer than the
1974    /// 65535 bytes a DATA_CHANNEL_OPEN can carry (RFC 8832 section 5.1)
1975    #[error("label is larger than 65535 bytes")]
1976    ErrLabelTooLarge,
1977
1978    /// An SRTP or SRTCP replay window of 1 to 63 packets (RFC 3711 section 3.3.2: at least 64).
1979    #[error("the {0} replay window of {1} packets is below the 64 RFC 3711 requires")]
1980    ErrSrtpReplayWindowTooSmall(&'static str, usize),
1981
1982    /// W3C `OperationError`, with what failed.
1983    #[error("OperationError: {0}")]
1984    ErrOperationError(String),
1985
1986    /// A character `insertDTMF` does not take (W3C: an `InvalidCharacterError`).
1987    #[error("{0:?} is not a DTMF tone")]
1988    ErrDtmfInvalidCharacter(char),
1989
1990    /// A send would take a data channel's `bufferedAmount` above the SCTP transport's
1991    /// `[[MaxBufferSize]]` (W3C `send()`: an `OperationError`).
1992    #[error("the data channel's send buffer is full")]
1993    ErrDataChannelBufferFull,
1994
1995    /// A negotiated data channel id at or above the connected SCTP transport's `maxChannels`
1996    /// (W3C createDataChannel: an `OperationError`).
1997    #[error("the data channel id is not below the SCTP transport's maxChannels")]
1998    ErrDataChannelIdAboveMaxChannels,
1999
2000    /// ErrDataChannelIdInUse indicates that a data channel was created with a negotiated id
2001    /// whose SCTP stream already carries a data channel (RFC 8831 section 6.5)
2002    #[error("data channel id is already in use")]
2003    ErrDataChannelIdInUse,
2004
2005    /// ErrSenderNotCreatedByConnection indicates remove_track was called with a RtpSender not created
2006    /// by this PeerConnection
2007    #[error("RtpSender not created by this PeerConnection")]
2008    ErrSenderNotCreatedByConnection,
2009
2010    /// ErrSenderInitialTrackIdAlreadySet indicates a second call to
2011    /// RtpSender::set_initial_track_id which is not allowed.
2012    #[error("RtpSender's initial_track_id has already been set")]
2013    ErrSenderInitialTrackIdAlreadySet,
2014
2015    /// ErrSessionDescriptionNoFingerprint indicates set_remote_description was called with a SessionDescription that has no
2016    /// fingerprint
2017    #[error("set_remote_description called with no fingerprint")]
2018    ErrSessionDescriptionNoFingerprint,
2019
2020    /// ErrSessionDescriptionInvalidFingerprint indicates set_remote_description was called with a SessionDescription that
2021    /// has an invalid fingerprint
2022    #[error("set_remote_description called with an invalid fingerprint")]
2023    ErrSessionDescriptionInvalidFingerprint,
2024
2025    /// ErrSessionDescriptionConflictingFingerprints indicates set_remote_description was called with a SessionDescription that
2026    /// has an conflicting fingerprints
2027    #[error("set_remote_description called with multiple conflicting fingerprint")]
2028    ErrSessionDescriptionConflictingFingerprints,
2029
2030    /// ErrSessionDescriptionInvalidSetup indicates set_remote_description was called with a SessionDescription whose
2031    /// `a=setup` value is not `active`, `passive` or `actpass` (RFC 4145 section 4; RFC 8842 section 5.1 bars
2032    /// `holdconn` from DTLS), or whose sections give different values for the one transport
2033    #[error("set_remote_description called with an invalid setup attribute")]
2034    ErrSessionDescriptionInvalidSetup,
2035
2036    /// ErrSessionDescriptionInvalidTlsId indicates set_remote_description was called with a SessionDescription whose
2037    /// `a=tls-id` value is not 20 to 255 characters of the RFC 8842 section 4 alphabet, or whose sections give
2038    /// different values for the one transport
2039    #[error("set_remote_description called with an invalid tls-id attribute")]
2040    ErrSessionDescriptionInvalidTlsId,
2041
2042    /// ErrInvalidIdentityAssertion indicates an `a=identity` value that does not follow RFC 8827 section 5
2043    #[error("invalid identity assertion")]
2044    ErrInvalidIdentityAssertion,
2045
2046    /// ErrSessionDescriptionMissingIceUfrag indicates set_remote_description was called with a SessionDescription that
2047    /// is missing an ice-ufrag value
2048    #[error("set_remote_description called with no ice-ufrag")]
2049    ErrSessionDescriptionMissingIceUfrag,
2050
2051    /// ErrSessionDescriptionMissingIcePwd indicates set_remote_description was called with a SessionDescription that
2052    /// is missing an ice-pwd value
2053    #[error("set_remote_description called with no ice-pwd")]
2054    ErrSessionDescriptionMissingIcePwd,
2055
2056    /// ErrSessionDescriptionConflictingIceUfrag  indicates set_remote_description was called with a SessionDescription that
2057    /// contains multiple conflicting ice-ufrag values
2058    #[error("set_remote_description called with multiple conflicting ice-ufrag values")]
2059    ErrSessionDescriptionConflictingIceUfrag,
2060
2061    /// ErrSessionDescriptionConflictingIcePwd indicates set_remote_description was called with a SessionDescription that
2062    /// contains multiple conflicting ice-pwd values
2063    #[error("set_remote_description called with multiple conflicting ice-pwd values")]
2064    ErrSessionDescriptionConflictingIcePwd,
2065
2066    /// ErrSessionDescriptionMissingCryptex indicates set_remote_description was called, under
2067    /// the `Require` RTP header encryption policy, with a SessionDescription that has an RTP
2068    /// media section without Cryptex (RFC 9335 `a=cryptex`)
2069    #[error("set_remote_description called without a=cryptex while header encryption is required")]
2070    ErrSessionDescriptionMissingCryptex,
2071
2072    /// ErrNoSRTPProtectionProfile indicates that the DTLS handshake completed and no SRTP Protection Profile was chosen
2073    #[error("DTLS Handshake completed and no SRTP Protection Profile was chosen")]
2074    ErrNoSRTPProtectionProfile,
2075
2076    /// ErrFailedToGenerateCertificateFingerprint indicates that we failed to generate the fingerprint used for comparing certificates
2077    #[error("failed to generate certificate fingerprint")]
2078    ErrFailedToGenerateCertificateFingerprint,
2079
2080    /// ErrNoCodecsAvailable indicates that operation isn't possible because the MediaEngine has no codecs available
2081    #[error("operation failed no codecs are available")]
2082    ErrNoCodecsAvailable,
2083
2084    /// ErrUnsupportedCodec indicates the remote peer doesn't support the requested codec
2085    #[error("unable to start track, codec is not supported by remote")]
2086    ErrUnsupportedCodec,
2087
2088    /// Invalid state error.
2089    #[error("Invalid state error")]
2090    InvalidStateError,
2091
2092    /// Invalid modification error.
2093    #[error("Invalid modification error")]
2094    InvalidModificationError,
2095
2096    /// Not found error: an argument names an object the callee does not have (W3C
2097    /// `NotFoundError`), such as a candidate pair that is not on the ICE agent's list.
2098    #[error("Not found error")]
2099    NotFoundError,
2100
2101    /// Invalid access error: an argument names something that is not the object's (W3C
2102    /// `InvalidAccessError`), such as a statistics selector that is not a sender or receiver
2103    /// of the peer connection.
2104    #[error("Invalid access error")]
2105    InvalidAccessError,
2106
2107    /// Range error.
2108    #[error("Range error {0}")]
2109    RangeError(String),
2110
2111    /// Type error: an argument is not a value the operation takes (W3C / WebIDL `TypeError`).
2112    #[error("Type error {0}")]
2113    TypeError(String),
2114
2115    /// Media Capture `OverconstrainedError`: constraints that cannot be satisfied, naming the
2116    /// constraint (W3C mediacapture-main 4.3.3 applyConstraints; webrtc-pc 9.3.1: always for
2117    /// the video properties of a remote track).
2118    #[error("Overconstrained: {0}")]
2119    OverconstrainedError(String),
2120
2121    /// draft-ietf-avtcore-rtp-sframe-03 section 6: the section's SFrame offer was answered
2122    /// without `a=sframe`; its media is not sent (no unencrypted fallback).
2123    #[error("SFrame was offered and the answer refused it: no media is sent")]
2124    ErrSFrameRefused,
2125
2126    /// A session description that does not parse (W3C webrtc-pc section 11.1, an `RTCError`
2127    /// with `errorDetail` `sdp-syntax-error`): what the SDP parser found, and on which line.
2128    #[error("SDP syntax error{}: {error}", .line_number.map(|n| format!(" on line {n}")).unwrap_or_default())]
2129    SdpSyntaxError {
2130        /// The line the error is about, from 1; `None` when it is about the whole description.
2131        line_number: Option<usize>,
2132        /// The parser's error.
2133        error: Box<Error>,
2134    },
2135
2136    /// ErrSenderWithNoCodecs indicates that a RTPSender was created without any codecs. To send media the MediaEngine needs at
2137    /// least one configured codec.
2138    #[error("unable to populate media section, RTPSender created with no codecs")]
2139    ErrSenderWithNoCodecs,
2140
2141    /// ErrSenderWithNoSSRCs indicates that a RTPSender was created without any SSRRs. To send media the Sender needs at
2142    /// least one configured ssrc.
2143    #[error("unable to populate media section, RTPSender created with no ssrcs")]
2144    ErrSenderWithNoSSRCs,
2145
2146    /// ErrRTPSenderNewTrackHasIncorrectKind indicates that the new track is of a different kind than the previous/original
2147    #[error("new track must be of the same kind as previous")]
2148    ErrRTPSenderNewTrackHasIncorrectKind,
2149
2150    /// New track has incorrect envelope.
2151    #[error("new track has incorrect envelope")]
2152    ErrRTPSenderNewTrackHasIncorrectEnvelope,
2153
2154    /// ErrRTPSenderDataSent indicates that the sequence number transformer tries to be enabled after the data sending began
2155    #[error("Sequence number transformer must be enabled before sending data")]
2156    ErrRTPSenderDataSent,
2157
2158    /// ErrRTPSenderSeqTransEnabled indicates that the sequence number transformer has been already enabled
2159    #[error("Sequence number transformer has been already enabled")]
2160    ErrRTPSenderSeqTransEnabled,
2161
2162    /// ErrUnbindFailed indicates that a TrackLocal was not able to be unbind
2163    #[error("failed to unbind TrackLocal from PeerConnection")]
2164    ErrUnbindFailed,
2165
2166    /// ErrNoPayloaderForCodec indicates that the requested codec does not have a payloader
2167    #[error("the requested codec does not have a payloader")]
2168    ErrNoPayloaderForCodec,
2169
2170    /// ErrRegisterHeaderExtensionInvalidDirection indicates that a extension was registered with different
2171    /// directions for two different calls.
2172    #[error("a header extension must be registered with the same direction each time")]
2173    ErrRegisterHeaderExtensionInvalidDirection,
2174
2175    /// Invalid direction.
2176    #[error("invalid direction")]
2177    ErrInvalidDirection,
2178
2179    /// ErrRegisterHeaderExtensionNoFreeID indicates that there was no extension ID available which
2180    /// in turn means that all 254 ids an RTP header can carry (1 to 14, and 16 to 255 in the
2181    /// two-byte form, RFC 8285) have been used.
2182    #[error(
2183        "no header extension ID was free to use (the maximum of 254 extensions have been registered)"
2184    )]
2185    ErrRegisterHeaderExtensionNoFreeID,
2186
2187    /// ErrSimulcastProbeOverflow indicates that too many Simulcast probe streams are in flight and the requested SSRC was ignored
2188    #[error("simulcast probe limit has been reached, new SSRC has been discarded")]
2189    ErrSimulcastProbeOverflow,
2190
2191    /// Enable detaching by calling webrtc.DetachDataChannels.
2192    #[error("enable detaching by calling webrtc.DetachDataChannels()")]
2193    ErrDetachNotEnabled,
2194    /// Datachannel not opened yet, try calling Detach from OnOpen.
2195    #[error("datachannel not opened yet, try calling Detach from OnOpen")]
2196    ErrDetachBeforeOpened,
2197    /// The DTLS transport has not started yet.
2198    #[error("the DTLS transport has not started yet")]
2199    ErrDtlsTransportNotStarted,
2200    /// Failed extracting keys from DTLS for SRTP.
2201    #[error("failed extracting keys from DTLS for SRTP")]
2202    ErrDtlsKeyExtractionFailed,
2203    /// Failed to start SRTP.
2204    #[error("failed to start SRTP")]
2205    ErrFailedToStartSRTP,
2206    /// Failed to start SRTCP.
2207    #[error("failed to start SRTCP")]
2208    ErrFailedToStartSRTCP,
2209    /// Attempted to start DTLSTransport that is not in new state.
2210    #[error("attempted to start DTLSTransport that is not in new state")]
2211    ErrInvalidDTLSStart,
2212    /// Peer didn't provide certificate via DTLS.
2213    #[error("peer didn't provide certificate via DTLS")]
2214    ErrNoRemoteCertificate,
2215    /// Identity provider is not implemented.
2216    #[error("identity provider is not implemented")]
2217    ErrIdentityProviderNotImplemented,
2218    /// Remote certificate does not match any fingerprint.
2219    #[error("remote certificate does not match any fingerprint")]
2220    ErrNoMatchingCertificateFingerprint,
2221    /// Unsupported fingerprint algorithm.
2222    #[error("unsupported fingerprint algorithm")]
2223    ErrUnsupportedFingerprintAlgorithm,
2224    /// ICE connection not started.
2225    #[error("ICE connection not started")]
2226    ErrICEConnectionNotStarted,
2227    /// Unknown candidate type.
2228    #[error("unknown candidate type")]
2229    ErrICECandidateTypeUnknown,
2230    /// Cannot convert ICE.CandidateType into webrtc.ICECandidateType, invalid type.
2231    #[error("cannot convert ice.CandidateType into webrtc.ICECandidateType, invalid type")]
2232    ErrICEInvalidConvertCandidateType,
2233    /// ICEAgent does not exist.
2234    #[error("ICEAgent does not exist")]
2235    ErrICEAgentNotExist,
2236    /// Unable to convert ICE candidates to ICECandidates.
2237    #[error("unable to convert ICE candidates to ICECandidates")]
2238    ErrICECandidatesConversionFailed,
2239    /// Unknown ICE Role.
2240    #[error("unknown ICE Role")]
2241    ErrICERoleUnknown,
2242    /// Unknown protocol.
2243    #[error("unknown protocol")]
2244    ErrICEProtocolUnknown,
2245    /// Gatherer not started.
2246    #[error("gatherer not started")]
2247    ErrICEGathererNotStarted,
2248    /// Unknown network type.
2249    #[error("unknown network type")]
2250    ErrNetworkTypeUnknown,
2251    /// New SDP does not match previous offer.
2252    #[error("new sdp does not match previous offer")]
2253    ErrSDPDoesNotMatchOffer,
2254    /// New SDP does not match previous answer.
2255    #[error("new sdp does not match previous answer")]
2256    ErrSDPDoesNotMatchAnswer,
2257    /// A remote answer does not answer the pending local offer (RFC 3264 section 6, RFC 9429
2258    /// section 5.8.3): the text names the media section and what differs.
2259    #[error("the answer does not match the offer: {0}")]
2260    ErrAnswerDoesNotMatchOffer(String),
2261    /// Provided value is not a valid enum value of type SDPType.
2262    #[error("provided value is not a valid enum value of type SDPType")]
2263    ErrPeerConnSDPTypeInvalidValue,
2264    /// Invalid state change op.
2265    #[error("invalid state change op")]
2266    ErrPeerConnStateChangeInvalid,
2267    /// Unhandled state change op.
2268    #[error("unhandled state change op")]
2269    ErrPeerConnStateChangeUnhandled,
2270    /// Invalid SDP type supplied to SetLocalDescription.
2271    #[error("invalid SDP type supplied to SetLocalDescription()")]
2272    ErrPeerConnSDPTypeInvalidValueSetLocalDescription,
2273    /// RemoteDescription contained media section without mid value.
2274    #[error("remoteDescription contained media section without mid value")]
2275    ErrPeerConnRemoteDescriptionWithoutMidValue,
2276    /// LocalDescription contained media section without mid value.
2277    #[error("localDescription contained media section without mid value")]
2278    ErrPeerConnLocalDescriptionWithoutMidValue,
2279    /// RemoteDescription has not been set yet.
2280    #[error("remoteDescription has not been set yet")]
2281    ErrPeerConnRemoteDescriptionNil,
2282    /// LocalDescription has not been set yet.
2283    #[error("localDescription has not been set yet")]
2284    ErrPeerConnLocalDescriptionNil,
2285    /// Single media section has an explicit SSRC.
2286    #[error("single media section has an explicit SSRC")]
2287    ErrPeerConnSingleMediaSectionHasExplicitSSRC,
2288    /// Could not add transceiver for remote SSRC.
2289    #[error("could not add transceiver for remote SSRC")]
2290    ErrPeerConnRemoteSSRCAddTransceiver,
2291    /// Mid RTP Extensions required for Simulcast.
2292    #[error("mid RTP Extensions required for Simulcast")]
2293    ErrPeerConnSimulcastMidRTPExtensionRequired,
2294    /// Stream id RTP Extensions required for Simulcast.
2295    #[error("stream id RTP Extensions required for Simulcast")]
2296    ErrPeerConnSimulcastStreamIDRTPExtensionRequired,
2297    /// Incoming SSRC failed Simulcast probing.
2298    #[error("incoming SSRC failed Simulcast probing")]
2299    ErrPeerConnSimulcastIncomingSSRCFailed,
2300    /// Failed collecting stats.
2301    #[error("failed collecting stats")]
2302    ErrPeerConnStatsCollectionFailed,
2303    /// Add_transceiver_from_kind only accepts one RTPTransceiverInit.
2304    #[error("add_transceiver_from_kind only accepts one RTPTransceiverInit")]
2305    ErrPeerConnAddTransceiverFromKindOnlyAcceptsOne,
2306    /// Add_transceiver_from_track only accepts one RTPTransceiverInit.
2307    #[error("add_transceiver_from_track only accepts one RTPTransceiverInit")]
2308    ErrPeerConnAddTransceiverFromTrackOnlyAcceptsOne,
2309    /// Add_transceiver_from_kind currently only supports recvonly.
2310    #[error("add_transceiver_from_kind currently only supports recvonly")]
2311    ErrPeerConnAddTransceiverFromKindSupport,
2312    /// Add_transceiver_from_track currently only supports sendonly and sendrecv.
2313    #[error("add_transceiver_from_track currently only supports sendonly and sendrecv")]
2314    ErrPeerConnAddTransceiverFromTrackSupport,
2315    /// TODO set_identity_provider.
2316    #[error("TODO set_identity_provider")]
2317    ErrPeerConnSetIdentityProviderNotImplemented,
2318    /// Write_RTCP failed to open write_stream.
2319    #[error("write_rtcp failed to open write_stream")]
2320    ErrPeerConnWriteRTCPOpenWriteStream,
2321    /// Cannot find transceiver with mid.
2322    #[error("cannot find transceiver with mid")]
2323    ErrPeerConnTransceiverMidNil,
2324    /// DTLSTransport must not be nil.
2325    #[error("DTLSTransport must not be nil")]
2326    ErrRTPReceiverDTLSTransportNil,
2327    /// Receive has already been called.
2328    #[error("Receive has already been called")]
2329    ErrRTPReceiverReceiveAlreadyCalled,
2330    /// Unable to find stream for Track with SSRC.
2331    #[error("unable to find stream for Track with SSRC")]
2332    ErrRTPReceiverWithSSRCTrackStreamNotFound,
2333    /// No trackStreams found for SSRC.
2334    #[error("no trackStreams found for SSRC")]
2335    ErrRTPReceiverForSSRCTrackStreamNotFound,
2336    /// No trackStreams found for RID.
2337    #[error("no trackStreams found for RID")]
2338    ErrRTPReceiverForRIDTrackStreamNotFound,
2339    /// Invalid RTP Receiver transition.
2340    #[error("invalid RTP Receiver transition")]
2341    ErrRTPReceiverStateChangeInvalid,
2342    /// Track must not be nil.
2343    #[error("Track must not be nil")]
2344    ErrRTPSenderTrackNil,
2345    /// RTPSender not existed.
2346    #[error("RTPSender not existed")]
2347    ErrRTPSenderNotExisted,
2348    /// Sender Track has been removed or replaced to nil.
2349    #[error("Sender Track has been removed or replaced to nil")]
2350    ErrRTPSenderTrackRemoved,
2351    /// Sender cannot add encoding as rid is empty.
2352    #[error("Sender cannot add encoding as rid is empty")]
2353    ErrRTPSenderRidNil,
2354    /// No `a=imageattr recv` line of the remote description can be satisfied for the
2355    /// resolution the encoder produces (RFC 9429 section 3.6.2): the encoding is not to be
2356    /// sent.
2357    #[error("no a=imageattr line of the remote description can be satisfied")]
2358    ErrImageAttrUnsatisfiable,
2359    /// Sender cannot add encoding as there is no base track.
2360    #[error("Sender cannot add encoding as there is no base track")]
2361    ErrRTPSenderNoBaseEncoding,
2362    /// Sender cannot add encoding as provided track does not match base track.
2363    #[error("Sender cannot add encoding as provided track does not match base track")]
2364    ErrRTPSenderBaseEncodingMismatch,
2365    /// Sender cannot encoding due to RID collision.
2366    #[error("Sender cannot encoding due to RID collision")]
2367    ErrRTPSenderRIDCollision,
2368    /// Two streams of a sender's encodings (a media, RTX or FEC SSRC) name the same SSRC: RFC
2369    /// 4588 section 4, "the original and retransmission streams ... MUST use two different
2370    /// SSRC values"; RFC 3550 section 8, one SSRC per source.
2371    #[error("sender encodings name SSRC {0} for more than one stream")]
2372    ErrRTPSenderSsrcCollision(u32),
2373    /// The application wrote RTCP feedback its section did not negotiate (RFC 4585 section
2374    /// 4.2, RFC 5104 section 7.2): the `a=rtcp-fb` type and parameter it needs.
2375    #[error("RTCP feedback `{0} {1}` was not negotiated for the stream")]
2376    ErrRTCPFeedbackNotNegotiated(String, String),
2377    /// An encoding's rid is not 1 to 255 alphanumeric characters (RFC 8852 section 3.1, the
2378    /// RtpStreamId the rid is sent as; RFC 8851 section 10).
2379    #[error("Sender cannot add encoding as its rid is not 1 to 255 alphanumeric characters")]
2380    ErrRTPSenderRidInvalid,
2381    /// An encoding names an SSRC another local stream of the connection has, or names one
2382    /// twice: every local stream is protected under the one SRTP master key, and two with the
2383    /// same SSRC would share a keystream (RFC 3711 sections 8 and 9.1, RFC 5764 section 3).
2384    #[error("Sender cannot use SSRC {0}: another local stream has it")]
2385    ErrRTPSenderSsrcTaken(u32),
2386    /// `RTCPeerConnection::set_peer_identity` without a remote description that carries an
2387    /// identity assertion (RFC 8827 section 5).
2388    #[error("the remote description carries no identity assertion")]
2389    ErrNoRemoteIdentityAssertion,
2390    /// The fingerprints an identity provider verified do not cover every fingerprint of the
2391    /// remote description (RFC 8827 section 7.4).
2392    #[error("the verified identity does not cover every fingerprint of the remote description")]
2393    ErrIdentityFingerprintsNotCovered,
2394    /// The certificate the DTLS association authenticated is not among the fingerprints an
2395    /// identity provider verified (RFC 8827 section 7.4).
2396    #[error("the certificate in use is not among the fingerprints of the verified identity")]
2397    ErrIdentityCertificateNotCovered,
2398    /// Sender does not have track for RID.
2399    #[error("Sender does not have track for RID")]
2400    ErrRTPSenderNoTrackForRID,
2401    /// RTPReceiver not existed.
2402    #[error("RTPReceiver not existed")]
2403    ErrRTPReceiverNotExisted,
2404    /// DTLSTransport must not be nil.
2405    #[error("DTLSTransport must not be nil")]
2406    ErrRTPSenderDTLSTransportNil,
2407    /// Send has already been called.
2408    #[error("Send has already been called")]
2409    ErrRTPSenderSendAlreadyCalled,
2410    /// RTPTransceiver not existed.
2411    #[error("RTPTransceiver not existed")]
2412    ErrRTPTransceiverNotExisted,
2413    /// SCTPTransport not existed.
2414    #[error("SCTPTransport not existed")]
2415    ErrSCTPTransportNotExisted,
2416    /// DTLSTransport not existed.
2417    #[error("DTLSTransport not existed")]
2418    ErrDTLSTransportNotExisted,
2419    /// ErrRTPSenderTrackNil.
2420    #[error("errRTPSenderTrackNil")]
2421    ErrRTPTransceiverCannotChangeMid,
2422    /// Invalid state change in RTPTransceiver.setSending.
2423    #[error("invalid state change in RTPTransceiver.setSending")]
2424    ErrRTPTransceiverSetSendingInvalidState,
2425    /// Unsupported codec type by this transceiver.
2426    #[error("unsupported codec type by this transceiver")]
2427    ErrRTPTransceiverCodecUnsupported,
2428    /// DTLS not established.
2429    #[error("DTLS not established")]
2430    ErrSCTPTransportDTLS,
2431    /// Add_transceiver_SDP called with 0 transceivers.
2432    #[error("add_transceiver_sdp() called with 0 transceivers")]
2433    ErrSDPZeroTransceivers,
2434    /// A data channel m= section without a valid `a=sctp-port` (RFC 8841 section 5).
2435    #[error("invalid Media Section. Data channel section without a valid a=sctp-port")]
2436    ErrSDPSctpPortInvalid,
2437    /// Invalid Media Section. Media + DataChannel both enabled.
2438    #[error("invalid Media Section. Media + DataChannel both enabled")]
2439    ErrSDPMediaSectionMediaDataChanInvalid,
2440    /// Invalid Media Section Track Index.
2441    #[error("invalid Media Section Track Index")]
2442    ErrSDPMediaSectionTrackInvalid,
2443    /// Can't rollback from stable state.
2444    #[error("can't rollback from stable state")]
2445    ErrSignalingStateCannotRollback,
2446    /// Invalid proposed signaling state transition.
2447    #[error("invalid proposed signaling state transition: {0}")]
2448    ErrSignalingStateProposedTransitionInvalid(String),
2449    /// Cannot convert to StatsICECandidatePairStateSucceeded invalid ICE candidate state.
2450    #[error("cannot convert to StatsICECandidatePairStateSucceeded invalid ice candidate state")]
2451    ErrStatsICECandidateStateInvalid,
2452    /// ICETransport can only be called in ICETransportStateNew.
2453    #[error("ICETransport can only be called in ICETransportStateNew")]
2454    ErrICETransportNotInNew,
2455    /// A local UDP candidate on a transport address the previous DTLS association used, given
2456    /// for the new association that replaces it (RFC 8842 sections 5.1 and 6: a new 3-tuple).
2457    #[error(
2458        "local candidate on {0}, a transport address of the previous DTLS association: a new DTLS association needs a new local address or port (RFC 8842 section 5.1)"
2459    )]
2460    ErrICECandidateAddressOfPreviousDtlsAssociation(std::net::SocketAddr),
2461    /// Bad Certificate PEM format.
2462    #[error("bad Certificate PEM format")]
2463    ErrCertificatePEMFormatError,
2464    /// SCTP is not established.
2465    #[error("SCTP is not established")]
2466    ErrSCTPNotEstablished,
2467
2468    /// DataChannel is not opened.
2469    #[error("DataChannel is not opened")]
2470    ErrClosedPipe,
2471    /// Interceptor is not bind.
2472    #[error("Interceptor is not bind")]
2473    ErrInterceptorNotBind,
2474    /// Excessive retries in CreateOffer.
2475    #[error("excessive retries in CreateOffer")]
2476    ErrExcessiveRetries,
2477
2478    /// Not long enough to be a RTP Packet.
2479    #[error("not long enough to be a RTP Packet")]
2480    ErrRTPTooShort,
2481
2482    /// SyntaxIdDirSplit indicates rid-syntax could not be parsed.
2483    #[error("RFC8851 mandates rid-syntax        = %s\"a=rid:\" rid-id SP rid-dir")]
2484    SimulcastRidParseErrorSyntaxIdDirSplit,
2485    /// UnknownDirection indicates rid-dir was not parsed. Should be "send" or "recv".
2486    #[error("RFC8851 mandates rid-dir           = %s\"send\" / %s\"recv\"")]
2487    SimulcastRidParseErrorUnknownDirection,
2488
2489    //SDP
2490    /// Codec not found.
2491    #[error("codec not found")]
2492    CodecNotFound,
2493    /// Missing whitespace.
2494    #[error("missing whitespace")]
2495    MissingWhitespace,
2496    /// Missing colon.
2497    #[error("missing colon")]
2498    MissingColon,
2499    /// Payload type not found.
2500    #[error("payload type not found")]
2501    PayloadTypeNotFound,
2502    /// SdpInvalidSyntax.
2503    #[error("SdpInvalidSyntax: {0}")]
2504    SdpInvalidSyntax(String),
2505    /// SdpInvalidValue.
2506    #[error("SdpInvalidValue: {0}")]
2507    SdpInvalidValue(String),
2508    /// SDP: empty time_descriptions.
2509    #[error("sdp: empty time_descriptions")]
2510    SdpEmptyTimeDescription,
2511    /// Parse extmap.
2512    #[error("parse extmap: {0}")]
2513    ParseExtMap(String),
2514    /// A syntax error at a known offset in the input, rendered with the offending character marked.
2515    #[error("{} --> {} <-- {}", .s.substring(0,*.p), .s.substring(*.p, *.p+1), .s.substring(*.p+1, .s.len())
2516    )]
2517    SyntaxError {
2518        /// The input being parsed.
2519        s: String,
2520        /// The byte offset of the offending character in `s`.
2521        p: usize,
2522    },
2523
2524    //Third Party Error
2525    /// Invalid PEM.
2526    #[error("invalid PEM: {0}")]
2527    InvalidPEM(String),
2528    /// Parse ip.
2529    #[error("parse ip: {0}")]
2530    ParseIp(#[from] net::AddrParseError),
2531    /// Parse int.
2532    #[error("parse int: {0}")]
2533    ParseInt(#[from] ParseIntError),
2534    /// An underlying I/O error.
2535    #[error("{0}")]
2536    Io(#[source] IoError),
2537    /// URL parse.
2538    #[error("url parse: {0}")]
2539    Url(#[from] url::ParseError),
2540    /// UTF-8.
2541    #[error("utf8: {0}")]
2542    Utf8(#[from] FromUtf8Error),
2543    /// An error from the standard library or another boxed source.
2544    #[error("{0}")]
2545    Std(#[source] StdError),
2546    //Other Errors
2547    /// Other RTCP Err.
2548    #[error("Other RTCP Err: {0}")]
2549    OtherRtcpErr(String),
2550    /// Other RTP Err.
2551    #[error("Other RTP Err: {0}")]
2552    OtherRtpErr(String),
2553    /// Other SRTP Err.
2554    #[error("Other SRTP Err: {0}")]
2555    OtherSrtpErr(String),
2556    /// Other STUN Err.
2557    #[error("Other STUN Err: {0}")]
2558    OtherStunErr(String),
2559    /// Other TURN Err.
2560    #[error("Other TURN Err: {0}")]
2561    OtherTurnErr(String),
2562    /// Other ICE Err.
2563    #[error("Other ICE Err: {0}")]
2564    OtherIceErr(String),
2565    /// Other DTLS Err.
2566    #[error("Other DTLS Err: {0}")]
2567    OtherDtlsErr(String),
2568    /// Other SCTP Err.
2569    #[error("Other SCTP Err: {0}")]
2570    OtherSctpErr(String),
2571    /// Other DataChannel Err.
2572    #[error("Other DataChannel Err: {0}")]
2573    OtherDataChannelErr(String),
2574    /// Other Interceptor Err.
2575    #[error("Other Interceptor Err: {0}")]
2576    OtherInterceptorErr(String),
2577    /// Other Media Err.
2578    #[error("Other Media Err: {0}")]
2579    OtherMediaErr(String),
2580    /// Other mDNS Err.
2581    #[error("Other mDNS Err: {0}")]
2582    OtherMdnsErr(String),
2583    /// Other SDP Err.
2584    #[error("Other SDP Err: {0}")]
2585    OtherSdpErr(String),
2586    /// Other PeerConnection Err.
2587    #[error("Other PeerConnection Err: {0}")]
2588    OtherPeerConnectionErr(String),
2589    /// A provider-neutral cryptographic operation failed.
2590    #[error("crypto: {0}")]
2591    Crypto(String),
2592    /// Stream transport: no connection or listener has this id (it was never opened, or it
2593    /// is closed).
2594    #[error("stream: unknown connection or listener")]
2595    ErrUnknownStream,
2596    /// Stream transport: the connection is closing or closed and takes no more data.
2597    #[error("stream: connection closed")]
2598    ErrStreamConnectionClosed,
2599    /// Stream transport: a message too long for the connection's framing (RFC 4571: 65535
2600    /// bytes).
2601    #[error("stream: message too long for its framing")]
2602    ErrStreamMessageTooLong,
2603    #[error("{0}")]
2604    /// An error that does not fit any other variant, carrying a description.
2605    Other(String),
2606}
2607
2608impl Error {
2609    /// Wraps any `std::error::Error` implementation as [`Error::Std`],
2610    /// preserving the original error and its stack trace.
2611    pub fn from_std<T>(error: T) -> Self
2612    where
2613        T: std::error::Error + Send + Sync + 'static,
2614    {
2615        Error::Std(StdError(Box::new(error)))
2616    }
2617
2618    /// The name of the W3C error a JavaScript API over this engine raises for this error, as
2619    /// webrtc-pc names them, where the engine knows it: `"InvalidAccessError"`,
2620    /// `"InvalidStateError"`, `"InvalidModificationError"`, `"NotFoundError"`,
2621    /// `"OperationError"` (for a description that does not parse an `RTCError`, see
2622    /// [`rtc_error_detail`](Self::rtc_error_detail)), `"SyntaxError"`, `"RangeError"`,
2623    /// `"TypeError"`, `"OverconstrainedError"`. `None` for the others.
2624    ///
2625    /// W3C webrtc-pc section 4.4.1.5 ("set the session description"): a description that does
2626    /// not parse (RFC 9429 sections 5.8.1 and 5.8.2) rejects with an `RTCError` whose
2627    /// `errorDetail` is `"sdp-syntax-error"` ([`Error::SdpSyntaxError`], with its line, and the
2628    /// attribute grammar errors); one that fails the semantic checks of RFC 9429 section 5.8.3
2629    /// (credentials, fingerprints, mids, rtcp-mux, the answer against its offer, ...) rejects
2630    /// with an `InvalidAccessError`; one invalid for the signaling state with an
2631    /// `InvalidStateError`.
2632    ///
2633    /// The other operations, as webrtc-pc names their failures: the constructor's expired
2634    /// certificate (4.4.1.1, [`Error::ErrCertificateExpired`]) and a TURN url without a
2635    /// username or credential ("validate an ICE server URL", [`Error::ErrNoTurnCredentials`])
2636    /// are `InvalidAccessError`s; the members "set the configuration" (4.4.1.5) does not let
2637    /// change (`ErrModifyingCertificates`, `ErrModifyingBundlePolicy`,
2638    /// `ErrModifyingRTCPMuxPolicy`, `ErrModifyingICECandidatePoolSize`), like a local offer
2639    /// or answer that is not the last one created (`ErrSDPDoesNotMatchOffer`,
2640    /// `ErrSDPDoesNotMatchAnswer`, 4.4.2 `setLocalDescription`), an
2641    /// `InvalidModificationError`; an ICE server without a url and a url that "validate an ICE
2642    /// server URL" refuses (`ErrNoIceServerUrls`, `ErrSchemeType`, `ErrInvalidUrl`,
2643    /// `ErrStunQuery`, `ErrInvalidQuery`, `ErrProtoType`) a `SyntaxError`; `addIceCandidate`
2644    /// (4.4.2) without a remote description, like `createAnswer` without one, an
2645    /// `InvalidStateError` ([`Error::ErrNoRemoteDescription`]), and a candidate whose `sdpMid`
2646    /// or `sdpMLineIndex` names no media description or whose `usernameFragment` is not its
2647    /// section's an `OperationError` (`ErrIceCandidateMediaSectionNotFound`,
2648    /// `ErrIceCandidateUsernameFragmentMismatch`; a `DOMException`, not an `RTCError`).
2649    pub fn dom_exception_name(&self) -> Option<&'static str> {
2650        match self {
2651            Error::SdpSyntaxError { .. } | Error::SdpInvalidSyntax(_) => Some("OperationError"),
2652            Error::ErrIceCandidateMediaSectionNotFound
2653            | Error::ErrIceCandidateUsernameFragmentMismatch => Some("OperationError"),
2654            Error::ErrNoIceServerUrls
2655            | Error::ErrSchemeType
2656            | Error::ErrInvalidUrl
2657            | Error::ErrStunQuery
2658            | Error::ErrInvalidQuery
2659            | Error::ErrProtoType => Some("SyntaxError"),
2660            Error::ErrSDPDoesNotMatchOffer
2661            | Error::ErrSDPDoesNotMatchAnswer
2662            | Error::ErrModifyingCertificates
2663            | Error::ErrModifyingBundlePolicy
2664            | Error::ErrModifyingRTCPMuxPolicy
2665            | Error::ErrModifyingICECandidatePoolSize => Some("InvalidModificationError"),
2666            Error::ErrCertificateExpired | Error::ErrNoTurnCredentials => {
2667                Some("InvalidAccessError")
2668            }
2669            Error::ErrNoRemoteDescription => Some("InvalidStateError"),
2670            Error::InvalidAccessError
2671            | Error::SdpInvalidValue(_)
2672            | Error::ErrPeerConnRemoteDescriptionWithoutMidValue
2673            | Error::ErrSessionDescriptionInvalidIceCredentials
2674            | Error::ErrSessionDescriptionNoFingerprint
2675            | Error::ErrSessionDescriptionInvalidFingerprint
2676            | Error::ErrSessionDescriptionConflictingFingerprints
2677            | Error::ErrSessionDescriptionInvalidSetup
2678            | Error::ErrSessionDescriptionInvalidTlsId
2679            | Error::ErrSessionDescriptionMissingIceUfrag
2680            | Error::ErrSessionDescriptionMissingIcePwd
2681            | Error::ErrSessionDescriptionConflictingIceUfrag
2682            | Error::ErrSessionDescriptionConflictingIcePwd
2683            | Error::ErrSessionDescriptionMissingCryptex => Some("InvalidAccessError"),
2684            Error::InvalidStateError
2685            | Error::ErrConnectionClosed
2686            | Error::ErrIncorrectSignalingState
2687            | Error::ErrSignalingStateCannotRollback
2688            | Error::ErrSignalingStateProposedTransitionInvalid(_) => Some("InvalidStateError"),
2689            Error::InvalidModificationError => Some("InvalidModificationError"),
2690            Error::NotFoundError => Some("NotFoundError"),
2691            Error::RangeError(_) => Some("RangeError"),
2692            Error::TypeError(_) => Some("TypeError"),
2693            Error::OverconstrainedError(_) => Some("OverconstrainedError"),
2694            _ => None,
2695        }
2696    }
2697
2698    /// The `errorDetail` of the W3C `RTCError` (webrtc-pc section 11.1) this error is, when it
2699    /// is one: `"sdp-syntax-error"` for a description that does not parse.
2700    pub fn rtc_error_detail(&self) -> Option<&'static str> {
2701        match self {
2702            Error::SdpSyntaxError { .. } | Error::SdpInvalidSyntax(_) => Some("sdp-syntax-error"),
2703            _ => None,
2704        }
2705    }
2706
2707    /// Attempts to downcast an [`Error::Std`] variant to a concrete error type.
2708    ///
2709    /// Returns `None` if this error is not `Error::Std` or if the inner error
2710    /// is not of type `T`.
2711    pub fn downcast_ref<T: std::error::Error + 'static>(&self) -> Option<&T> {
2712        if let Error::Std(s) = self {
2713            return s.0.downcast_ref();
2714        }
2715
2716        None
2717    }
2718}
2719
2720/// Wrapper around [`std::io::Error`] that implements [`PartialEq`].
2721///
2722/// `io::Error` does not implement `PartialEq`, which is required by the
2723/// top-level [`enum@Error`] enum. This newtype delegates equality to
2724/// [`io::ErrorKind`], so two `IoError` values are equal when their kinds match.
2725#[derive(Debug, Error)]
2726#[error("io error: {0}")]
2727pub struct IoError(#[from] pub io::Error);
2728
2729// Workaround for wanting PartialEq for io::Error.
2730impl PartialEq for IoError {
2731    fn eq(&self, other: &Self) -> bool {
2732        self.0.kind() == other.0.kind()
2733    }
2734}
2735
2736impl From<io::Error> for Error {
2737    fn from(e: io::Error) -> Self {
2738        Error::Io(IoError(e))
2739    }
2740}
2741
2742/// An escape hatch to preserve stack traces for errors whose concrete type is unknown.
2743///
2744/// Some traits exported by this crate (e.g. `Conn`, `Listener`) return `Error`.
2745/// When those traits are used in higher-level crates that have their own error
2746/// types, callers are forced to handle foreign errors. `StdError` boxes any
2747/// `std::error::Error` implementation and wraps it in `Error::Std`, preserving
2748/// the original error's message and — where supported — its stack trace.
2749///
2750/// Use [`Error::from_std`] to construct this variant.
2751#[derive(Debug, Error)]
2752#[error("{0}")]
2753pub struct StdError(pub Box<dyn std::error::Error + Send + Sync>);
2754
2755impl PartialEq for StdError {
2756    fn eq(&self, _: &Self) -> bool {
2757        false
2758    }
2759}
2760
2761impl<T> From<std::sync::PoisonError<T>> for Error {
2762    fn from(e: std::sync::PoisonError<T>) -> Self {
2763        Error::PoisonError(e.to_string())
2764    }
2765}
2766
2767impl From<SystemTimeError> for Error {
2768    fn from(e: SystemTimeError) -> Self {
2769        Error::Other(e.to_string())
2770    }
2771}
2772
2773/// Flattens a list of errors into a single [`enum@Error`], joining their messages with newlines.
2774///
2775/// Returns `Ok(())` if `errs` is empty.
2776pub fn flatten_errs(errs: Vec<impl Into<Error>>) -> Result<()> {
2777    if errs.is_empty() {
2778        Ok(())
2779    } else {
2780        let errs_strs: Vec<String> = errs.into_iter().map(|e| e.into().to_string()).collect();
2781        Err(Error::Other(errs_strs.join("\n")))
2782    }
2783}