Skip to main content

rtc_shared/
error.rs

1#![allow(dead_code)]
2
3use std::io;
4use std::net;
5use std::net::SocketAddr;
6use std::num::ParseIntError;
7use std::string::FromUtf8Error;
8use std::time::SystemTimeError;
9use substring::Substring;
10use thiserror::Error;
11
12/// A type alias for `std::result::Result` with this crate's [`enum@Error`] type.
13pub type Result<T> = std::result::Result<T, Error>;
14
15/// Unified error type for all WebRTC sub-protocols.
16///
17/// Aggregates errors from every layer of the WebRTC stack — buffers, RTP/RTCP,
18/// SRTP, STUN, TURN, ICE, DTLS, SCTP, data channels, SDP, mDNS, and the
19/// top-level peer connection — into a single enum so callers only need to
20/// handle one error type.
21///
22/// The enum is `#[non_exhaustive]`: new variants may be added in future
23/// releases without a semver-breaking change.
24#[derive(Error, Debug, PartialEq)]
25#[non_exhaustive]
26pub enum Error {
27    #[error("buffer: full")]
28    ErrBufferFull,
29    #[error("buffer: closed")]
30    ErrBufferClosed,
31    #[error("buffer: short")]
32    ErrBufferShort,
33    #[error("packet too big")]
34    ErrPacketTooBig,
35    #[error("i/o timeout")]
36    ErrTimeout,
37    #[error("udp: listener closed")]
38    ErrClosedListener,
39    #[error("udp: listen queue exceeded")]
40    ErrListenQueueExceeded,
41    #[error("udp: listener accept ch closed")]
42    ErrClosedListenerAcceptCh,
43    #[error("obs cannot be nil")]
44    ErrObsCannotBeNil,
45    #[error("se of closed network connection")]
46    ErrUseClosedNetworkConn,
47    #[error("addr is not a net.UDPAddr")]
48    ErrAddrNotUdpAddr,
49    #[error("something went wrong with locAddr")]
50    ErrLocAddr,
51    #[error("already closed")]
52    ErrAlreadyClosed,
53    #[error("no remAddr defined")]
54    ErrNoRemAddr,
55    #[error("address already in use")]
56    ErrAddressAlreadyInUse,
57    #[error("no such UDPConn")]
58    ErrNoSuchUdpConn,
59    #[error("cannot remove unspecified IP by the specified IP")]
60    ErrCannotRemoveUnspecifiedIp,
61    #[error("no address assigned")]
62    ErrNoAddressAssigned,
63    #[error("1:1 NAT requires more than one mapping")]
64    ErrNatRequriesMapping,
65    #[error("length mismtach between mappedIPs and localIPs")]
66    ErrMismatchLengthIp,
67    #[error("non-udp translation is not supported yet")]
68    ErrNonUdpTranslationNotSupported,
69    #[error("no associated local address")]
70    ErrNoAssociatedLocalAddress,
71    #[error("no NAT binding found")]
72    ErrNoNatBindingFound,
73    #[error("has no permission")]
74    ErrHasNoPermission,
75    #[error("host name must not be empty")]
76    ErrHostnameEmpty,
77    #[error("failed to parse IP address")]
78    ErrFailedToParseIpaddr,
79    #[error("no interface is available")]
80    ErrNoInterface,
81    #[error("not found")]
82    ErrNotFound,
83    #[error("unexpected network")]
84    ErrUnexpectedNetwork,
85    #[error("can't assign requested address")]
86    ErrCantAssignRequestedAddr,
87    #[error("unknown network")]
88    ErrUnknownNetwork,
89    #[error("no router linked")]
90    ErrNoRouterLinked,
91    #[error("invalid port number")]
92    ErrInvalidPortNumber,
93    #[error("unexpected type-switch failure")]
94    ErrUnexpectedTypeSwitchFailure,
95    #[error("bind failed")]
96    ErrBindFailed,
97    #[error("end port is less than the start")]
98    ErrEndPortLessThanStart,
99    #[error("port space exhausted")]
100    ErrPortSpaceExhausted,
101    #[error("vnet is not enabled")]
102    ErrVnetDisabled,
103    #[error("invalid local IP in static_ips")]
104    ErrInvalidLocalIpInStaticIps,
105    #[error("mapped in static_ips is beyond subnet")]
106    ErrLocalIpBeyondStaticIpsSubset,
107    #[error("all static_ips must have associated local IPs")]
108    ErrLocalIpNoStaticsIpsAssociated,
109    #[error("router already started")]
110    ErrRouterAlreadyStarted,
111    #[error("router already stopped")]
112    ErrRouterAlreadyStopped,
113    #[error("static IP is beyond subnet")]
114    ErrStaticIpIsBeyondSubnet,
115    #[error("address space exhausted")]
116    ErrAddressSpaceExhausted,
117    #[error("no IP address is assigned for eth0")]
118    ErrNoIpaddrEth0,
119    #[error("Invalid mask")]
120    ErrInvalidMask,
121
122    //ExportKeyingMaterial errors
123    #[error("tls handshake is in progress")]
124    HandshakeInProgress,
125    #[error("context is not supported for export_keying_material")]
126    ContextUnsupported,
127    #[error("export_keying_material can not be used with a reserved label")]
128    ReservedExportKeyingMaterial,
129    #[error("no cipher suite for export_keying_material")]
130    CipherSuiteUnset,
131    #[error("export_keying_material hash: {0}")]
132    Hash(String),
133    #[error("mutex poison: {0}")]
134    PoisonError(String),
135
136    //RTCP errors
137    /// Wrong marshal size.
138    #[error("Wrong marshal size")]
139    WrongMarshalSize,
140    /// Packet lost exceeds maximum amount of packets
141    /// that can possibly be lost.
142    #[error("Invalid total lost count")]
143    InvalidTotalLost,
144    /// Packet contains an invalid header.
145    #[error("Invalid header")]
146    InvalidHeader,
147    /// Packet contains empty compound.
148    #[error("Empty compound packet")]
149    EmptyCompound,
150    /// Invalid first packet in compound packets. First packet
151    /// should either be a SenderReport packet or ReceiverReport
152    #[error("First packet in compound must be SR or RR")]
153    BadFirstPacket,
154    /// CNAME was not defined.
155    #[error("Compound missing SourceDescription with CNAME")]
156    MissingCname,
157    /// Packet was defined before CNAME.
158    #[error("Feedback packet seen before CNAME")]
159    PacketBeforeCname,
160    /// Too many reports.
161    #[error("Too many reports")]
162    TooManyReports,
163    /// Too many chunks.
164    #[error("Too many chunks")]
165    TooManyChunks,
166    /// Too many sources.
167    #[error("too many sources")]
168    TooManySources,
169    /// Packet received is too short.
170    #[error("Packet too short to be read")]
171    PacketTooShort,
172    /// Buffer is too short.
173    #[error("Buffer too short to be written")]
174    BufferTooShort,
175    /// Wrong packet type.
176    #[error("Wrong packet type")]
177    WrongType,
178    /// SDES received is too long.
179    #[error("SDES must be < 255 octets long")]
180    SdesTextTooLong,
181    /// SDES type is missing.
182    #[error("SDES item missing type")]
183    SdesMissingType,
184    /// Reason is too long.
185    #[error("Reason must be < 255 octets long")]
186    ReasonTooLong,
187    /// Invalid packet version.
188    #[error("Invalid packet version")]
189    BadVersion,
190    /// Invalid padding value.
191    #[error("Invalid padding value")]
192    WrongPadding,
193    /// Wrong feedback message type.
194    #[error("Wrong feedback message type")]
195    WrongFeedbackType,
196    /// Wrong payload type.
197    #[error("Wrong payload type")]
198    WrongPayloadType,
199    /// Header length is too small.
200    #[error("Header length is too small")]
201    HeaderTooSmall,
202    /// Media ssrc was defined as zero.
203    #[error("Media SSRC must be 0")]
204    SsrcMustBeZero,
205    /// Missing REMB identifier.
206    #[error("Missing REMB identifier")]
207    MissingRembIdentifier,
208    /// SSRC number and length mismatches.
209    #[error("SSRC num and length do not match")]
210    SsrcNumAndLengthMismatch,
211    /// Invalid size or start index.
212    #[error("Invalid size or startIndex")]
213    InvalidSizeOrStartIndex,
214    /// Delta exceeds limit.
215    #[error("Delta exceed limit")]
216    DeltaExceedLimit,
217    /// Packet status chunk is not 2 bytes.
218    #[error("Packet status chunk must be 2 bytes")]
219    PacketStatusChunkLength,
220    #[error("Invalid bitrate")]
221    InvalidBitrate,
222    #[error("Wrong chunk type")]
223    WrongChunkType,
224    #[error("Struct contains unexpected member type")]
225    BadStructMemberType,
226    #[error("Cannot read into non-pointer")]
227    BadReadParameter,
228    #[error("Invalid block size")]
229    InvalidBlockSize,
230
231    //RTP errors
232    #[error("RTP header size insufficient")]
233    ErrHeaderSizeInsufficient,
234    #[error("RTP header size insufficient for extension")]
235    ErrHeaderSizeInsufficientForExtension,
236    #[error("buffer too small")]
237    ErrBufferTooSmall,
238    #[error("extension not enabled")]
239    ErrHeaderExtensionsNotEnabled,
240    #[error("extension not found")]
241    ErrHeaderExtensionNotFound,
242
243    #[error("header extension id must be between 1 and 14 for RFC 5285 extensions")]
244    ErrRfc8285oneByteHeaderIdrange,
245    #[error("header extension payload must be 16bytes or less for RFC 5285 one byte extensions")]
246    ErrRfc8285oneByteHeaderSize,
247
248    #[error("header extension id must be between 1 and 255 for RFC 5285 extensions")]
249    ErrRfc8285twoByteHeaderIdrange,
250    #[error("header extension payload must be 255bytes or less for RFC 5285 two byte extensions")]
251    ErrRfc8285twoByteHeaderSize,
252
253    #[error("header extension id must be 0 for none RFC 5285 extensions")]
254    ErrRfc3550headerIdrange,
255
256    #[error("packet is not large enough")]
257    ErrShortPacket,
258    #[error("invalid nil packet")]
259    ErrNilPacket,
260    #[error("too many PDiff")]
261    ErrTooManyPDiff,
262    #[error("too many spatial layers")]
263    ErrTooManySpatialLayers,
264    #[error("NALU Type is unhandled")]
265    ErrUnhandledNaluType,
266
267    #[error("corrupted h265 packet")]
268    ErrH265CorruptedPacket,
269    #[error("invalid h265 packet type")]
270    ErrInvalidH265PacketType,
271
272    #[error("payload is too small for OBU extension header")]
273    ErrPayloadTooSmallForObuExtensionHeader,
274    #[error("payload is too small for OBU payload size")]
275    ErrPayloadTooSmallForObuPayloadSize,
276
277    #[error("extension_payload must be in 32-bit words")]
278    HeaderExtensionPayloadNot32BitWords,
279    #[error("audio level overflow")]
280    AudioLevelOverflow,
281    #[error("playout delay overflow")]
282    PlayoutDelayOverflow,
283    #[error("payload is not large enough")]
284    PayloadIsNotLargeEnough,
285    #[error("STAP-A declared size({0}) is larger than buffer({1})")]
286    StapASizeLargerThanBuffer(usize, usize),
287    #[error("nalu type {0} is currently not handled")]
288    NaluTypeIsNotHandled(u8),
289
290    //SRTP
291    #[error("duplicated packet")]
292    ErrDuplicated,
293    #[error("SRTP master key is not long enough")]
294    ErrShortSrtpMasterKey,
295    #[error("SRTP master salt is not long enough")]
296    ErrShortSrtpMasterSalt,
297    #[error("no such SRTP Profile")]
298    ErrNoSuchSrtpProfile,
299    #[error("indexOverKdr > 0 is not supported yet")]
300    ErrNonZeroKdrNotSupported,
301    #[error("exporter called with wrong label")]
302    ErrExporterWrongLabel,
303    #[error("no config provided")]
304    ErrNoConfig,
305    #[error("no conn provided")]
306    ErrNoConn,
307    #[error("failed to verify auth tag")]
308    ErrFailedToVerifyAuthTag,
309    #[error("packet is too short to be RTP packet")]
310    ErrTooShortRtp,
311    #[error("packet is too short to be RTCP packet")]
312    ErrTooShortRtcp,
313    #[error("payload differs")]
314    ErrPayloadDiffers,
315    #[error("started channel used incorrectly, should only be closed")]
316    ErrStartedChannelUsedIncorrectly,
317    #[error("stream has not been inited, unable to close")]
318    ErrStreamNotInited,
319    #[error("stream is already closed")]
320    ErrStreamAlreadyClosed,
321    #[error("stream is already inited")]
322    ErrStreamAlreadyInited,
323    #[error("failed to cast child")]
324    ErrFailedTypeAssertion,
325    #[error("exceeded the maximum number of packets")]
326    ErrExceededMaxPackets,
327
328    #[error("index_over_kdr > 0 is not supported yet")]
329    UnsupportedIndexOverKdr,
330    #[error("invalid master key length for aes_256_cm")]
331    InvalidMasterKeyLength,
332    #[error("invalid master salt length for aes_256_cm")]
333    InvalidMasterSaltLength,
334    #[error("out_len > 32 is not supported for aes_256_cm")]
335    UnsupportedOutLength,
336    #[error("SRTP Master Key must be len {0}, got {1}")]
337    SrtpMasterKeyLength(usize, usize),
338    #[error("SRTP Salt must be len {0}, got {1}")]
339    SrtpSaltLength(usize, usize),
340    #[error("SyntaxError: {0}")]
341    ExtMapParse(String),
342    #[error("ssrc {0} not exist in srtp_ssrc_state")]
343    SsrcMissingFromSrtp(u32),
344    #[error("srtp ssrc={0} index={1}: duplicated")]
345    SrtpSsrcDuplicated(u32, u16),
346    #[error("srtcp ssrc={0} index={1}: duplicated")]
347    SrtcpSsrcDuplicated(u32, usize),
348    #[error("ssrc {0} not exist in srtcp_ssrc_state")]
349    SsrcMissingFromSrtcp(u32),
350    #[error("Stream with ssrc {0} exists")]
351    StreamWithSsrcExists(u32),
352    #[error("Session RTP/RTCP type must be same as input buffer")]
353    SessionRtpRtcpTypeMismatch,
354    #[error("Session EOF")]
355    SessionEof,
356    #[error("too short SRTP packet: only {0} bytes, expected > {1} bytes")]
357    SrtpTooSmall(usize, usize),
358    #[error("too short SRTCP packet: only {0} bytes, expected > {1} bytes")]
359    SrtcpTooSmall(usize, usize),
360    #[error("failed to verify rtp auth tag")]
361    RtpFailedToVerifyAuthTag,
362    #[error("too short auth tag: only {0} bytes, expected > {1} bytes")]
363    RtcpInvalidLengthAuthTag(usize, usize),
364    #[error("failed to verify rtcp auth tag")]
365    RtcpFailedToVerifyAuthTag,
366    #[error("SessionSRTP has been closed")]
367    SessionSrtpAlreadyClosed,
368    #[error("this stream is not a RTPStream")]
369    InvalidRtpStream,
370    #[error("this stream is not a RTCPStream")]
371    InvalidRtcpStream,
372
373    //STUN errors
374    #[error("attribute not found")]
375    ErrAttributeNotFound,
376    #[error("transaction is stopped")]
377    ErrTransactionStopped,
378    #[error("transaction not exists")]
379    ErrTransactionNotExists,
380    #[error("transaction exists with same id")]
381    ErrTransactionExists,
382    #[error("agent is closed")]
383    ErrAgentClosed,
384    #[error("transaction is timed out")]
385    ErrTransactionTimeOut,
386    #[error("no default reason for ErrorCode")]
387    ErrNoDefaultReason,
388    #[error("unexpected EOF")]
389    ErrUnexpectedEof,
390    #[error("attribute size is invalid")]
391    ErrAttributeSizeInvalid,
392    #[error("attribute size overflow")]
393    ErrAttributeSizeOverflow,
394    #[error("attempt to decode to nil message")]
395    ErrDecodeToNil,
396    #[error("unexpected EOF: not enough bytes to read header")]
397    ErrUnexpectedHeaderEof,
398    #[error("integrity check failed")]
399    ErrIntegrityMismatch,
400    #[error("fingerprint check failed")]
401    ErrFingerprintMismatch,
402    #[error("FINGERPRINT before MESSAGE-INTEGRITY attribute")]
403    ErrFingerprintBeforeIntegrity,
404    #[error("bad UNKNOWN-ATTRIBUTES size")]
405    ErrBadUnknownAttrsSize,
406    #[error("invalid length of IP value")]
407    ErrBadIpLength,
408    #[error("no connection provided")]
409    ErrNoConnection,
410    #[error("client is closed")]
411    ErrClientClosed,
412    #[error("no agent is set")]
413    ErrNoAgent,
414    #[error("collector is closed")]
415    ErrCollectorClosed,
416    #[error("unsupported network")]
417    ErrUnsupportedNetwork,
418    #[error("invalid url")]
419    ErrInvalidUrl,
420    #[error("unknown scheme type")]
421    ErrSchemeType,
422    #[error("invalid hostname")]
423    ErrHost,
424
425    // TURN errors
426    #[error("turn: RelayAddress must be valid IP to use RelayAddressGeneratorStatic")]
427    ErrRelayAddressInvalid,
428    #[error("turn: PacketConnConfigs and ConnConfigs are empty, unable to proceed")]
429    ErrNoAvailableConns,
430    #[error("turn: PacketConnConfig must have a non-nil Conn")]
431    ErrConnUnset,
432    #[error("turn: ListenerConfig must have a non-nil Listener")]
433    ErrListenerUnset,
434    #[error("turn: RelayAddressGenerator has invalid ListeningAddress")]
435    ErrListeningAddressInvalid,
436    #[error("turn: RelayAddressGenerator in RelayConfig is unset")]
437    ErrRelayAddressGeneratorUnset,
438    #[error("turn: max retries exceeded")]
439    ErrMaxRetriesExceeded,
440    #[error("turn: MaxPort must be not 0")]
441    ErrMaxPortNotZero,
442    #[error("turn: MaxPort must be not 0")]
443    ErrMinPortNotZero,
444    #[error("turn: MaxPort less than MinPort")]
445    ErrMaxPortLessThanMinPort,
446    #[error("turn: relay_conn cannot not be nil")]
447    ErrNilConn,
448    #[error("turn: TODO")]
449    ErrTodo,
450    #[error("turn: already listening")]
451    ErrAlreadyListening,
452    #[error("turn: Server failed to close")]
453    ErrFailedToClose,
454    #[error("turn: failed to retransmit transaction")]
455    ErrFailedToRetransmitTransaction,
456    #[error("all retransmissions failed")]
457    ErrAllRetransmissionsFailed,
458    #[error("no binding found for channel")]
459    ErrChannelBindNotFound,
460    #[error("STUN server address is not set for the client")]
461    ErrStunserverAddressNotSet,
462    #[error("only one Allocate() caller is allowed")]
463    ErrOneAllocateOnly,
464    #[error("already allocated")]
465    ErrAlreadyAllocated,
466    #[error("non-STUN message from STUN server")]
467    ErrNonStunmessage,
468    #[error("failed to decode STUN message")]
469    ErrFailedToDecodeStun,
470    #[error("unexpected STUN request message")]
471    ErrUnexpectedStunrequestMessage,
472    #[error("channel number not in [0x4000, 0x7FFF]")]
473    ErrInvalidChannelNumber,
474    #[error("channelData length != len(Data)")]
475    ErrBadChannelDataLength,
476    #[error("invalid value for requested family attribute")]
477    ErrInvalidRequestedFamilyValue,
478    #[error("fake error")]
479    ErrFakeErr,
480    #[error("use of closed network connection")]
481    ErrClosed,
482    #[error("addr is not a net.UDPAddr")]
483    ErrUdpaddrCast,
484    #[error("try-lock is already locked")]
485    ErrDoubleLock,
486    #[error("transaction closed")]
487    ErrTransactionClosed,
488    #[error("wait_for_result called on non-result transaction")]
489    ErrWaitForResultOnNonResultTransaction,
490    #[error("failed to build refresh request")]
491    ErrFailedToBuildRefreshRequest,
492    #[error("failed to refresh allocation")]
493    ErrFailedToRefreshAllocation,
494    #[error("failed to get lifetime from refresh response")]
495    ErrFailedToGetLifetime,
496    #[error("too short buffer")]
497    ErrShortBuffer,
498    #[error("unexpected response type")]
499    ErrUnexpectedResponse,
500    #[error("AllocatePacketConn must be set")]
501    ErrAllocatePacketConnMustBeSet,
502    #[error("AllocateConn must be set")]
503    ErrAllocateConnMustBeSet,
504    #[error("LeveledLogger must be set")]
505    ErrLeveledLoggerMustBeSet,
506    #[error("you cannot use the same channel number with different peer")]
507    ErrSameChannelDifferentPeer,
508    #[error("allocations must not be created with nil FivTuple")]
509    ErrNilFiveTuple,
510    #[error("allocations must not be created with nil FiveTuple.src_addr")]
511    ErrNilFiveTupleSrcAddr,
512    #[error("allocations must not be created with nil FiveTuple.dst_addr")]
513    ErrNilFiveTupleDstAddr,
514    #[error("allocations must not be created with nil turnSocket")]
515    ErrNilTurnSocket,
516    #[error("allocations must not be created with a lifetime of 0")]
517    ErrLifetimeZero,
518    #[error("allocation attempt created with duplicate FiveTuple")]
519    ErrDupeFiveTuple,
520    #[error("failed to cast net.Addr to *net.UDPAddr")]
521    ErrFailedToCastUdpaddr,
522    #[error("failed to generate nonce")]
523    ErrFailedToGenerateNonce,
524    #[error("failed to send error message")]
525    ErrFailedToSendError,
526    #[error("duplicated Nonce generated, discarding request")]
527    ErrDuplicatedNonce,
528    #[error("no such user exists")]
529    ErrNoSuchUser,
530    #[error("unexpected class")]
531    ErrUnexpectedClass,
532    #[error("unexpected method")]
533    ErrUnexpectedMethod,
534    #[error("failed to handle")]
535    ErrFailedToHandle,
536    #[error("unhandled STUN packet")]
537    ErrUnhandledStunpacket,
538    #[error("unable to handle ChannelData")]
539    ErrUnableToHandleChannelData,
540    #[error("failed to create stun message from packet")]
541    ErrFailedToCreateStunpacket,
542    #[error("failed to create channel data from packet")]
543    ErrFailedToCreateChannelData,
544    #[error("relay already allocated for 5-TUPLE")]
545    ErrRelayAlreadyAllocatedForFiveTuple,
546    #[error("RequestedTransport must be UDP")]
547    ErrRequestedTransportMustBeUdp,
548    #[error("no support for DONT-FRAGMENT")]
549    ErrNoDontFragmentSupport,
550    #[error("Request must not contain RESERVATION-TOKEN and EVEN-PORT")]
551    ErrRequestWithReservationTokenAndEvenPort,
552    #[error("no allocation found")]
553    ErrNoAllocationFound,
554    #[error("unable to handle send-indication, no permission added")]
555    ErrNoPermission,
556    #[error("packet write smaller than packet")]
557    ErrShortWrite,
558    #[error("no such channel bind")]
559    ErrNoSuchChannelBind,
560    #[error("failed writing to socket")]
561    ErrFailedWriteSocket,
562
563    // ICE errors
564    /// Indicates an error with Unknown info.
565    #[error("Unknown type")]
566    ErrUnknownType,
567
568    /// Indicates query arguments are provided in a STUN URL.
569    #[error("queries not supported in stun address")]
570    ErrStunQuery,
571
572    /// Indicates an malformed query is provided.
573    #[error("invalid query")]
574    ErrInvalidQuery,
575
576    /// Indicates malformed port is provided.
577    #[error("url parse: invalid port number")]
578    ErrPort,
579
580    /// Indicates local username fragment insufficient bits are provided.
581    /// Have to be at least 24 bits long.
582    #[error("local username fragment is less than 24 bits long")]
583    ErrLocalUfragInsufficientBits,
584
585    /// Indicates local passoword insufficient bits are provided.
586    /// Have to be at least 128 bits long.
587    #[error("local password is less than 128 bits long")]
588    ErrLocalPwdInsufficientBits,
589
590    /// Indicates an unsupported transport type was provided.
591    #[error("invalid transport protocol type")]
592    ErrProtoType,
593
594    /// Indicates agent does not have a valid candidate pair.
595    #[error("no candidate pairs available")]
596    ErrNoCandidatePairs,
597
598    /// Indicates agent connection was canceled by the caller.
599    #[error("connecting canceled by caller")]
600    ErrCanceledByCaller,
601
602    /// Indicates agent was started twice.
603    #[error("attempted to start agent twice")]
604    ErrMultipleStart,
605
606    /// Indicates agent was started with an empty remote ufrag.
607    #[error("remote ufrag is empty")]
608    ErrRemoteUfragEmpty,
609
610    /// Indicates agent was started with an empty remote pwd.
611    #[error("remote pwd is empty")]
612    ErrRemotePwdEmpty,
613
614    /// Indicates agent was started without on_candidate.
615    #[error("no on_candidate provided")]
616    ErrNoOnCandidateHandler,
617
618    /// Indicates GatherCandidates has been called multiple times.
619    #[error("attempting to gather candidates during gathering state")]
620    ErrMultipleGatherAttempted,
621
622    /// Indicates agent was give TURN URL with an empty Username.
623    #[error("username is empty")]
624    ErrUsernameEmpty,
625
626    /// Indicates agent was give TURN URL with an empty Password.
627    #[error("password is empty")]
628    ErrPasswordEmpty,
629
630    /// Indicates we were unable to parse a candidate address.
631    #[error("failed to parse address")]
632    ErrAddressParseFailed,
633
634    /// Indicates that non host candidates were selected for a lite agent.
635    #[error("lite agents must only use host candidates")]
636    ErrLiteUsingNonHostCandidates,
637
638    /// Indicates that current ice agent supports Lite only
639    #[error("lite support only")]
640    ErrLiteSupportOnly,
641
642    /// Indicates that one or more URL was provided to the agent but no host candidate required them.
643    #[error("agent does not need URL with selected candidate types")]
644    ErrUselessUrlsProvided,
645
646    /// Indicates that the specified NAT1To1IPCandidateType is unsupported.
647    #[error("unsupported 1:1 NAT IP candidate type")]
648    ErrUnsupportedNat1to1IpCandidateType,
649
650    /// Indicates that the given 1:1 NAT IP mapping is invalid.
651    #[error("invalid 1:1 NAT IP mapping")]
652    ErrInvalidNat1to1IpMapping,
653
654    /// IPNotFound in NAT1To1IPMapping.
655    #[error("external mapped IP not found")]
656    ErrExternalMappedIpNotFound,
657
658    /// Indicates that the mDNS gathering cannot be used along with 1:1 NAT IP mapping for host
659    /// candidate.
660    #[error("mDNS gathering cannot be used with 1:1 NAT IP mapping for host candidate")]
661    ErrMulticastDnsWithNat1to1IpMapping,
662
663    /// Indicates that 1:1 NAT IP mapping for host candidate is requested, but the host candidate
664    /// type is disabled.
665    #[error("1:1 NAT IP mapping for host candidate ineffective")]
666    ErrIneffectiveNat1to1IpMappingHost,
667
668    /// Indicates that 1:1 NAT IP mapping for srflx candidate is requested, but the srflx candidate
669    /// type is disabled.
670    #[error("1:1 NAT IP mapping for srflx candidate ineffective")]
671    ErrIneffectiveNat1to1IpMappingSrflx,
672
673    /// Indicates an invalid MulticastDNSHostName.
674    #[error("invalid mDNS HostName, must end with .local and can only contain a single '.'")]
675    ErrInvalidMulticastDnshostName,
676
677    /// Indicates mdns is not supported.
678    #[error("mdns is not supported")]
679    ErrMulticastDnsNotSupported,
680
681    /// Indicates Restart was called when Agent is in GatheringStateGathering.
682    #[error("ICE Agent can not be restarted when gathering")]
683    ErrRestartWhenGathering,
684
685    /// Indicates a run operation was canceled by its individual done.
686    #[error("run was canceled by done")]
687    ErrRunCanceled,
688
689    /// Initialized Indicates TCPMux is not initialized and that invalidTCPMux is used.
690    #[error("TCPMux is not initialized")]
691    ErrTcpMuxNotInitialized,
692
693    /// Indicates we already have the connection with same remote addr.
694    #[error("conn with same remote addr already exists")]
695    ErrTcpRemoteAddrAlreadyExists,
696
697    #[error("failed to send packet")]
698    ErrSendPacket,
699    #[error("attribute not long enough to be ICE candidate")]
700    ErrAttributeTooShortIceCandidate,
701    #[error("could not parse component")]
702    ErrParseComponent,
703    #[error("could not parse priority")]
704    ErrParsePriority,
705    #[error("could not parse port")]
706    ErrParsePort,
707    #[error("could not parse related addresses")]
708    ErrParseRelatedAddr,
709    #[error("could not parse type")]
710    ErrParseType,
711    #[error("unknown candidate type")]
712    ErrUnknownCandidateType,
713    #[error("failed to get XOR-MAPPED-ADDRESS response")]
714    ErrGetXorMappedAddrResponse,
715    #[error("connection with same remote address already exists")]
716    ErrConnectionAddrAlreadyExist,
717    #[error("error reading streaming packet")]
718    ErrReadingStreamingPacket,
719    #[error("error writing to")]
720    ErrWriting,
721    #[error("error closing connection")]
722    ErrClosingConnection,
723    #[error("unable to determine networkType")]
724    ErrDetermineNetworkType,
725    #[error("missing protocol scheme")]
726    ErrMissingProtocolScheme,
727    #[error("too many colons in address")]
728    ErrTooManyColonsAddr,
729    #[error("unexpected error trying to read")]
730    ErrRead,
731    #[error("unknown role")]
732    ErrUnknownRole,
733    #[error("username mismatch")]
734    ErrMismatchUsername,
735    #[error("the ICE conn can't write STUN messages")]
736    ErrIceWriteStunMessage,
737    #[error("url parse: relative URL without a base")]
738    ErrUrlParse,
739    #[error("Candidate IP could not be found")]
740    ErrCandidateIpNotFound,
741
742    // DTLS errors
743    #[error("conn is closed")]
744    ErrConnClosed,
745    #[error("read/write timeout")]
746    ErrDeadlineExceeded,
747    #[error("context is not supported for export_keying_material")]
748    ErrContextUnsupported,
749    #[error("packet is too short")]
750    ErrDtlspacketInvalidLength,
751    #[error("handshake is in progress")]
752    ErrHandshakeInProgress,
753    #[error("invalid content type")]
754    ErrInvalidContentType,
755    #[error("invalid mac")]
756    ErrInvalidMac,
757    #[error("packet length and declared length do not match")]
758    ErrInvalidPacketLength,
759    #[error("export_keying_material can not be used with a reserved label")]
760    ErrReservedExportKeyingMaterial,
761    #[error("client sent certificate verify but we have no certificate to verify")]
762    ErrCertificateVerifyNoCertificate,
763    #[error("client+server do not support any shared cipher suites")]
764    ErrCipherSuiteNoIntersection,
765    #[error("server hello can not be created without a cipher suite")]
766    ErrCipherSuiteUnset,
767    #[error("client sent certificate but did not verify it")]
768    ErrClientCertificateNotVerified,
769    #[error("server required client verification, but got none")]
770    ErrClientCertificateRequired,
771    #[error("server responded with SRTP Profile we do not support")]
772    ErrClientNoMatchingSrtpProfile,
773    #[error("client required Extended Master Secret extension, but server does not support it")]
774    ErrClientRequiredButNoServerEms,
775    #[error("server hello can not be created without a compression method")]
776    ErrCompressionMethodUnset,
777    #[error("client+server cookie does not match")]
778    ErrCookieMismatch,
779    #[error("cookie must not be longer then 255 bytes")]
780    ErrCookieTooLong,
781    #[error("PSK Identity Hint provided but PSK is nil")]
782    ErrIdentityNoPsk,
783    #[error("no certificate provided")]
784    ErrInvalidCertificate,
785    #[error("cipher spec invalid")]
786    ErrInvalidCipherSpec,
787    #[error("invalid or unknown cipher suite")]
788    ErrInvalidCipherSuite,
789    #[error("unable to determine if ClientKeyExchange is a public key or PSK Identity")]
790    ErrInvalidClientKeyExchange,
791    #[error("invalid or unknown compression method")]
792    ErrInvalidCompressionMethod,
793    #[error("ECDSA signature contained zero or negative values")]
794    ErrInvalidEcdsasignature,
795    #[error("invalid or unknown elliptic curve type")]
796    ErrInvalidEllipticCurveType,
797    #[error("invalid extension type")]
798    ErrInvalidExtensionType,
799    #[error("invalid hash algorithm")]
800    ErrInvalidHashAlgorithm,
801    #[error("invalid named curve")]
802    ErrInvalidNamedCurve,
803    #[error("invalid private key type")]
804    ErrInvalidPrivateKey,
805    #[error("named curve and private key type does not match")]
806    ErrNamedCurveAndPrivateKeyMismatch,
807    #[error("invalid server name format")]
808    ErrInvalidSniFormat,
809    #[error("invalid signature algorithm")]
810    ErrInvalidSignatureAlgorithm,
811    #[error("expected and actual key signature do not match")]
812    ErrKeySignatureMismatch,
813    #[error("Conn can not be created with a nil nextConn")]
814    ErrNilNextConn,
815    #[error("connection can not be created, no CipherSuites satisfy this Config")]
816    ErrNoAvailableCipherSuites,
817    #[error("connection can not be created, no SignatureScheme satisfy this Config")]
818    ErrNoAvailableSignatureSchemes,
819    #[error("no certificates configured")]
820    ErrNoCertificates,
821    #[error("no config provided")]
822    ErrNoConfigProvided,
823    #[error("client requested zero or more elliptic curves that are not supported by the server")]
824    ErrNoSupportedEllipticCurves,
825    #[error("unsupported protocol version")]
826    ErrUnsupportedProtocolVersion,
827    #[error("Certificate and PSK provided")]
828    ErrPskAndCertificate,
829    #[error("PSK and PSK Identity Hint must both be set for client")]
830    ErrPskAndIdentityMustBeSetForClient,
831    #[error("SRTP support was requested but server did not respond with use_srtp extension")]
832    ErrRequestedButNoSrtpExtension,
833    #[error("Certificate is mandatory for server")]
834    ErrServerMustHaveCertificate,
835    #[error("client requested SRTP but we have no matching profiles")]
836    ErrServerNoMatchingSrtpProfile,
837    #[error(
838        "server requires the Extended Master Secret extension, but the client does not support it"
839    )]
840    ErrServerRequiredButNoClientEms,
841    #[error("expected and actual verify data does not match")]
842    ErrVerifyDataMismatch,
843    #[error("handshake message unset, unable to marshal")]
844    ErrHandshakeMessageUnset,
845    #[error("invalid flight number")]
846    ErrInvalidFlight,
847    #[error("unable to generate key signature, unimplemented")]
848    ErrKeySignatureGenerateUnimplemented,
849    #[error("unable to verify key signature, unimplemented")]
850    ErrKeySignatureVerifyUnimplemented,
851    #[error("data length and declared length do not match")]
852    ErrLengthMismatch,
853    #[error("buffer not long enough to contain nonce")]
854    ErrNotEnoughRoomForNonce,
855    #[error("feature has not been implemented yet")]
856    ErrNotImplemented,
857    #[error("sequence number overflow")]
858    ErrSequenceNumberOverflow,
859    #[error("unable to marshal fragmented handshakes")]
860    ErrUnableToMarshalFragmented,
861    #[error("invalid state machine transition")]
862    ErrInvalidFsmTransition,
863    #[error("ApplicationData with epoch of 0")]
864    ErrApplicationDataEpochZero,
865    #[error("unhandled contentType")]
866    ErrUnhandledContextType,
867    #[error("context canceled")]
868    ErrContextCanceled,
869    #[error("empty fragment")]
870    ErrEmptyFragment,
871    #[error("Alert is Fatal or Close Notify")]
872    ErrAlertFatalOrClose,
873    #[error(
874        "Fragment buffer overflow. New size {new_size} is greater than specified max {max_size}"
875    )]
876    ErrFragmentBufferOverflow { new_size: usize, max_size: usize },
877    #[error("Client transport is not set yet")]
878    ErrClientTransportNotSet,
879
880    /// The endpoint can no longer create new connections
881    ///
882    /// Indicates that a necessary component of the endpoint has been dropped or otherwise disabled.
883    #[error("endpoint stopping")]
884    EndpointStopping,
885    /// The number of active connections on the local endpoint is at the limit
886    ///
887    /// Try using longer connection IDs.
888    #[error("too many connections")]
889    TooManyConnections,
890    /// The domain name supplied was malformed
891    #[error("invalid DNS name: {0}")]
892    InvalidDnsName(String),
893    /// The remote [`SocketAddr`] supplied was malformed
894    ///
895    /// Examples include attempting to connect to port 0, or using an inappropriate address family.
896    #[error("invalid remote address: {0}")]
897    InvalidRemoteAddress(SocketAddr),
898    /// No client configuration was set up
899    #[error("no client config")]
900    NoClientConfig,
901    /// No server configuration was set up
902    #[error("no server config")]
903    NoServerConfig,
904
905    //SCTP errors
906    #[error("raw is too small for a SCTP chunk")]
907    ErrChunkHeaderTooSmall,
908    #[error("not enough data left in SCTP packet to satisfy requested length")]
909    ErrChunkHeaderNotEnoughSpace,
910    #[error("chunk PADDING is non-zero at offset")]
911    ErrChunkHeaderPaddingNonZero,
912    #[error("chunk has invalid length")]
913    ErrChunkHeaderInvalidLength,
914
915    #[error("ChunkType is not of type ABORT")]
916    ErrChunkTypeNotAbort,
917    #[error("failed build Abort Chunk")]
918    ErrBuildAbortChunkFailed,
919    #[error("ChunkType is not of type COOKIEACK")]
920    ErrChunkTypeNotCookieAck,
921    #[error("ChunkType is not of type COOKIEECHO")]
922    ErrChunkTypeNotCookieEcho,
923    #[error("ChunkType is not of type ctError")]
924    ErrChunkTypeNotCt,
925    #[error("failed build Error Chunk")]
926    ErrBuildErrorChunkFailed,
927    #[error("failed to marshal stream")]
928    ErrMarshalStreamFailed,
929    #[error("chunk too short")]
930    ErrChunkTooShort,
931    #[error("ChunkType is not of type ForwardTsn")]
932    ErrChunkTypeNotForwardTsn,
933    #[error("ChunkType is not of type HEARTBEAT")]
934    ErrChunkTypeNotHeartbeat,
935    #[error("ChunkType is not of type HEARTBEATACK")]
936    ErrChunkTypeNotHeartbeatAck,
937    #[error("heartbeat is not long enough to contain Heartbeat Info")]
938    ErrHeartbeatNotLongEnoughInfo,
939    #[error("failed to parse param type")]
940    ErrParseParamTypeFailed,
941    #[error("heartbeat should only have HEARTBEAT param")]
942    ErrHeartbeatParam,
943    #[error("failed unmarshalling param in Heartbeat Chunk")]
944    ErrHeartbeatChunkUnmarshal,
945    #[error("unimplemented")]
946    ErrUnimplemented,
947    #[error("heartbeat Ack must have one param")]
948    ErrHeartbeatAckParams,
949    #[error("heartbeat Ack must have one param, and it should be a HeartbeatInfo")]
950    ErrHeartbeatAckNotHeartbeatInfo,
951    #[error("unable to marshal parameter for Heartbeat Ack")]
952    ErrHeartbeatAckMarshalParam,
953
954    #[error("raw is too small for error cause")]
955    ErrErrorCauseTooSmall,
956
957    #[error("unhandled ParamType: {typ}")]
958    ErrParamTypeUnhandled { typ: u16 },
959
960    #[error("unexpected ParamType")]
961    ErrParamTypeUnexpected,
962
963    #[error("param header too short")]
964    ErrParamHeaderTooShort,
965    #[error("param self reported length is shorter than header length")]
966    ErrParamHeaderSelfReportedLengthShorter,
967    #[error("param self reported length is longer than header length")]
968    ErrParamHeaderSelfReportedLengthLonger,
969    #[error("failed to parse param type")]
970    ErrParamHeaderParseFailed,
971
972    #[error("packet to short")]
973    ErrParamPacketTooShort,
974    #[error("outgoing SSN reset request parameter too short")]
975    ErrSsnResetRequestParamTooShort,
976    #[error("failed unmarshalling SSN reset request parameter in RE-CONFIG chunk")]
977    ErrUnmarshalSsnResetRequestParam,
978    #[error("reconfig response parameter too short")]
979    ErrReconfigRespParamTooShort,
980    #[error("failed unmarshalling re-configuration response parameter in RE-CONFIG chunk")]
981    ErrUnmarshalReconfigRespParam,
982    #[error("invalid algorithm type")]
983    ErrInvalidAlgorithmType,
984
985    #[error("failed to parse param type")]
986    ErrInitChunkParseParamTypeFailed,
987    #[error("failed unmarshalling param in Init Chunk")]
988    ErrInitChunkUnmarshalParam,
989    #[error("unable to marshal parameter for INIT/INITACK")]
990    ErrInitAckMarshalParam,
991
992    #[error("ChunkType is not of type INIT")]
993    ErrChunkTypeNotTypeInit,
994    #[error("chunk Value isn't long enough for mandatory parameters exp")]
995    ErrChunkValueNotLongEnough,
996    #[error("ChunkType of type INIT flags must be all 0")]
997    ErrChunkTypeInitFlagZero,
998    #[error("failed to unmarshal INIT body")]
999    ErrChunkTypeInitUnmarshalFailed,
1000    #[error("failed marshaling INIT common data")]
1001    ErrChunkTypeInitMarshalFailed,
1002    #[error("ChunkType of type INIT ACK InitiateTag must not be 0")]
1003    ErrChunkTypeInitInitiateTagZero,
1004    #[error("INIT ACK inbound stream request must be > 0")]
1005    ErrInitInboundStreamRequestZero,
1006    #[error("INIT ACK outbound stream request must be > 0")]
1007    ErrInitOutboundStreamRequestZero,
1008    #[error("INIT ACK Advertised Receiver Window Credit (a_rwnd) must be >= 1500")]
1009    ErrInitAdvertisedReceiver1500,
1010
1011    #[error("packet is smaller than the header size")]
1012    ErrChunkPayloadSmall,
1013    #[error("ChunkType is not of type PayloadData")]
1014    ErrChunkTypeNotPayloadData,
1015    #[error("failed unmarshalling payload data chunk")]
1016    ErrChunkUnmarshalPayloadData,
1017    #[error("ChunkType is not of type Reconfig")]
1018    ErrChunkTypeNotReconfig,
1019    #[error("ChunkReconfig has invalid ParamA")]
1020    ErrChunkReconfigInvalidParamA,
1021
1022    #[error("failed to parse param type")]
1023    ErrChunkParseParamTypeFailed,
1024    #[error("unable to marshal parameter A for reconfig")]
1025    ErrChunkMarshalParamAReconfigFailed,
1026    #[error("unable to marshal parameter B for reconfig")]
1027    ErrChunkMarshalParamBReconfigFailed,
1028
1029    #[error("ChunkType is not of type SACK")]
1030    ErrChunkTypeNotSack,
1031    #[error("SACK Chunk size is not large enough to contain header")]
1032    ErrSackSizeNotLargeEnoughInfo,
1033    #[error("failed unmarshalling SACK chunk")]
1034    ErrChunkUnmarshalSack,
1035
1036    #[error("invalid chunk size")]
1037    ErrInvalidChunkSize,
1038    #[error("ChunkType is not of type SHUTDOWN")]
1039    ErrChunkTypeNotShutdown,
1040    #[error("failed unmarshalling shutdown chunk")]
1041    ErrChunkUnmarshalShutdown,
1042
1043    #[error("ChunkType is not of type SHUTDOWN-ACK")]
1044    ErrChunkTypeNotShutdownAck,
1045    #[error("ChunkType is not of type SHUTDOWN-COMPLETE")]
1046    ErrChunkTypeNotShutdownComplete,
1047
1048    #[error("raw is smaller than the minimum length for a SCTP packet")]
1049    ErrPacketRawTooSmall,
1050    #[error("unable to parse SCTP chunk, not enough data for complete header")]
1051    ErrParseSctpChunkNotEnoughData,
1052    #[error("failed to unmarshal, contains unknown chunk type")]
1053    ErrUnmarshalUnknownChunkType,
1054    #[error("checksum mismatch theirs")]
1055    ErrChecksumMismatch,
1056
1057    #[error("unexpected chunk popped (unordered)")]
1058    ErrUnexpectedChuckPoppedUnordered,
1059    #[error("unexpected chunk popped (ordered)")]
1060    ErrUnexpectedChuckPoppedOrdered,
1061    #[error("unexpected q state (should've been selected)")]
1062    ErrUnexpectedQState,
1063    #[error("try again")]
1064    ErrTryAgain,
1065
1066    #[error("abort chunk, with following errors: {0}")]
1067    ErrAbortChunk(String),
1068    #[error("shutdown called in non-Established state")]
1069    ErrShutdownNonEstablished,
1070    #[error("association closed before connecting")]
1071    ErrAssociationClosedBeforeConn,
1072    #[error("association init failed")]
1073    ErrAssociationInitFailed,
1074    #[error("association handshake closed")]
1075    ErrAssociationHandshakeClosed,
1076    #[error("silently discard")]
1077    ErrSilentlyDiscard,
1078    #[error("the init not stored to send")]
1079    ErrInitNotStoredToSend,
1080    #[error("cookieEcho not stored to send")]
1081    ErrCookieEchoNotStoredToSend,
1082    #[error("sctp packet must not have a source port of 0")]
1083    ErrSctpPacketSourcePortZero,
1084    #[error("sctp packet must not have a destination port of 0")]
1085    ErrSctpPacketDestinationPortZero,
1086    #[error("init chunk must not be bundled with any other chunk")]
1087    ErrInitChunkBundled,
1088    #[error("init chunk expects a verification tag of 0 on the packet when out-of-the-blue")]
1089    ErrInitChunkVerifyTagNotZero,
1090    #[error("todo: handle Init when in state")]
1091    ErrHandleInitState,
1092    #[error("no cookie in InitAck")]
1093    ErrInitAckNoCookie,
1094    #[error("there already exists a stream with identifier")]
1095    ErrStreamAlreadyExist,
1096    #[error("Failed to create a stream with identifier")]
1097    ErrStreamCreateFailed,
1098    #[error("unable to be popped from inflight queue TSN")]
1099    ErrInflightQueueTsnPop,
1100    #[error("requested non-existent TSN")]
1101    ErrTsnRequestNotExist,
1102    #[error("sending reset packet in non-Established state")]
1103    ErrResetPacketInStateNotExist,
1104    #[error("unexpected parameter type")]
1105    ErrParameterType,
1106    #[error("sending payload data in non-Established state")]
1107    ErrPayloadDataStateNotExist,
1108    #[error("unhandled chunk type")]
1109    ErrChunkTypeUnhandled,
1110    #[error("handshake failed (INIT ACK)")]
1111    ErrHandshakeInitAck,
1112    #[error("handshake failed (COOKIE ECHO)")]
1113    ErrHandshakeCookieEcho,
1114
1115    #[error("outbound packet larger than maximum message size")]
1116    ErrOutboundPacketTooLarge,
1117    #[error("Stream closed")]
1118    ErrStreamClosed,
1119    #[error("Stream not existed")]
1120    ErrStreamNotExisted,
1121    #[error("Association not existed")]
1122    ErrAssociationNotExisted,
1123    #[error("Transport not existed")]
1124    ErrTransportNoExisted,
1125    #[error("Io EOF")]
1126    ErrEof,
1127    #[error("Invalid SystemTime")]
1128    ErrInvalidSystemTime,
1129    #[error("Net Conn read error")]
1130    ErrNetConnRead,
1131    #[error("Max Data Channel ID")]
1132    ErrMaxDataChannelID,
1133
1134    //Data Channel
1135    #[error(
1136        "DataChannel message is not long enough to determine type: (expected: {expected}, actual: {actual})"
1137    )]
1138    UnexpectedEndOfBuffer { expected: usize, actual: usize },
1139    #[error("Unknown MessageType {0}")]
1140    InvalidMessageType(u8),
1141    #[error("Unknown ChannelType {0}")]
1142    InvalidChannelType(u8),
1143    #[error("Unknown PayloadProtocolIdentifier {0}")]
1144    InvalidPayloadProtocolIdentifier(u8),
1145    #[error("Unknow Protocol")]
1146    UnknownProtocol,
1147
1148    //Media
1149    #[error("stream is nil")]
1150    ErrNilStream,
1151    #[error("incomplete frame header")]
1152    ErrIncompleteFrameHeader,
1153    #[error("incomplete frame data")]
1154    ErrIncompleteFrameData,
1155    #[error("incomplete file header")]
1156    ErrIncompleteFileHeader,
1157    #[error("IVF signature mismatch")]
1158    ErrSignatureMismatch,
1159    #[error("IVF version unknown, parser may not parse correctly")]
1160    ErrUnknownIVFVersion,
1161
1162    #[error("file not opened")]
1163    ErrFileNotOpened,
1164    #[error("invalid nil packet")]
1165    ErrInvalidNilPacket,
1166
1167    #[error("bad header signature")]
1168    ErrBadIDPageSignature,
1169    #[error("wrong header, expected beginning of stream")]
1170    ErrBadIDPageType,
1171    #[error("payload for id page must be 19 bytes")]
1172    ErrBadIDPageLength,
1173    #[error("bad payload signature")]
1174    ErrBadIDPagePayloadSignature,
1175    #[error("not enough data for payload header")]
1176    ErrShortPageHeader,
1177    #[error("bad OpusTags signature")]
1178    ErrBadOpusTagsSignature,
1179    #[error("unsupported channel mapping family")]
1180    ErrUnsupportedChannelMappingFamily,
1181
1182    #[error("data is not a H264 bitstream")]
1183    ErrDataIsNotH264Stream,
1184    #[error("data is not a H265 bitstream")]
1185    ErrDataIsNotH265Stream,
1186    #[error("Io EOF")]
1187    ErrIoEOF,
1188
1189    // mDNS
1190    #[error("mDNS: port not support, only 5353 is supported")]
1191    ErrMDNSPortNotSupported,
1192    #[error("mDNS: connection is closed")]
1193    ErrMDNSConnectionClosed,
1194    #[error("mDNS: query not found")]
1195    ErrMDNSQueryNotFound,
1196    #[error("mDNS: parsing/packing of this type isn't available yet")]
1197    ErrNotStarted,
1198    #[error("mDNS: parsing/packing of this section has completed")]
1199    ErrSectionDone,
1200    #[error("mDNS: parsing/packing of this section is header")]
1201    ErrSectionHeader,
1202    #[error("mDNS: insufficient data for base length type")]
1203    ErrBaseLen,
1204    #[error("mDNS: insufficient data for calculated length type")]
1205    ErrCalcLen,
1206    #[error("mDNS: segment prefix is reserved")]
1207    ErrReserved,
1208    #[error("mDNS: too many pointers (>10)")]
1209    ErrTooManyPtr,
1210    #[error("mDNS: invalid pointer")]
1211    ErrInvalidPtr,
1212    #[error("mDNS: nil resource body")]
1213    ErrNilResourceBody,
1214    #[error("mDNS: insufficient data for resource body length")]
1215    ErrResourceLen,
1216    #[error("mDNS: segment length too long")]
1217    ErrSegTooLong,
1218    #[error("mDNS: zero length segment")]
1219    ErrZeroSegLen,
1220    #[error("mDNS: resource length too long")]
1221    ErrResTooLong,
1222    #[error("mDNS: too many Questions to pack (>65535)")]
1223    ErrTooManyQuestions,
1224    #[error("mDNS: too many Answers to pack (>65535)")]
1225    ErrTooManyAnswers,
1226    #[error("mDNS: too many Authorities to pack (>65535)")]
1227    ErrTooManyAuthorities,
1228    #[error("mDNS: too many Additionals to pack (>65535)")]
1229    ErrTooManyAdditionals,
1230    #[error("mDNS: name is not in canonical format (it must end with a .)")]
1231    ErrNonCanonicalName,
1232    #[error("mDNS: character string exceeds maximum length (255)")]
1233    ErrStringTooLong,
1234    #[error("mDNS: compressed name in SRV resource data")]
1235    ErrCompressedSrv,
1236    #[error("mDNS: empty builder msg")]
1237    ErrEmptyBuilderMsg,
1238
1239    //RTC
1240    /// ErrConnectionClosed indicates an operation executed after connection
1241    /// has already been closed.
1242    #[error("connection closed")]
1243    ErrConnectionClosed,
1244
1245    /// ErrDataChannelClosed indicates an operation executed when the data
1246    /// channel is not (yet) open or closed.
1247    #[error("data channel closed")]
1248    ErrDataChannelClosed,
1249
1250    /// ErrDataChannelNonExist indicates an operation executed when the data
1251    /// channel not existed.
1252    #[error("data channel not existed")]
1253    ErrDataChannelNotExisted,
1254
1255    /// ErrCertificateExpired indicates that an x509 certificate has expired.
1256    #[error("x509Cert expired")]
1257    ErrCertificateExpired,
1258
1259    /// ErrNoTurnCredentials indicates that a TURN server URL was provided
1260    /// without required credentials.
1261    #[error("turn server credentials required")]
1262    ErrNoTurnCredentials,
1263
1264    /// ErrTurnCredentials indicates that provided TURN credentials are partial
1265    /// or malformed.
1266    #[error("invalid turn server credentials")]
1267    ErrTurnCredentials,
1268
1269    /// ErrExistingTrack indicates that a track already exists.
1270    #[error("track already exists")]
1271    ErrExistingTrack,
1272
1273    /// ErrExistingTrack indicates that a track already exists.
1274    #[error("track not existed")]
1275    ErrTrackNotExisted,
1276
1277    /// ErrPrivateKeyType indicates that a particular private key encryption
1278    /// chosen to generate a certificate is not supported.
1279    #[error("private key type not supported")]
1280    ErrPrivateKeyType,
1281
1282    /// ErrModifyingPeerIdentity indicates that an attempt to modify
1283    /// PeerIdentity was made after PeerConnection has been initialized.
1284    #[error("peerIdentity cannot be modified")]
1285    ErrModifyingPeerIdentity,
1286
1287    /// ErrModifyingCertificates indicates that an attempt to modify
1288    /// Certificates was made after PeerConnection has been initialized.
1289    #[error("certificates cannot be modified")]
1290    ErrModifyingCertificates,
1291
1292    /// ErrNonCertificate indicates that there is no certificate
1293    #[error("no certificate")]
1294    ErrNonCertificate,
1295
1296    /// ErrModifyingBundlePolicy indicates that an attempt to modify
1297    /// BundlePolicy was made after PeerConnection has been initialized.
1298    #[error("bundle policy cannot be modified")]
1299    ErrModifyingBundlePolicy,
1300
1301    /// ErrModifyingRTCPMuxPolicy indicates that an attempt to modify
1302    /// RTCPMuxPolicy was made after PeerConnection has been initialized.
1303    #[error("rtcp mux policy cannot be modified")]
1304    ErrModifyingRTCPMuxPolicy,
1305
1306    /// ErrModifyingICECandidatePoolSize indicates that an attempt to modify
1307    /// ICECandidatePoolSize was made after PeerConnection has been initialized.
1308    #[error("ice candidate pool size cannot be modified")]
1309    ErrModifyingICECandidatePoolSize,
1310
1311    /// ErrStringSizeLimit indicates that the character size limit of string is
1312    /// exceeded. The limit is hardcoded to 65535 according to specifications.
1313    #[error("data channel label exceeds size limit")]
1314    ErrStringSizeLimit,
1315
1316    /// ErrNegotiatedWithoutID indicates that an attempt to create a data channel
1317    /// was made while setting the negotiated option to true without providing
1318    /// the negotiated channel ID.
1319    #[error("negotiated set without channel id")]
1320    ErrNegotiatedWithoutID,
1321
1322    /// ErrRetransmitsOrPacketLifeTime indicates that an attempt to create a data
1323    /// channel was made with both options max_packet_life_time and max_retransmits
1324    /// set together. Such configuration is not supported by the specification
1325    /// and is mutually exclusive.
1326    #[error("both max_packet_life_time and max_retransmits was set")]
1327    ErrRetransmitsOrPacketLifeTime,
1328
1329    /// ErrCodecNotFound is returned when a codec search to the Media Engine fails
1330    #[error("codec not found")]
1331    ErrCodecNotFound,
1332
1333    /// ErrNoRemoteDescription indicates that an operation was rejected because
1334    /// the remote description is not set
1335    #[error("remote description is not set")]
1336    ErrNoRemoteDescription,
1337
1338    /// ErrIncorrectSDPSemantics indicates that the PeerConnection was configured to
1339    /// generate SDP Answers with different SDP Semantics than the received Offer
1340    #[error("offer SDP semantics does not match configuration")]
1341    ErrIncorrectSDPSemantics,
1342
1343    /// ErrIncorrectSignalingState indicates that the signaling state of PeerConnection is not correct
1344    #[error("operation can not be run in current signaling state")]
1345    ErrIncorrectSignalingState,
1346
1347    /// ErrProtocolTooLarge indicates that value given for a DataChannelInit protocol is
1348    /// longer then 65535 bytes
1349    #[error("protocol is larger then 65535 bytes")]
1350    ErrProtocolTooLarge,
1351
1352    /// ErrSenderNotCreatedByConnection indicates remove_track was called with a RtpSender not created
1353    /// by this PeerConnection
1354    #[error("RtpSender not created by this PeerConnection")]
1355    ErrSenderNotCreatedByConnection,
1356
1357    /// ErrSenderInitialTrackIdAlreadySet indicates a second call to
1358    /// RtpSender::set_initial_track_id which is not allowed.
1359    #[error("RtpSender's initial_track_id has already been set")]
1360    ErrSenderInitialTrackIdAlreadySet,
1361
1362    /// ErrSessionDescriptionNoFingerprint indicates set_remote_description was called with a SessionDescription that has no
1363    /// fingerprint
1364    #[error("set_remote_description called with no fingerprint")]
1365    ErrSessionDescriptionNoFingerprint,
1366
1367    /// ErrSessionDescriptionInvalidFingerprint indicates set_remote_description was called with a SessionDescription that
1368    /// has an invalid fingerprint
1369    #[error("set_remote_description called with an invalid fingerprint")]
1370    ErrSessionDescriptionInvalidFingerprint,
1371
1372    /// ErrSessionDescriptionConflictingFingerprints indicates set_remote_description was called with a SessionDescription that
1373    /// has an conflicting fingerprints
1374    #[error("set_remote_description called with multiple conflicting fingerprint")]
1375    ErrSessionDescriptionConflictingFingerprints,
1376
1377    /// ErrSessionDescriptionMissingIceUfrag indicates set_remote_description was called with a SessionDescription that
1378    /// is missing an ice-ufrag value
1379    #[error("set_remote_description called with no ice-ufrag")]
1380    ErrSessionDescriptionMissingIceUfrag,
1381
1382    /// ErrSessionDescriptionMissingIcePwd indicates set_remote_description was called with a SessionDescription that
1383    /// is missing an ice-pwd value
1384    #[error("set_remote_description called with no ice-pwd")]
1385    ErrSessionDescriptionMissingIcePwd,
1386
1387    /// ErrSessionDescriptionConflictingIceUfrag  indicates set_remote_description was called with a SessionDescription that
1388    /// contains multiple conflicting ice-ufrag values
1389    #[error("set_remote_description called with multiple conflicting ice-ufrag values")]
1390    ErrSessionDescriptionConflictingIceUfrag,
1391
1392    /// ErrSessionDescriptionConflictingIcePwd indicates set_remote_description was called with a SessionDescription that
1393    /// contains multiple conflicting ice-pwd values
1394    #[error("set_remote_description called with multiple conflicting ice-pwd values")]
1395    ErrSessionDescriptionConflictingIcePwd,
1396
1397    /// ErrNoSRTPProtectionProfile indicates that the DTLS handshake completed and no SRTP Protection Profile was chosen
1398    #[error("DTLS Handshake completed and no SRTP Protection Profile was chosen")]
1399    ErrNoSRTPProtectionProfile,
1400
1401    /// ErrFailedToGenerateCertificateFingerprint indicates that we failed to generate the fingerprint used for comparing certificates
1402    #[error("failed to generate certificate fingerprint")]
1403    ErrFailedToGenerateCertificateFingerprint,
1404
1405    /// ErrNoCodecsAvailable indicates that operation isn't possible because the MediaEngine has no codecs available
1406    #[error("operation failed no codecs are available")]
1407    ErrNoCodecsAvailable,
1408
1409    /// ErrUnsupportedCodec indicates the remote peer doesn't support the requested codec
1410    #[error("unable to start track, codec is not supported by remote")]
1411    ErrUnsupportedCodec,
1412
1413    #[error("Invalid state error")]
1414    InvalidStateError,
1415
1416    #[error("Invalid modification error")]
1417    InvalidModificationError,
1418
1419    #[error("Range error {0}")]
1420    RangeError(String),
1421
1422    /// ErrSenderWithNoCodecs indicates that a RTPSender was created without any codecs. To send media the MediaEngine needs at
1423    /// least one configured codec.
1424    #[error("unable to populate media section, RTPSender created with no codecs")]
1425    ErrSenderWithNoCodecs,
1426
1427    /// ErrSenderWithNoSSRCs indicates that a RTPSender was created without any SSRRs. To send media the Sender needs at
1428    /// least one configured ssrc.
1429    #[error("unable to populate media section, RTPSender created with no ssrcs")]
1430    ErrSenderWithNoSSRCs,
1431
1432    /// ErrRTPSenderNewTrackHasIncorrectKind indicates that the new track is of a different kind than the previous/original
1433    #[error("new track must be of the same kind as previous")]
1434    ErrRTPSenderNewTrackHasIncorrectKind,
1435
1436    #[error("new track has incorrect envelope")]
1437    ErrRTPSenderNewTrackHasIncorrectEnvelope,
1438
1439    /// ErrRTPSenderDataSent indicates that the sequence number transformer tries to be enabled after the data sending began
1440    #[error("Sequence number transformer must be enabled before sending data")]
1441    ErrRTPSenderDataSent,
1442
1443    /// ErrRTPSenderSeqTransEnabled indicates that the sequence number transformer has been already enabled
1444    #[error("Sequence number transformer has been already enabled")]
1445    ErrRTPSenderSeqTransEnabled,
1446
1447    /// ErrUnbindFailed indicates that a TrackLocal was not able to be unbind
1448    #[error("failed to unbind TrackLocal from PeerConnection")]
1449    ErrUnbindFailed,
1450
1451    /// ErrNoPayloaderForCodec indicates that the requested codec does not have a payloader
1452    #[error("the requested codec does not have a payloader")]
1453    ErrNoPayloaderForCodec,
1454
1455    /// ErrRegisterHeaderExtensionInvalidDirection indicates that a extension was registered with different
1456    /// directions for two different calls.
1457    #[error("a header extension must be registered with the same direction each time")]
1458    ErrRegisterHeaderExtensionInvalidDirection,
1459
1460    #[error("invalid direction")]
1461    ErrInvalidDirection,
1462
1463    /// ErrRegisterHeaderExtensionNoFreeID indicates that there was no extension ID available which
1464    /// in turn means that all 15 available id(1 through 14) have been used.
1465    #[error(
1466        "no header extension ID was free to use(this means the maximum of 15 extensions have been registered)"
1467    )]
1468    ErrRegisterHeaderExtensionNoFreeID,
1469
1470    /// ErrSimulcastProbeOverflow indicates that too many Simulcast probe streams are in flight and the requested SSRC was ignored
1471    #[error("simulcast probe limit has been reached, new SSRC has been discarded")]
1472    ErrSimulcastProbeOverflow,
1473
1474    #[error("enable detaching by calling webrtc.DetachDataChannels()")]
1475    ErrDetachNotEnabled,
1476    #[error("datachannel not opened yet, try calling Detach from OnOpen")]
1477    ErrDetachBeforeOpened,
1478    #[error("the DTLS transport has not started yet")]
1479    ErrDtlsTransportNotStarted,
1480    #[error("failed extracting keys from DTLS for SRTP")]
1481    ErrDtlsKeyExtractionFailed,
1482    #[error("failed to start SRTP")]
1483    ErrFailedToStartSRTP,
1484    #[error("failed to start SRTCP")]
1485    ErrFailedToStartSRTCP,
1486    #[error("attempted to start DTLSTransport that is not in new state")]
1487    ErrInvalidDTLSStart,
1488    #[error("peer didn't provide certificate via DTLS")]
1489    ErrNoRemoteCertificate,
1490    #[error("identity provider is not implemented")]
1491    ErrIdentityProviderNotImplemented,
1492    #[error("remote certificate does not match any fingerprint")]
1493    ErrNoMatchingCertificateFingerprint,
1494    #[error("unsupported fingerprint algorithm")]
1495    ErrUnsupportedFingerprintAlgorithm,
1496    #[error("ICE connection not started")]
1497    ErrICEConnectionNotStarted,
1498    #[error("unknown candidate type")]
1499    ErrICECandidateTypeUnknown,
1500    #[error("cannot convert ice.CandidateType into webrtc.ICECandidateType, invalid type")]
1501    ErrICEInvalidConvertCandidateType,
1502    #[error("ICEAgent does not exist")]
1503    ErrICEAgentNotExist,
1504    #[error("unable to convert ICE candidates to ICECandidates")]
1505    ErrICECandidatesConversionFailed,
1506    #[error("unknown ICE Role")]
1507    ErrICERoleUnknown,
1508    #[error("unknown protocol")]
1509    ErrICEProtocolUnknown,
1510    #[error("gatherer not started")]
1511    ErrICEGathererNotStarted,
1512    #[error("unknown network type")]
1513    ErrNetworkTypeUnknown,
1514    #[error("new sdp does not match previous offer")]
1515    ErrSDPDoesNotMatchOffer,
1516    #[error("new sdp does not match previous answer")]
1517    ErrSDPDoesNotMatchAnswer,
1518    #[error("provided value is not a valid enum value of type SDPType")]
1519    ErrPeerConnSDPTypeInvalidValue,
1520    #[error("invalid state change op")]
1521    ErrPeerConnStateChangeInvalid,
1522    #[error("unhandled state change op")]
1523    ErrPeerConnStateChangeUnhandled,
1524    #[error("invalid SDP type supplied to SetLocalDescription()")]
1525    ErrPeerConnSDPTypeInvalidValueSetLocalDescription,
1526    #[error("remoteDescription contained media section without mid value")]
1527    ErrPeerConnRemoteDescriptionWithoutMidValue,
1528    #[error("localDescription contained media section without mid value")]
1529    ErrPeerConnLocalDescriptionWithoutMidValue,
1530    #[error("remoteDescription has not been set yet")]
1531    ErrPeerConnRemoteDescriptionNil,
1532    #[error("localDescription has not been set yet")]
1533    ErrPeerConnLocalDescriptionNil,
1534    #[error("single media section has an explicit SSRC")]
1535    ErrPeerConnSingleMediaSectionHasExplicitSSRC,
1536    #[error("could not add transceiver for remote SSRC")]
1537    ErrPeerConnRemoteSSRCAddTransceiver,
1538    #[error("mid RTP Extensions required for Simulcast")]
1539    ErrPeerConnSimulcastMidRTPExtensionRequired,
1540    #[error("stream id RTP Extensions required for Simulcast")]
1541    ErrPeerConnSimulcastStreamIDRTPExtensionRequired,
1542    #[error("incoming SSRC failed Simulcast probing")]
1543    ErrPeerConnSimulcastIncomingSSRCFailed,
1544    #[error("failed collecting stats")]
1545    ErrPeerConnStatsCollectionFailed,
1546    #[error("add_transceiver_from_kind only accepts one RTPTransceiverInit")]
1547    ErrPeerConnAddTransceiverFromKindOnlyAcceptsOne,
1548    #[error("add_transceiver_from_track only accepts one RTPTransceiverInit")]
1549    ErrPeerConnAddTransceiverFromTrackOnlyAcceptsOne,
1550    #[error("add_transceiver_from_kind currently only supports recvonly")]
1551    ErrPeerConnAddTransceiverFromKindSupport,
1552    #[error("add_transceiver_from_track currently only supports sendonly and sendrecv")]
1553    ErrPeerConnAddTransceiverFromTrackSupport,
1554    #[error("TODO set_identity_provider")]
1555    ErrPeerConnSetIdentityProviderNotImplemented,
1556    #[error("write_rtcp failed to open write_stream")]
1557    ErrPeerConnWriteRTCPOpenWriteStream,
1558    #[error("cannot find transceiver with mid")]
1559    ErrPeerConnTransceiverMidNil,
1560    #[error("DTLSTransport must not be nil")]
1561    ErrRTPReceiverDTLSTransportNil,
1562    #[error("Receive has already been called")]
1563    ErrRTPReceiverReceiveAlreadyCalled,
1564    #[error("unable to find stream for Track with SSRC")]
1565    ErrRTPReceiverWithSSRCTrackStreamNotFound,
1566    #[error("no trackStreams found for SSRC")]
1567    ErrRTPReceiverForSSRCTrackStreamNotFound,
1568    #[error("no trackStreams found for RID")]
1569    ErrRTPReceiverForRIDTrackStreamNotFound,
1570    #[error("invalid RTP Receiver transition")]
1571    ErrRTPReceiverStateChangeInvalid,
1572    #[error("Track must not be nil")]
1573    ErrRTPSenderTrackNil,
1574    #[error("RTPSender not existed")]
1575    ErrRTPSenderNotExisted,
1576    #[error("Sender Track has been removed or replaced to nil")]
1577    ErrRTPSenderTrackRemoved,
1578    #[error("Sender cannot add encoding as rid is empty")]
1579    ErrRTPSenderRidNil,
1580    #[error("Sender cannot add encoding as there is no base track")]
1581    ErrRTPSenderNoBaseEncoding,
1582    #[error("Sender cannot add encoding as provided track does not match base track")]
1583    ErrRTPSenderBaseEncodingMismatch,
1584    #[error("Sender cannot encoding due to RID collision")]
1585    ErrRTPSenderRIDCollision,
1586    #[error("Sender does not have track for RID")]
1587    ErrRTPSenderNoTrackForRID,
1588    #[error("RTPReceiver not existed")]
1589    ErrRTPReceiverNotExisted,
1590    #[error("DTLSTransport must not be nil")]
1591    ErrRTPSenderDTLSTransportNil,
1592    #[error("Send has already been called")]
1593    ErrRTPSenderSendAlreadyCalled,
1594    #[error("RTPTransceiver not existed")]
1595    ErrRTPTransceiverNotExisted,
1596    #[error("errRTPSenderTrackNil")]
1597    ErrRTPTransceiverCannotChangeMid,
1598    #[error("invalid state change in RTPTransceiver.setSending")]
1599    ErrRTPTransceiverSetSendingInvalidState,
1600    #[error("unsupported codec type by this transceiver")]
1601    ErrRTPTransceiverCodecUnsupported,
1602    #[error("DTLS not established")]
1603    ErrSCTPTransportDTLS,
1604    #[error("add_transceiver_sdp() called with 0 transceivers")]
1605    ErrSDPZeroTransceivers,
1606    #[error("invalid Media Section. Media + DataChannel both enabled")]
1607    ErrSDPMediaSectionMediaDataChanInvalid,
1608    #[error("invalid Media Section Track Index")]
1609    ErrSDPMediaSectionTrackInvalid,
1610    #[error("set_answering_dtlsrole must DTLSRoleClient or DTLSRoleServer")]
1611    ErrSettingEngineSetAnsweringDTLSRole,
1612    #[error("can't rollback from stable state")]
1613    ErrSignalingStateCannotRollback,
1614    #[error("invalid proposed signaling state transition: {0}")]
1615    ErrSignalingStateProposedTransitionInvalid(String),
1616    #[error("cannot convert to StatsICECandidatePairStateSucceeded invalid ice candidate state")]
1617    ErrStatsICECandidateStateInvalid,
1618    #[error("ICETransport can only be called in ICETransportStateNew")]
1619    ErrICETransportNotInNew,
1620    #[error("bad Certificate PEM format")]
1621    ErrCertificatePEMFormatError,
1622    #[error("SCTP is not established")]
1623    ErrSCTPNotEstablished,
1624
1625    #[error("DataChannel is not opened")]
1626    ErrClosedPipe,
1627    #[error("Interceptor is not bind")]
1628    ErrInterceptorNotBind,
1629    #[error("excessive retries in CreateOffer")]
1630    ErrExcessiveRetries,
1631
1632    #[error("not long enough to be a RTP Packet")]
1633    ErrRTPTooShort,
1634
1635    /// SyntaxIdDirSplit indicates rid-syntax could not be parsed.
1636    #[error("RFC8851 mandates rid-syntax        = %s\"a=rid:\" rid-id SP rid-dir")]
1637    SimulcastRidParseErrorSyntaxIdDirSplit,
1638    /// UnknownDirection indicates rid-dir was not parsed. Should be "send" or "recv".
1639    #[error("RFC8851 mandates rid-dir           = %s\"send\" / %s\"recv\"")]
1640    SimulcastRidParseErrorUnknownDirection,
1641
1642    //SDP
1643    #[error("codec not found")]
1644    CodecNotFound,
1645    #[error("missing whitespace")]
1646    MissingWhitespace,
1647    #[error("missing colon")]
1648    MissingColon,
1649    #[error("payload type not found")]
1650    PayloadTypeNotFound,
1651    #[error("SdpInvalidSyntax: {0}")]
1652    SdpInvalidSyntax(String),
1653    #[error("SdpInvalidValue: {0}")]
1654    SdpInvalidValue(String),
1655    #[error("sdp: empty time_descriptions")]
1656    SdpEmptyTimeDescription,
1657    #[error("parse extmap: {0}")]
1658    ParseExtMap(String),
1659    #[error("{} --> {} <-- {}", .s.substring(0,*.p), .s.substring(*.p, *.p+1), .s.substring(*.p+1, .s.len())
1660    )]
1661    SyntaxError { s: String, p: usize },
1662
1663    //Third Party Error
1664    #[error("{0}")]
1665    Sec1(#[source] sec1::Error),
1666    #[error("{0}")]
1667    P256(#[source] P256Error),
1668    #[error("{0}")]
1669    RcGen(#[from] rcgen::Error),
1670    #[error("invalid PEM: {0}")]
1671    InvalidPEM(String),
1672    #[error("aes gcm: {0}")]
1673    AesGcm(#[from] aes_gcm::Error),
1674    #[error("parse ip: {0}")]
1675    ParseIp(#[from] net::AddrParseError),
1676    #[error("parse int: {0}")]
1677    ParseInt(#[from] ParseIntError),
1678    #[error("{0}")]
1679    Io(#[source] IoError),
1680    #[error("url parse: {0}")]
1681    Url(#[from] url::ParseError),
1682    #[error("utf8: {0}")]
1683    Utf8(#[from] FromUtf8Error),
1684    #[error("{0}")]
1685    Std(#[source] StdError),
1686    #[error("{0}")]
1687    Aes(#[from] aes::cipher::InvalidLength),
1688
1689    //Other Errors
1690    #[error("Other RTCP Err: {0}")]
1691    OtherRtcpErr(String),
1692    #[error("Other RTP Err: {0}")]
1693    OtherRtpErr(String),
1694    #[error("Other SRTP Err: {0}")]
1695    OtherSrtpErr(String),
1696    #[error("Other STUN Err: {0}")]
1697    OtherStunErr(String),
1698    #[error("Other TURN Err: {0}")]
1699    OtherTurnErr(String),
1700    #[error("Other ICE Err: {0}")]
1701    OtherIceErr(String),
1702    #[error("Other DTLS Err: {0}")]
1703    OtherDtlsErr(String),
1704    #[error("Other SCTP Err: {0}")]
1705    OtherSctpErr(String),
1706    #[error("Other DataChannel Err: {0}")]
1707    OtherDataChannelErr(String),
1708    #[error("Other Interceptor Err: {0}")]
1709    OtherInterceptorErr(String),
1710    #[error("Other Media Err: {0}")]
1711    OtherMediaErr(String),
1712    #[error("Other mDNS Err: {0}")]
1713    OtherMdnsErr(String),
1714    #[error("Other SDP Err: {0}")]
1715    OtherSdpErr(String),
1716    #[error("Other PeerConnection Err: {0}")]
1717    OtherPeerConnectionErr(String),
1718    #[error("{0}")]
1719    Other(String),
1720}
1721
1722impl Error {
1723    /// Wraps any `std::error::Error` implementation as [`Error::Std`],
1724    /// preserving the original error and its stack trace.
1725    pub fn from_std<T>(error: T) -> Self
1726    where
1727        T: std::error::Error + Send + Sync + 'static,
1728    {
1729        Error::Std(StdError(Box::new(error)))
1730    }
1731
1732    /// Attempts to downcast an [`Error::Std`] variant to a concrete error type.
1733    ///
1734    /// Returns `None` if this error is not `Error::Std` or if the inner error
1735    /// is not of type `T`.
1736    pub fn downcast_ref<T: std::error::Error + 'static>(&self) -> Option<&T> {
1737        if let Error::Std(s) = self {
1738            return s.0.downcast_ref();
1739        }
1740
1741        None
1742    }
1743}
1744
1745/// Wrapper around [`std::io::Error`] that implements [`PartialEq`].
1746///
1747/// `io::Error` does not implement `PartialEq`, which is required by the
1748/// top-level [`enum@Error`] enum. This newtype delegates equality to
1749/// [`io::ErrorKind`], so two `IoError` values are equal when their kinds match.
1750#[derive(Debug, Error)]
1751#[error("io error: {0}")]
1752pub struct IoError(#[from] pub io::Error);
1753
1754// Workaround for wanting PartialEq for io::Error.
1755impl PartialEq for IoError {
1756    fn eq(&self, other: &Self) -> bool {
1757        self.0.kind() == other.0.kind()
1758    }
1759}
1760
1761impl From<io::Error> for Error {
1762    fn from(e: io::Error) -> Self {
1763        Error::Io(IoError(e))
1764    }
1765}
1766
1767/// An escape hatch to preserve stack traces for errors whose concrete type is unknown.
1768///
1769/// Some traits exported by this crate (e.g. `Conn`, `Listener`) return `Error`.
1770/// When those traits are used in higher-level crates that have their own error
1771/// types, callers are forced to handle foreign errors. `StdError` boxes any
1772/// `std::error::Error` implementation and wraps it in `Error::Std`, preserving
1773/// the original error's message and — where supported — its stack trace.
1774///
1775/// Use [`Error::from_std`] to construct this variant.
1776#[derive(Debug, Error)]
1777#[error("{0}")]
1778pub struct StdError(pub Box<dyn std::error::Error + Send + Sync>);
1779
1780impl PartialEq for StdError {
1781    fn eq(&self, _: &Self) -> bool {
1782        false
1783    }
1784}
1785
1786impl<T> From<std::sync::PoisonError<T>> for Error {
1787    fn from(e: std::sync::PoisonError<T>) -> Self {
1788        Error::PoisonError(e.to_string())
1789    }
1790}
1791
1792impl From<sec1::Error> for Error {
1793    fn from(e: sec1::Error) -> Self {
1794        Error::Sec1(e)
1795    }
1796}
1797
1798/// Wrapper around [`p256::elliptic_curve::Error`] that implements [`PartialEq`].
1799///
1800/// `p256::elliptic_curve::Error` does not implement `PartialEq`, which is
1801/// required by the top-level [`enum@Error`] enum. This newtype always returns
1802/// `false` for equality comparisons, which is the safe conservative choice
1803/// for opaque cryptographic errors.
1804#[derive(Debug, Error)]
1805#[error("{0}")]
1806pub struct P256Error(#[source] p256::elliptic_curve::Error);
1807
1808impl PartialEq for P256Error {
1809    fn eq(&self, _: &Self) -> bool {
1810        false
1811    }
1812}
1813
1814impl From<p256::elliptic_curve::Error> for Error {
1815    fn from(e: p256::elliptic_curve::Error) -> Self {
1816        Error::P256(P256Error(e))
1817    }
1818}
1819
1820impl From<SystemTimeError> for Error {
1821    fn from(e: SystemTimeError) -> Self {
1822        Error::Other(e.to_string())
1823    }
1824}
1825
1826/// Flattens a list of errors into a single [`enum@Error`], joining their messages with newlines.
1827///
1828/// Returns `Ok(())` if `errs` is empty.
1829pub fn flatten_errs(errs: Vec<impl Into<Error>>) -> Result<()> {
1830    if errs.is_empty() {
1831        Ok(())
1832    } else {
1833        let errs_strs: Vec<String> = errs.into_iter().map(|e| e.into().to_string()).collect();
1834        Err(Error::Other(errs_strs.join("\n")))
1835    }
1836}