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