association.go 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573
  1. package sctp
  2. import (
  3. "bytes"
  4. "context"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "math"
  9. "net"
  10. "sync"
  11. "sync/atomic"
  12. "time"
  13. "github.com/pion/logging"
  14. "github.com/pion/randutil"
  15. )
  16. // Use global random generator to properly seed by crypto grade random.
  17. var globalMathRandomGenerator = randutil.NewMathRandomGenerator() // nolint:gochecknoglobals
  18. // Association errors
  19. var (
  20. ErrChunk = errors.New("abort chunk, with following errors")
  21. ErrShutdownNonEstablished = errors.New("shutdown called in non-established state")
  22. ErrAssociationClosedBeforeConn = errors.New("association closed before connecting")
  23. ErrSilentlyDiscard = errors.New("silently discard")
  24. ErrInitNotStoredToSend = errors.New("the init not stored to send")
  25. ErrCookieEchoNotStoredToSend = errors.New("cookieEcho not stored to send")
  26. ErrSCTPPacketSourcePortZero = errors.New("sctp packet must not have a source port of 0")
  27. ErrSCTPPacketDestinationPortZero = errors.New("sctp packet must not have a destination port of 0")
  28. ErrInitChunkBundled = errors.New("init chunk must not be bundled with any other chunk")
  29. ErrInitChunkVerifyTagNotZero = errors.New("init chunk expects a verification tag of 0 on the packet when out-of-the-blue")
  30. ErrHandleInitState = errors.New("todo: handle Init when in state")
  31. ErrInitAckNoCookie = errors.New("no cookie in InitAck")
  32. ErrInflightQueueTSNPop = errors.New("unable to be popped from inflight queue TSN")
  33. ErrTSNRequestNotExist = errors.New("requested non-existent TSN")
  34. ErrResetPacketInStateNotExist = errors.New("sending reset packet in non-established state")
  35. ErrParamterType = errors.New("unexpected parameter type")
  36. ErrPayloadDataStateNotExist = errors.New("sending payload data in non-established state")
  37. ErrChunkTypeUnhandled = errors.New("unhandled chunk type")
  38. ErrHandshakeInitAck = errors.New("handshake failed (INIT ACK)")
  39. ErrHandshakeCookieEcho = errors.New("handshake failed (COOKIE ECHO)")
  40. )
  41. const (
  42. receiveMTU uint32 = 8192 // MTU for inbound packet (from DTLS)
  43. initialMTU uint32 = 1228 // initial MTU for outgoing packets (to DTLS)
  44. initialRecvBufSize uint32 = 1024 * 1024
  45. commonHeaderSize uint32 = 12
  46. dataChunkHeaderSize uint32 = 16
  47. defaultMaxMessageSize uint32 = 65536
  48. )
  49. // association state enums
  50. const (
  51. closed uint32 = iota
  52. cookieWait
  53. cookieEchoed
  54. established
  55. shutdownAckSent
  56. shutdownPending
  57. shutdownReceived
  58. shutdownSent
  59. )
  60. // retransmission timer IDs
  61. const (
  62. timerT1Init int = iota
  63. timerT1Cookie
  64. timerT2Shutdown
  65. timerT3RTX
  66. timerReconfig
  67. )
  68. // ack mode (for testing)
  69. const (
  70. ackModeNormal int = iota
  71. ackModeNoDelay
  72. ackModeAlwaysDelay
  73. )
  74. // ack transmission state
  75. const (
  76. ackStateIdle int = iota // ack timer is off
  77. ackStateImmediate // will send ack immediately
  78. ackStateDelay // ack timer is on (ack is being delayed)
  79. )
  80. // other constants
  81. const (
  82. acceptChSize = 16
  83. )
  84. func getAssociationStateString(a uint32) string {
  85. switch a {
  86. case closed:
  87. return "Closed"
  88. case cookieWait:
  89. return "CookieWait"
  90. case cookieEchoed:
  91. return "CookieEchoed"
  92. case established:
  93. return "Established"
  94. case shutdownPending:
  95. return "ShutdownPending"
  96. case shutdownSent:
  97. return "ShutdownSent"
  98. case shutdownReceived:
  99. return "ShutdownReceived"
  100. case shutdownAckSent:
  101. return "ShutdownAckSent"
  102. default:
  103. return fmt.Sprintf("Invalid association state %d", a)
  104. }
  105. }
  106. // Association represents an SCTP association
  107. // 13.2. Parameters Necessary per Association (i.e., the TCB)
  108. //
  109. // Peer : Tag value to be sent in every packet and is received
  110. // Verification: in the INIT or INIT ACK chunk.
  111. // Tag :
  112. // State : A state variable indicating what state the association
  113. // : is in, i.e., COOKIE-WAIT, COOKIE-ECHOED, ESTABLISHED,
  114. // : SHUTDOWN-PENDING, SHUTDOWN-SENT, SHUTDOWN-RECEIVED,
  115. // : SHUTDOWN-ACK-SENT.
  116. //
  117. // Note: No "CLOSED" state is illustrated since if a
  118. // association is "CLOSED" its TCB SHOULD be removed.
  119. type Association struct {
  120. bytesReceived uint64
  121. bytesSent uint64
  122. lock sync.RWMutex
  123. netConn net.Conn
  124. peerVerificationTag uint32
  125. myVerificationTag uint32
  126. state uint32
  127. myNextTSN uint32 // nextTSN
  128. peerLastTSN uint32 // lastRcvdTSN
  129. minTSN2MeasureRTT uint32 // for RTT measurement
  130. willSendForwardTSN bool
  131. willRetransmitFast bool
  132. willRetransmitReconfig bool
  133. willSendShutdown bool
  134. willSendShutdownAck bool
  135. willSendShutdownComplete bool
  136. willSendAbort bool
  137. willSendAbortCause errorCause
  138. // Reconfig
  139. myNextRSN uint32
  140. reconfigs map[uint32]*chunkReconfig
  141. reconfigRequests map[uint32]*paramOutgoingResetRequest
  142. // Non-RFC internal data
  143. sourcePort uint16
  144. destinationPort uint16
  145. myMaxNumInboundStreams uint16
  146. myMaxNumOutboundStreams uint16
  147. myCookie *paramStateCookie
  148. payloadQueue *payloadQueue
  149. inflightQueue *payloadQueue
  150. pendingQueue *pendingQueue
  151. controlQueue *controlQueue
  152. mtu uint32
  153. maxPayloadSize uint32 // max DATA chunk payload size
  154. srtt atomic.Value // type float64
  155. cumulativeTSNAckPoint uint32
  156. advancedPeerTSNAckPoint uint32
  157. useForwardTSN bool
  158. // Congestion control parameters
  159. maxReceiveBufferSize uint32
  160. maxMessageSize uint32
  161. cwnd uint32 // my congestion window size
  162. rwnd uint32 // calculated peer's receiver windows size
  163. ssthresh uint32 // slow start threshold
  164. partialBytesAcked uint32
  165. inFastRecovery bool
  166. fastRecoverExitPoint uint32
  167. // RTX & Ack timer
  168. rtoMgr *rtoManager
  169. t1Init *rtxTimer
  170. t1Cookie *rtxTimer
  171. t2Shutdown *rtxTimer
  172. t3RTX *rtxTimer
  173. tReconfig *rtxTimer
  174. ackTimer *ackTimer
  175. // Chunks stored for retransmission
  176. storedInit *chunkInit
  177. storedCookieEcho *chunkCookieEcho
  178. streams map[uint16]*Stream
  179. acceptCh chan *Stream
  180. readLoopCloseCh chan struct{}
  181. awakeWriteLoopCh chan struct{}
  182. closeWriteLoopCh chan struct{}
  183. handshakeCompletedCh chan error
  184. closeWriteLoopOnce sync.Once
  185. // local error
  186. silentError error
  187. ackState int
  188. ackMode int // for testing
  189. // stats
  190. stats *associationStats
  191. // per inbound packet context
  192. delayedAckTriggered bool
  193. immediateAckTriggered bool
  194. name string
  195. log logging.LeveledLogger
  196. }
  197. // Config collects the arguments to createAssociation construction into
  198. // a single structure
  199. type Config struct {
  200. NetConn net.Conn
  201. MaxReceiveBufferSize uint32
  202. MaxMessageSize uint32
  203. LoggerFactory logging.LoggerFactory
  204. }
  205. // Server accepts a SCTP stream over a conn
  206. func Server(config Config) (*Association, error) {
  207. a := createAssociation(config)
  208. a.init(false)
  209. select {
  210. case err := <-a.handshakeCompletedCh:
  211. if err != nil {
  212. return nil, err
  213. }
  214. return a, nil
  215. case <-a.readLoopCloseCh:
  216. return nil, ErrAssociationClosedBeforeConn
  217. }
  218. }
  219. // Client opens a SCTP stream over a conn
  220. func Client(config Config) (*Association, error) {
  221. a := createAssociation(config)
  222. a.init(true)
  223. select {
  224. case err := <-a.handshakeCompletedCh:
  225. if err != nil {
  226. return nil, err
  227. }
  228. return a, nil
  229. case <-a.readLoopCloseCh:
  230. return nil, ErrAssociationClosedBeforeConn
  231. }
  232. }
  233. func createAssociation(config Config) *Association {
  234. var maxReceiveBufferSize uint32
  235. if config.MaxReceiveBufferSize == 0 {
  236. maxReceiveBufferSize = initialRecvBufSize
  237. } else {
  238. maxReceiveBufferSize = config.MaxReceiveBufferSize
  239. }
  240. var maxMessageSize uint32
  241. if config.MaxMessageSize == 0 {
  242. maxMessageSize = defaultMaxMessageSize
  243. } else {
  244. maxMessageSize = config.MaxMessageSize
  245. }
  246. tsn := globalMathRandomGenerator.Uint32()
  247. a := &Association{
  248. netConn: config.NetConn,
  249. maxReceiveBufferSize: maxReceiveBufferSize,
  250. maxMessageSize: maxMessageSize,
  251. myMaxNumOutboundStreams: math.MaxUint16,
  252. myMaxNumInboundStreams: math.MaxUint16,
  253. payloadQueue: newPayloadQueue(),
  254. inflightQueue: newPayloadQueue(),
  255. pendingQueue: newPendingQueue(),
  256. controlQueue: newControlQueue(),
  257. mtu: initialMTU,
  258. maxPayloadSize: initialMTU - (commonHeaderSize + dataChunkHeaderSize),
  259. myVerificationTag: globalMathRandomGenerator.Uint32(),
  260. myNextTSN: tsn,
  261. myNextRSN: tsn,
  262. minTSN2MeasureRTT: tsn,
  263. state: closed,
  264. rtoMgr: newRTOManager(),
  265. streams: map[uint16]*Stream{},
  266. reconfigs: map[uint32]*chunkReconfig{},
  267. reconfigRequests: map[uint32]*paramOutgoingResetRequest{},
  268. acceptCh: make(chan *Stream, acceptChSize),
  269. readLoopCloseCh: make(chan struct{}),
  270. awakeWriteLoopCh: make(chan struct{}, 1),
  271. closeWriteLoopCh: make(chan struct{}),
  272. handshakeCompletedCh: make(chan error),
  273. cumulativeTSNAckPoint: tsn - 1,
  274. advancedPeerTSNAckPoint: tsn - 1,
  275. silentError: ErrSilentlyDiscard,
  276. stats: &associationStats{},
  277. log: config.LoggerFactory.NewLogger("sctp"),
  278. }
  279. a.name = fmt.Sprintf("%p", a)
  280. // RFC 4690 Sec 7.2.1
  281. // o The initial cwnd before DATA transmission or after a sufficiently
  282. // long idle period MUST be set to min(4*MTU, max (2*MTU, 4380
  283. // bytes)).
  284. a.cwnd = min32(4*a.mtu, max32(2*a.mtu, 4380))
  285. a.log.Tracef("[%s] updated cwnd=%d ssthresh=%d inflight=%d (INI)",
  286. a.name, a.cwnd, a.ssthresh, a.inflightQueue.getNumBytes())
  287. a.srtt.Store(float64(0))
  288. a.t1Init = newRTXTimer(timerT1Init, a, maxInitRetrans)
  289. a.t1Cookie = newRTXTimer(timerT1Cookie, a, maxInitRetrans)
  290. a.t2Shutdown = newRTXTimer(timerT2Shutdown, a, noMaxRetrans) // retransmit forever
  291. a.t3RTX = newRTXTimer(timerT3RTX, a, noMaxRetrans) // retransmit forever
  292. a.tReconfig = newRTXTimer(timerReconfig, a, noMaxRetrans) // retransmit forever
  293. a.ackTimer = newAckTimer(a)
  294. return a
  295. }
  296. func (a *Association) init(isClient bool) {
  297. a.lock.Lock()
  298. defer a.lock.Unlock()
  299. go a.readLoop()
  300. go a.writeLoop()
  301. if isClient {
  302. a.setState(cookieWait)
  303. init := &chunkInit{}
  304. init.initialTSN = a.myNextTSN
  305. init.numOutboundStreams = a.myMaxNumOutboundStreams
  306. init.numInboundStreams = a.myMaxNumInboundStreams
  307. init.initiateTag = a.myVerificationTag
  308. init.advertisedReceiverWindowCredit = a.maxReceiveBufferSize
  309. setSupportedExtensions(&init.chunkInitCommon)
  310. a.storedInit = init
  311. err := a.sendInit()
  312. if err != nil {
  313. a.log.Errorf("[%s] failed to send init: %s", a.name, err.Error())
  314. }
  315. a.t1Init.start(a.rtoMgr.getRTO())
  316. }
  317. }
  318. // caller must hold a.lock
  319. func (a *Association) sendInit() error {
  320. a.log.Debugf("[%s] sending INIT", a.name)
  321. if a.storedInit == nil {
  322. return ErrInitNotStoredToSend
  323. }
  324. outbound := &packet{}
  325. outbound.verificationTag = a.peerVerificationTag
  326. a.sourcePort = 5000 // Spec??
  327. a.destinationPort = 5000 // Spec??
  328. outbound.sourcePort = a.sourcePort
  329. outbound.destinationPort = a.destinationPort
  330. outbound.chunks = []chunk{a.storedInit}
  331. a.controlQueue.push(outbound)
  332. a.awakeWriteLoop()
  333. return nil
  334. }
  335. // caller must hold a.lock
  336. func (a *Association) sendCookieEcho() error {
  337. if a.storedCookieEcho == nil {
  338. return ErrCookieEchoNotStoredToSend
  339. }
  340. a.log.Debugf("[%s] sending COOKIE-ECHO", a.name)
  341. outbound := &packet{}
  342. outbound.verificationTag = a.peerVerificationTag
  343. outbound.sourcePort = a.sourcePort
  344. outbound.destinationPort = a.destinationPort
  345. outbound.chunks = []chunk{a.storedCookieEcho}
  346. a.controlQueue.push(outbound)
  347. a.awakeWriteLoop()
  348. return nil
  349. }
  350. // Shutdown initiates the shutdown sequence. The method blocks until the
  351. // shutdown sequence is completed and the connection is closed, or until the
  352. // passed context is done, in which case the context's error is returned.
  353. func (a *Association) Shutdown(ctx context.Context) error {
  354. a.log.Debugf("[%s] closing association..", a.name)
  355. state := a.getState()
  356. if state != established {
  357. return fmt.Errorf("%w: shutdown %s", ErrShutdownNonEstablished, a.name)
  358. }
  359. // Attempt a graceful shutdown.
  360. a.setState(shutdownPending)
  361. a.lock.Lock()
  362. if a.inflightQueue.size() == 0 {
  363. // No more outstanding, send shutdown.
  364. a.willSendShutdown = true
  365. a.awakeWriteLoop()
  366. a.setState(shutdownSent)
  367. }
  368. a.lock.Unlock()
  369. select {
  370. case <-a.closeWriteLoopCh:
  371. return nil
  372. case <-ctx.Done():
  373. return ctx.Err()
  374. }
  375. }
  376. // Close ends the SCTP Association and cleans up any state
  377. func (a *Association) Close() error {
  378. a.log.Debugf("[%s] closing association..", a.name)
  379. err := a.close()
  380. // Wait for readLoop to end
  381. <-a.readLoopCloseCh
  382. a.log.Debugf("[%s] association closed", a.name)
  383. a.log.Debugf("[%s] stats nDATAs (in) : %d", a.name, a.stats.getNumDATAs())
  384. a.log.Debugf("[%s] stats nSACKs (in) : %d", a.name, a.stats.getNumSACKs())
  385. a.log.Debugf("[%s] stats nT3Timeouts : %d", a.name, a.stats.getNumT3Timeouts())
  386. a.log.Debugf("[%s] stats nAckTimeouts: %d", a.name, a.stats.getNumAckTimeouts())
  387. a.log.Debugf("[%s] stats nFastRetrans: %d", a.name, a.stats.getNumFastRetrans())
  388. return err
  389. }
  390. func (a *Association) close() error {
  391. a.log.Debugf("[%s] closing association..", a.name)
  392. a.setState(closed)
  393. err := a.netConn.Close()
  394. a.closeAllTimers()
  395. // awake writeLoop to exit
  396. a.closeWriteLoopOnce.Do(func() { close(a.closeWriteLoopCh) })
  397. return err
  398. }
  399. // Abort sends the abort packet with user initiated abort and immediately
  400. // closes the connection.
  401. func (a *Association) Abort(reason string) {
  402. a.log.Debugf("[%s] aborting association: %s", a.name, reason)
  403. a.lock.Lock()
  404. a.willSendAbort = true
  405. a.willSendAbortCause = &errorCauseUserInitiatedAbort{
  406. upperLayerAbortReason: []byte(reason),
  407. }
  408. a.lock.Unlock()
  409. a.awakeWriteLoop()
  410. // Wait for readLoop to end
  411. <-a.readLoopCloseCh
  412. }
  413. func (a *Association) closeAllTimers() {
  414. // Close all retransmission & ack timers
  415. a.t1Init.close()
  416. a.t1Cookie.close()
  417. a.t2Shutdown.close()
  418. a.t3RTX.close()
  419. a.tReconfig.close()
  420. a.ackTimer.close()
  421. }
  422. func (a *Association) readLoop() {
  423. var closeErr error
  424. defer func() {
  425. // also stop writeLoop, otherwise writeLoop can be leaked
  426. // if connection is lost when there is no writing packet.
  427. a.closeWriteLoopOnce.Do(func() { close(a.closeWriteLoopCh) })
  428. a.lock.Lock()
  429. for _, s := range a.streams {
  430. a.unregisterStream(s, closeErr)
  431. }
  432. a.lock.Unlock()
  433. close(a.acceptCh)
  434. close(a.readLoopCloseCh)
  435. a.log.Debugf("[%s] association closed", a.name)
  436. a.log.Debugf("[%s] stats nDATAs (in) : %d", a.name, a.stats.getNumDATAs())
  437. a.log.Debugf("[%s] stats nSACKs (in) : %d", a.name, a.stats.getNumSACKs())
  438. a.log.Debugf("[%s] stats nT3Timeouts : %d", a.name, a.stats.getNumT3Timeouts())
  439. a.log.Debugf("[%s] stats nAckTimeouts: %d", a.name, a.stats.getNumAckTimeouts())
  440. a.log.Debugf("[%s] stats nFastRetrans: %d", a.name, a.stats.getNumFastRetrans())
  441. }()
  442. a.log.Debugf("[%s] readLoop entered", a.name)
  443. buffer := make([]byte, receiveMTU)
  444. for {
  445. n, err := a.netConn.Read(buffer)
  446. if err != nil {
  447. closeErr = err
  448. break
  449. }
  450. // Make a buffer sized to what we read, then copy the data we
  451. // read from the underlying transport. We do this because the
  452. // user data is passed to the reassembly queue without
  453. // copying.
  454. inbound := make([]byte, n)
  455. copy(inbound, buffer[:n])
  456. atomic.AddUint64(&a.bytesReceived, uint64(n))
  457. if err = a.handleInbound(inbound); err != nil {
  458. closeErr = err
  459. break
  460. }
  461. }
  462. a.log.Debugf("[%s] readLoop exited %s", a.name, closeErr)
  463. }
  464. func (a *Association) writeLoop() {
  465. a.log.Debugf("[%s] writeLoop entered", a.name)
  466. defer a.log.Debugf("[%s] writeLoop exited", a.name)
  467. loop:
  468. for {
  469. rawPackets, ok := a.gatherOutbound()
  470. for _, raw := range rawPackets {
  471. _, err := a.netConn.Write(raw)
  472. if err != nil {
  473. if !errors.Is(err, io.EOF) {
  474. a.log.Warnf("[%s] failed to write packets on netConn: %v", a.name, err)
  475. }
  476. a.log.Debugf("[%s] writeLoop ended", a.name)
  477. break loop
  478. }
  479. atomic.AddUint64(&a.bytesSent, uint64(len(raw)))
  480. }
  481. if !ok {
  482. if err := a.close(); err != nil {
  483. a.log.Warnf("[%s] failed to close association: %v", a.name, err)
  484. }
  485. return
  486. }
  487. select {
  488. case <-a.awakeWriteLoopCh:
  489. case <-a.closeWriteLoopCh:
  490. break loop
  491. }
  492. }
  493. a.setState(closed)
  494. a.closeAllTimers()
  495. }
  496. func (a *Association) awakeWriteLoop() {
  497. select {
  498. case a.awakeWriteLoopCh <- struct{}{}:
  499. default:
  500. }
  501. }
  502. // unregisterStream un-registers a stream from the association
  503. // The caller should hold the association write lock.
  504. func (a *Association) unregisterStream(s *Stream, err error) {
  505. s.lock.Lock()
  506. defer s.lock.Unlock()
  507. delete(a.streams, s.streamIdentifier)
  508. s.readErr = err
  509. s.readNotifier.Broadcast()
  510. }
  511. // handleInbound parses incoming raw packets
  512. func (a *Association) handleInbound(raw []byte) error {
  513. p := &packet{}
  514. if err := p.unmarshal(raw); err != nil {
  515. a.log.Warnf("[%s] unable to parse SCTP packet %s", a.name, err)
  516. return nil
  517. }
  518. if err := checkPacket(p); err != nil {
  519. a.log.Warnf("[%s] failed validating packet %s", a.name, err)
  520. return nil
  521. }
  522. a.handleChunkStart()
  523. for _, c := range p.chunks {
  524. if err := a.handleChunk(p, c); err != nil {
  525. return err
  526. }
  527. }
  528. a.handleChunkEnd()
  529. return nil
  530. }
  531. // The caller should hold the lock
  532. func (a *Association) gatherDataPacketsToRetransmit(rawPackets [][]byte) [][]byte {
  533. for _, p := range a.getDataPacketsToRetransmit() {
  534. raw, err := p.marshal()
  535. if err != nil {
  536. a.log.Warnf("[%s] failed to serialize a DATA packet to be retransmitted", a.name)
  537. continue
  538. }
  539. rawPackets = append(rawPackets, raw)
  540. }
  541. return rawPackets
  542. }
  543. // The caller should hold the lock
  544. func (a *Association) gatherOutboundDataAndReconfigPackets(rawPackets [][]byte) [][]byte {
  545. // Pop unsent data chunks from the pending queue to send as much as
  546. // cwnd and rwnd allow.
  547. chunks, sisToReset := a.popPendingDataChunksToSend()
  548. if len(chunks) > 0 {
  549. // Start timer. (noop if already started)
  550. a.log.Tracef("[%s] T3-rtx timer start (pt1)", a.name)
  551. a.t3RTX.start(a.rtoMgr.getRTO())
  552. for _, p := range a.bundleDataChunksIntoPackets(chunks) {
  553. raw, err := p.marshal()
  554. if err != nil {
  555. a.log.Warnf("[%s] failed to serialize a DATA packet", a.name)
  556. continue
  557. }
  558. rawPackets = append(rawPackets, raw)
  559. }
  560. }
  561. if len(sisToReset) > 0 || a.willRetransmitReconfig {
  562. if a.willRetransmitReconfig {
  563. a.willRetransmitReconfig = false
  564. a.log.Debugf("[%s] retransmit %d RECONFIG chunk(s)", a.name, len(a.reconfigs))
  565. for _, c := range a.reconfigs {
  566. p := a.createPacket([]chunk{c})
  567. raw, err := p.marshal()
  568. if err != nil {
  569. a.log.Warnf("[%s] failed to serialize a RECONFIG packet to be retransmitted", a.name)
  570. } else {
  571. rawPackets = append(rawPackets, raw)
  572. }
  573. }
  574. }
  575. if len(sisToReset) > 0 {
  576. rsn := a.generateNextRSN()
  577. tsn := a.myNextTSN - 1
  578. c := &chunkReconfig{
  579. paramA: &paramOutgoingResetRequest{
  580. reconfigRequestSequenceNumber: rsn,
  581. senderLastTSN: tsn,
  582. streamIdentifiers: sisToReset,
  583. },
  584. }
  585. a.reconfigs[rsn] = c // store in the map for retransmission
  586. a.log.Debugf("[%s] sending RECONFIG: rsn=%d tsn=%d streams=%v",
  587. a.name, rsn, a.myNextTSN-1, sisToReset)
  588. p := a.createPacket([]chunk{c})
  589. raw, err := p.marshal()
  590. if err != nil {
  591. a.log.Warnf("[%s] failed to serialize a RECONFIG packet to be transmitted", a.name)
  592. } else {
  593. rawPackets = append(rawPackets, raw)
  594. }
  595. }
  596. if len(a.reconfigs) > 0 {
  597. a.tReconfig.start(a.rtoMgr.getRTO())
  598. }
  599. }
  600. return rawPackets
  601. }
  602. // The caller should hold the lock
  603. func (a *Association) gatherOutboundFastRetransmissionPackets(rawPackets [][]byte) [][]byte {
  604. if a.willRetransmitFast {
  605. a.willRetransmitFast = false
  606. toFastRetrans := []chunk{}
  607. fastRetransSize := commonHeaderSize
  608. for i := 0; ; i++ {
  609. c, ok := a.inflightQueue.get(a.cumulativeTSNAckPoint + uint32(i) + 1)
  610. if !ok {
  611. break // end of pending data
  612. }
  613. if c.acked || c.abandoned() {
  614. continue
  615. }
  616. if c.nSent > 1 || c.missIndicator < 3 {
  617. continue
  618. }
  619. // RFC 4960 Sec 7.2.4 Fast Retransmit on Gap Reports
  620. // 3) Determine how many of the earliest (i.e., lowest TSN) DATA chunks
  621. // marked for retransmission will fit into a single packet, subject
  622. // to constraint of the path MTU of the destination transport
  623. // address to which the packet is being sent. Call this value K.
  624. // Retransmit those K DATA chunks in a single packet. When a Fast
  625. // Retransmit is being performed, the sender SHOULD ignore the value
  626. // of cwnd and SHOULD NOT delay retransmission for this single
  627. // packet.
  628. dataChunkSize := dataChunkHeaderSize + uint32(len(c.userData))
  629. if a.mtu < fastRetransSize+dataChunkSize {
  630. break
  631. }
  632. fastRetransSize += dataChunkSize
  633. a.stats.incFastRetrans()
  634. c.nSent++
  635. a.checkPartialReliabilityStatus(c)
  636. toFastRetrans = append(toFastRetrans, c)
  637. a.log.Tracef("[%s] fast-retransmit: tsn=%d sent=%d htna=%d",
  638. a.name, c.tsn, c.nSent, a.fastRecoverExitPoint)
  639. }
  640. if len(toFastRetrans) > 0 {
  641. raw, err := a.createPacket(toFastRetrans).marshal()
  642. if err != nil {
  643. a.log.Warnf("[%s] failed to serialize a DATA packet to be fast-retransmitted", a.name)
  644. } else {
  645. rawPackets = append(rawPackets, raw)
  646. }
  647. }
  648. }
  649. return rawPackets
  650. }
  651. // The caller should hold the lock
  652. func (a *Association) gatherOutboundSackPackets(rawPackets [][]byte) [][]byte {
  653. if a.ackState == ackStateImmediate {
  654. a.ackState = ackStateIdle
  655. sack := a.createSelectiveAckChunk()
  656. a.log.Debugf("[%s] sending SACK: %s", a.name, sack)
  657. raw, err := a.createPacket([]chunk{sack}).marshal()
  658. if err != nil {
  659. a.log.Warnf("[%s] failed to serialize a SACK packet", a.name)
  660. } else {
  661. rawPackets = append(rawPackets, raw)
  662. }
  663. }
  664. return rawPackets
  665. }
  666. // The caller should hold the lock
  667. func (a *Association) gatherOutboundForwardTSNPackets(rawPackets [][]byte) [][]byte {
  668. if a.willSendForwardTSN {
  669. a.willSendForwardTSN = false
  670. if sna32GT(a.advancedPeerTSNAckPoint, a.cumulativeTSNAckPoint) {
  671. fwdtsn := a.createForwardTSN()
  672. raw, err := a.createPacket([]chunk{fwdtsn}).marshal()
  673. if err != nil {
  674. a.log.Warnf("[%s] failed to serialize a Forward TSN packet", a.name)
  675. } else {
  676. rawPackets = append(rawPackets, raw)
  677. }
  678. }
  679. }
  680. return rawPackets
  681. }
  682. func (a *Association) gatherOutboundShutdownPackets(rawPackets [][]byte) ([][]byte, bool) {
  683. ok := true
  684. switch {
  685. case a.willSendShutdown:
  686. a.willSendShutdown = false
  687. shutdown := &chunkShutdown{
  688. cumulativeTSNAck: a.cumulativeTSNAckPoint,
  689. }
  690. raw, err := a.createPacket([]chunk{shutdown}).marshal()
  691. if err != nil {
  692. a.log.Warnf("[%s] failed to serialize a Shutdown packet", a.name)
  693. } else {
  694. a.t2Shutdown.start(a.rtoMgr.getRTO())
  695. rawPackets = append(rawPackets, raw)
  696. }
  697. case a.willSendShutdownAck:
  698. a.willSendShutdownAck = false
  699. shutdownAck := &chunkShutdownAck{}
  700. raw, err := a.createPacket([]chunk{shutdownAck}).marshal()
  701. if err != nil {
  702. a.log.Warnf("[%s] failed to serialize a ShutdownAck packet", a.name)
  703. } else {
  704. a.t2Shutdown.start(a.rtoMgr.getRTO())
  705. rawPackets = append(rawPackets, raw)
  706. }
  707. case a.willSendShutdownComplete:
  708. a.willSendShutdownComplete = false
  709. shutdownComplete := &chunkShutdownComplete{}
  710. raw, err := a.createPacket([]chunk{shutdownComplete}).marshal()
  711. if err != nil {
  712. a.log.Warnf("[%s] failed to serialize a ShutdownComplete packet", a.name)
  713. } else {
  714. rawPackets = append(rawPackets, raw)
  715. ok = false
  716. }
  717. }
  718. return rawPackets, ok
  719. }
  720. func (a *Association) gatherAbortPacket() ([]byte, error) {
  721. cause := a.willSendAbortCause
  722. a.willSendAbort = false
  723. a.willSendAbortCause = nil
  724. abort := &chunkAbort{}
  725. if cause != nil {
  726. abort.errorCauses = []errorCause{cause}
  727. }
  728. raw, err := a.createPacket([]chunk{abort}).marshal()
  729. return raw, err
  730. }
  731. // gatherOutbound gathers outgoing packets. The returned bool value set to
  732. // false means the association should be closed down after the final send.
  733. func (a *Association) gatherOutbound() ([][]byte, bool) {
  734. a.lock.Lock()
  735. defer a.lock.Unlock()
  736. if a.willSendAbort {
  737. pkt, err := a.gatherAbortPacket()
  738. if err != nil {
  739. a.log.Warnf("[%s] failed to serialize an abort packet", a.name)
  740. return nil, false
  741. }
  742. return [][]byte{pkt}, false
  743. }
  744. rawPackets := [][]byte{}
  745. if a.controlQueue.size() > 0 {
  746. for _, p := range a.controlQueue.popAll() {
  747. raw, err := p.marshal()
  748. if err != nil {
  749. a.log.Warnf("[%s] failed to serialize a control packet", a.name)
  750. continue
  751. }
  752. rawPackets = append(rawPackets, raw)
  753. }
  754. }
  755. state := a.getState()
  756. ok := true
  757. switch state {
  758. case established:
  759. rawPackets = a.gatherDataPacketsToRetransmit(rawPackets)
  760. rawPackets = a.gatherOutboundDataAndReconfigPackets(rawPackets)
  761. rawPackets = a.gatherOutboundFastRetransmissionPackets(rawPackets)
  762. rawPackets = a.gatherOutboundSackPackets(rawPackets)
  763. rawPackets = a.gatherOutboundForwardTSNPackets(rawPackets)
  764. case shutdownPending, shutdownSent, shutdownReceived:
  765. rawPackets = a.gatherDataPacketsToRetransmit(rawPackets)
  766. rawPackets = a.gatherOutboundFastRetransmissionPackets(rawPackets)
  767. rawPackets = a.gatherOutboundSackPackets(rawPackets)
  768. rawPackets, ok = a.gatherOutboundShutdownPackets(rawPackets)
  769. case shutdownAckSent:
  770. rawPackets, ok = a.gatherOutboundShutdownPackets(rawPackets)
  771. }
  772. return rawPackets, ok
  773. }
  774. func checkPacket(p *packet) error {
  775. // All packets must adhere to these rules
  776. // This is the SCTP sender's port number. It can be used by the
  777. // receiver in combination with the source IP address, the SCTP
  778. // destination port, and possibly the destination IP address to
  779. // identify the association to which this packet belongs. The port
  780. // number 0 MUST NOT be used.
  781. if p.sourcePort == 0 {
  782. return ErrSCTPPacketSourcePortZero
  783. }
  784. // This is the SCTP port number to which this packet is destined.
  785. // The receiving host will use this port number to de-multiplex the
  786. // SCTP packet to the correct receiving endpoint/application. The
  787. // port number 0 MUST NOT be used.
  788. if p.destinationPort == 0 {
  789. return ErrSCTPPacketDestinationPortZero
  790. }
  791. // Check values on the packet that are specific to a particular chunk type
  792. for _, c := range p.chunks {
  793. switch c.(type) { // nolint:gocritic
  794. case *chunkInit:
  795. // An INIT or INIT ACK chunk MUST NOT be bundled with any other chunk.
  796. // They MUST be the only chunks present in the SCTP packets that carry
  797. // them.
  798. if len(p.chunks) != 1 {
  799. return ErrInitChunkBundled
  800. }
  801. // A packet containing an INIT chunk MUST have a zero Verification
  802. // Tag.
  803. if p.verificationTag != 0 {
  804. return ErrInitChunkVerifyTagNotZero
  805. }
  806. }
  807. }
  808. return nil
  809. }
  810. func min16(a, b uint16) uint16 {
  811. if a < b {
  812. return a
  813. }
  814. return b
  815. }
  816. func max32(a, b uint32) uint32 {
  817. if a > b {
  818. return a
  819. }
  820. return b
  821. }
  822. func min32(a, b uint32) uint32 {
  823. if a < b {
  824. return a
  825. }
  826. return b
  827. }
  828. // setState atomically sets the state of the Association.
  829. // The caller should hold the lock.
  830. func (a *Association) setState(newState uint32) {
  831. oldState := atomic.SwapUint32(&a.state, newState)
  832. if newState != oldState {
  833. a.log.Debugf("[%s] state change: '%s' => '%s'",
  834. a.name,
  835. getAssociationStateString(oldState),
  836. getAssociationStateString(newState))
  837. }
  838. }
  839. // getState atomically returns the state of the Association.
  840. func (a *Association) getState() uint32 {
  841. return atomic.LoadUint32(&a.state)
  842. }
  843. // BytesSent returns the number of bytes sent
  844. func (a *Association) BytesSent() uint64 {
  845. return atomic.LoadUint64(&a.bytesSent)
  846. }
  847. // BytesReceived returns the number of bytes received
  848. func (a *Association) BytesReceived() uint64 {
  849. return atomic.LoadUint64(&a.bytesReceived)
  850. }
  851. // MTU returns the association's current MTU
  852. func (a *Association) MTU() uint32 {
  853. return atomic.LoadUint32(&a.mtu)
  854. }
  855. // CWND returns the association's current congestion window (cwnd)
  856. func (a *Association) CWND() uint32 {
  857. return atomic.LoadUint32(&a.cwnd)
  858. }
  859. // RWND returns the association's current receiver window (rwnd)
  860. func (a *Association) RWND() uint32 {
  861. return atomic.LoadUint32(&a.rwnd)
  862. }
  863. // SRTT returns the latest smoothed round-trip time (srrt)
  864. func (a *Association) SRTT() float64 {
  865. return a.srtt.Load().(float64) //nolint:forcetypeassert
  866. }
  867. func setSupportedExtensions(init *chunkInitCommon) {
  868. // nolint:godox
  869. // TODO RFC5061 https://tools.ietf.org/html/rfc6525#section-5.2
  870. // An implementation supporting this (Supported Extensions Parameter)
  871. // extension MUST list the ASCONF, the ASCONF-ACK, and the AUTH chunks
  872. // in its INIT and INIT-ACK parameters.
  873. init.params = append(init.params, &paramSupportedExtensions{
  874. ChunkTypes: []chunkType{ctReconfig, ctForwardTSN},
  875. })
  876. }
  877. // The caller should hold the lock.
  878. func (a *Association) handleInit(p *packet, i *chunkInit) ([]*packet, error) {
  879. state := a.getState()
  880. a.log.Debugf("[%s] chunkInit received in state '%s'", a.name, getAssociationStateString(state))
  881. // https://tools.ietf.org/html/rfc4960#section-5.2.1
  882. // Upon receipt of an INIT in the COOKIE-WAIT state, an endpoint MUST
  883. // respond with an INIT ACK using the same parameters it sent in its
  884. // original INIT chunk (including its Initiate Tag, unchanged). When
  885. // responding, the endpoint MUST send the INIT ACK back to the same
  886. // address that the original INIT (sent by this endpoint) was sent.
  887. if state != closed && state != cookieWait && state != cookieEchoed {
  888. // 5.2.2. Unexpected INIT in States Other than CLOSED, COOKIE-ECHOED,
  889. // COOKIE-WAIT, and SHUTDOWN-ACK-SENT
  890. return nil, fmt.Errorf("%w: %s", ErrHandleInitState, getAssociationStateString(state))
  891. }
  892. // Should we be setting any of these permanently until we've ACKed further?
  893. a.myMaxNumInboundStreams = min16(i.numInboundStreams, a.myMaxNumInboundStreams)
  894. a.myMaxNumOutboundStreams = min16(i.numOutboundStreams, a.myMaxNumOutboundStreams)
  895. a.peerVerificationTag = i.initiateTag
  896. a.sourcePort = p.destinationPort
  897. a.destinationPort = p.sourcePort
  898. // 13.2 This is the last TSN received in sequence. This value
  899. // is set initially by taking the peer's initial TSN,
  900. // received in the INIT or INIT ACK chunk, and
  901. // subtracting one from it.
  902. a.peerLastTSN = i.initialTSN - 1
  903. for _, param := range i.params {
  904. switch v := param.(type) { // nolint:gocritic
  905. case *paramSupportedExtensions:
  906. for _, t := range v.ChunkTypes {
  907. if t == ctForwardTSN {
  908. a.log.Debugf("[%s] use ForwardTSN (on init)", a.name)
  909. a.useForwardTSN = true
  910. }
  911. }
  912. }
  913. }
  914. if !a.useForwardTSN {
  915. a.log.Warnf("[%s] not using ForwardTSN (on init)", a.name)
  916. }
  917. outbound := &packet{}
  918. outbound.verificationTag = a.peerVerificationTag
  919. outbound.sourcePort = a.sourcePort
  920. outbound.destinationPort = a.destinationPort
  921. initAck := &chunkInitAck{}
  922. initAck.initialTSN = a.myNextTSN
  923. initAck.numOutboundStreams = a.myMaxNumOutboundStreams
  924. initAck.numInboundStreams = a.myMaxNumInboundStreams
  925. initAck.initiateTag = a.myVerificationTag
  926. initAck.advertisedReceiverWindowCredit = a.maxReceiveBufferSize
  927. if a.myCookie == nil {
  928. var err error
  929. if a.myCookie, err = newRandomStateCookie(); err != nil {
  930. return nil, err
  931. }
  932. }
  933. initAck.params = []param{a.myCookie}
  934. setSupportedExtensions(&initAck.chunkInitCommon)
  935. outbound.chunks = []chunk{initAck}
  936. return pack(outbound), nil
  937. }
  938. // The caller should hold the lock.
  939. func (a *Association) handleInitAck(p *packet, i *chunkInitAck) error {
  940. state := a.getState()
  941. a.log.Debugf("[%s] chunkInitAck received in state '%s'", a.name, getAssociationStateString(state))
  942. if state != cookieWait {
  943. // RFC 4960
  944. // 5.2.3. Unexpected INIT ACK
  945. // If an INIT ACK is received by an endpoint in any state other than the
  946. // COOKIE-WAIT state, the endpoint should discard the INIT ACK chunk.
  947. // An unexpected INIT ACK usually indicates the processing of an old or
  948. // duplicated INIT chunk.
  949. return nil
  950. }
  951. a.myMaxNumInboundStreams = min16(i.numInboundStreams, a.myMaxNumInboundStreams)
  952. a.myMaxNumOutboundStreams = min16(i.numOutboundStreams, a.myMaxNumOutboundStreams)
  953. a.peerVerificationTag = i.initiateTag
  954. a.peerLastTSN = i.initialTSN - 1
  955. if a.sourcePort != p.destinationPort ||
  956. a.destinationPort != p.sourcePort {
  957. a.log.Warnf("[%s] handleInitAck: port mismatch", a.name)
  958. return nil
  959. }
  960. a.rwnd = i.advertisedReceiverWindowCredit
  961. a.log.Debugf("[%s] initial rwnd=%d", a.name, a.rwnd)
  962. // RFC 4690 Sec 7.2.1
  963. // o The initial value of ssthresh MAY be arbitrarily high (for
  964. // example, implementations MAY use the size of the receiver
  965. // advertised window).
  966. a.ssthresh = a.rwnd
  967. a.log.Tracef("[%s] updated cwnd=%d ssthresh=%d inflight=%d (INI)",
  968. a.name, a.cwnd, a.ssthresh, a.inflightQueue.getNumBytes())
  969. a.t1Init.stop()
  970. a.storedInit = nil
  971. var cookieParam *paramStateCookie
  972. for _, param := range i.params {
  973. switch v := param.(type) {
  974. case *paramStateCookie:
  975. cookieParam = v
  976. case *paramSupportedExtensions:
  977. for _, t := range v.ChunkTypes {
  978. if t == ctForwardTSN {
  979. a.log.Debugf("[%s] use ForwardTSN (on initAck)", a.name)
  980. a.useForwardTSN = true
  981. }
  982. }
  983. }
  984. }
  985. if !a.useForwardTSN {
  986. a.log.Warnf("[%s] not using ForwardTSN (on initAck)", a.name)
  987. }
  988. if cookieParam == nil {
  989. return ErrInitAckNoCookie
  990. }
  991. a.storedCookieEcho = &chunkCookieEcho{}
  992. a.storedCookieEcho.cookie = cookieParam.cookie
  993. err := a.sendCookieEcho()
  994. if err != nil {
  995. a.log.Errorf("[%s] failed to send init: %s", a.name, err.Error())
  996. }
  997. a.t1Cookie.start(a.rtoMgr.getRTO())
  998. a.setState(cookieEchoed)
  999. return nil
  1000. }
  1001. // The caller should hold the lock.
  1002. func (a *Association) handleHeartbeat(c *chunkHeartbeat) []*packet {
  1003. a.log.Tracef("[%s] chunkHeartbeat", a.name)
  1004. hbi, ok := c.params[0].(*paramHeartbeatInfo)
  1005. if !ok {
  1006. a.log.Warnf("[%s] failed to handle Heartbeat, no ParamHeartbeatInfo", a.name)
  1007. }
  1008. return pack(&packet{
  1009. verificationTag: a.peerVerificationTag,
  1010. sourcePort: a.sourcePort,
  1011. destinationPort: a.destinationPort,
  1012. chunks: []chunk{&chunkHeartbeatAck{
  1013. params: []param{
  1014. &paramHeartbeatInfo{
  1015. heartbeatInformation: hbi.heartbeatInformation,
  1016. },
  1017. },
  1018. }},
  1019. })
  1020. }
  1021. // The caller should hold the lock.
  1022. func (a *Association) handleCookieEcho(c *chunkCookieEcho) []*packet {
  1023. state := a.getState()
  1024. a.log.Debugf("[%s] COOKIE-ECHO received in state '%s'", a.name, getAssociationStateString(state))
  1025. if a.myCookie == nil {
  1026. a.log.Debugf("[%s] COOKIE-ECHO received before initialization", a.name)
  1027. return nil
  1028. }
  1029. switch state {
  1030. default:
  1031. return nil
  1032. case established:
  1033. if !bytes.Equal(a.myCookie.cookie, c.cookie) {
  1034. return nil
  1035. }
  1036. case closed, cookieWait, cookieEchoed:
  1037. if !bytes.Equal(a.myCookie.cookie, c.cookie) {
  1038. return nil
  1039. }
  1040. a.t1Init.stop()
  1041. a.storedInit = nil
  1042. a.t1Cookie.stop()
  1043. a.storedCookieEcho = nil
  1044. a.setState(established)
  1045. a.handshakeCompletedCh <- nil
  1046. }
  1047. p := &packet{
  1048. verificationTag: a.peerVerificationTag,
  1049. sourcePort: a.sourcePort,
  1050. destinationPort: a.destinationPort,
  1051. chunks: []chunk{&chunkCookieAck{}},
  1052. }
  1053. return pack(p)
  1054. }
  1055. // The caller should hold the lock.
  1056. func (a *Association) handleCookieAck() {
  1057. state := a.getState()
  1058. a.log.Debugf("[%s] COOKIE-ACK received in state '%s'", a.name, getAssociationStateString(state))
  1059. if state != cookieEchoed {
  1060. // RFC 4960
  1061. // 5.2.5. Handle Duplicate COOKIE-ACK.
  1062. // At any state other than COOKIE-ECHOED, an endpoint should silently
  1063. // discard a received COOKIE ACK chunk.
  1064. return
  1065. }
  1066. a.t1Cookie.stop()
  1067. a.storedCookieEcho = nil
  1068. a.setState(established)
  1069. a.handshakeCompletedCh <- nil
  1070. }
  1071. // The caller should hold the lock.
  1072. func (a *Association) handleData(d *chunkPayloadData) []*packet {
  1073. a.log.Tracef("[%s] DATA: tsn=%d immediateSack=%v len=%d",
  1074. a.name, d.tsn, d.immediateSack, len(d.userData))
  1075. a.stats.incDATAs()
  1076. canPush := a.payloadQueue.canPush(d, a.peerLastTSN)
  1077. if canPush {
  1078. s := a.getOrCreateStream(d.streamIdentifier, true, PayloadTypeUnknown)
  1079. if s == nil {
  1080. // silentely discard the data. (sender will retry on T3-rtx timeout)
  1081. // see pion/sctp#30
  1082. a.log.Debugf("discard %d", d.streamSequenceNumber)
  1083. return nil
  1084. }
  1085. if a.getMyReceiverWindowCredit() > 0 {
  1086. // Pass the new chunk to stream level as soon as it arrives
  1087. a.payloadQueue.push(d, a.peerLastTSN)
  1088. s.handleData(d)
  1089. } else {
  1090. // Receive buffer is full
  1091. lastTSN, ok := a.payloadQueue.getLastTSNReceived()
  1092. if ok && sna32LT(d.tsn, lastTSN) {
  1093. a.log.Debugf("[%s] receive buffer full, but accepted as this is a missing chunk with tsn=%d ssn=%d", a.name, d.tsn, d.streamSequenceNumber)
  1094. a.payloadQueue.push(d, a.peerLastTSN)
  1095. s.handleData(d)
  1096. } else {
  1097. a.log.Debugf("[%s] receive buffer full. dropping DATA with tsn=%d ssn=%d", a.name, d.tsn, d.streamSequenceNumber)
  1098. }
  1099. }
  1100. }
  1101. return a.handlePeerLastTSNAndAcknowledgement(d.immediateSack)
  1102. }
  1103. // A common routine for handleData and handleForwardTSN routines
  1104. // The caller should hold the lock.
  1105. func (a *Association) handlePeerLastTSNAndAcknowledgement(sackImmediately bool) []*packet {
  1106. var reply []*packet
  1107. // Try to advance peerLastTSN
  1108. // From RFC 3758 Sec 3.6:
  1109. // .. and then MUST further advance its cumulative TSN point locally
  1110. // if possible
  1111. // Meaning, if peerLastTSN+1 points to a chunk that is received,
  1112. // advance peerLastTSN until peerLastTSN+1 points to unreceived chunk.
  1113. for {
  1114. if _, popOk := a.payloadQueue.pop(a.peerLastTSN + 1); !popOk {
  1115. break
  1116. }
  1117. a.peerLastTSN++
  1118. for _, rstReq := range a.reconfigRequests {
  1119. resp := a.resetStreamsIfAny(rstReq)
  1120. if resp != nil {
  1121. a.log.Debugf("[%s] RESET RESPONSE: %+v", a.name, resp)
  1122. reply = append(reply, resp)
  1123. }
  1124. }
  1125. }
  1126. hasPacketLoss := (a.payloadQueue.size() > 0)
  1127. if hasPacketLoss {
  1128. a.log.Tracef("[%s] packetloss: %s", a.name, a.payloadQueue.getGapAckBlocksString(a.peerLastTSN))
  1129. }
  1130. if (a.ackState != ackStateImmediate && !sackImmediately && !hasPacketLoss && a.ackMode == ackModeNormal) || a.ackMode == ackModeAlwaysDelay {
  1131. if a.ackState == ackStateIdle {
  1132. a.delayedAckTriggered = true
  1133. } else {
  1134. a.immediateAckTriggered = true
  1135. }
  1136. } else {
  1137. a.immediateAckTriggered = true
  1138. }
  1139. return reply
  1140. }
  1141. // The caller should hold the lock.
  1142. func (a *Association) getMyReceiverWindowCredit() uint32 {
  1143. var bytesQueued uint32
  1144. for _, s := range a.streams {
  1145. bytesQueued += uint32(s.getNumBytesInReassemblyQueue())
  1146. }
  1147. if bytesQueued >= a.maxReceiveBufferSize {
  1148. return 0
  1149. }
  1150. return a.maxReceiveBufferSize - bytesQueued
  1151. }
  1152. // OpenStream opens a stream
  1153. func (a *Association) OpenStream(streamIdentifier uint16, defaultPayloadType PayloadProtocolIdentifier) (*Stream, error) {
  1154. a.lock.Lock()
  1155. defer a.lock.Unlock()
  1156. return a.getOrCreateStream(streamIdentifier, false, defaultPayloadType), nil
  1157. }
  1158. // AcceptStream accepts a stream
  1159. func (a *Association) AcceptStream() (*Stream, error) {
  1160. s, ok := <-a.acceptCh
  1161. if !ok {
  1162. return nil, io.EOF // no more incoming streams
  1163. }
  1164. return s, nil
  1165. }
  1166. // createStream creates a stream. The caller should hold the lock and check no stream exists for this id.
  1167. func (a *Association) createStream(streamIdentifier uint16, accept bool) *Stream {
  1168. s := &Stream{
  1169. association: a,
  1170. streamIdentifier: streamIdentifier,
  1171. reassemblyQueue: newReassemblyQueue(streamIdentifier),
  1172. log: a.log,
  1173. name: fmt.Sprintf("%d:%s", streamIdentifier, a.name),
  1174. }
  1175. s.readNotifier = sync.NewCond(&s.lock)
  1176. if accept {
  1177. select {
  1178. case a.acceptCh <- s:
  1179. a.streams[streamIdentifier] = s
  1180. a.log.Debugf("[%s] accepted a new stream (streamIdentifier: %d)",
  1181. a.name, streamIdentifier)
  1182. default:
  1183. a.log.Debugf("[%s] dropped a new stream (acceptCh size: %d)",
  1184. a.name, len(a.acceptCh))
  1185. return nil
  1186. }
  1187. } else {
  1188. a.streams[streamIdentifier] = s
  1189. }
  1190. return s
  1191. }
  1192. // getOrCreateStream gets or creates a stream. The caller should hold the lock.
  1193. func (a *Association) getOrCreateStream(streamIdentifier uint16, accept bool, defaultPayloadType PayloadProtocolIdentifier) *Stream {
  1194. if s, ok := a.streams[streamIdentifier]; ok {
  1195. s.SetDefaultPayloadType(defaultPayloadType)
  1196. return s
  1197. }
  1198. s := a.createStream(streamIdentifier, accept)
  1199. if s != nil {
  1200. s.SetDefaultPayloadType(defaultPayloadType)
  1201. }
  1202. return s
  1203. }
  1204. // The caller should hold the lock.
  1205. func (a *Association) processSelectiveAck(d *chunkSelectiveAck) (map[uint16]int, uint32, error) { // nolint:gocognit
  1206. bytesAckedPerStream := map[uint16]int{}
  1207. // New ack point, so pop all ACKed packets from inflightQueue
  1208. // We add 1 because the "currentAckPoint" has already been popped from the inflight queue
  1209. // For the first SACK we take care of this by setting the ackpoint to cumAck - 1
  1210. for i := a.cumulativeTSNAckPoint + 1; sna32LTE(i, d.cumulativeTSNAck); i++ {
  1211. c, ok := a.inflightQueue.pop(i)
  1212. if !ok {
  1213. return nil, 0, fmt.Errorf("%w: %v", ErrInflightQueueTSNPop, i)
  1214. }
  1215. if !c.acked {
  1216. // RFC 4096 sec 6.3.2. Retransmission Timer Rules
  1217. // R3) Whenever a SACK is received that acknowledges the DATA chunk
  1218. // with the earliest outstanding TSN for that address, restart the
  1219. // T3-rtx timer for that address with its current RTO (if there is
  1220. // still outstanding data on that address).
  1221. if i == a.cumulativeTSNAckPoint+1 {
  1222. // T3 timer needs to be reset. Stop it for now.
  1223. a.t3RTX.stop()
  1224. }
  1225. nBytesAcked := len(c.userData)
  1226. // Sum the number of bytes acknowledged per stream
  1227. if amount, ok := bytesAckedPerStream[c.streamIdentifier]; ok {
  1228. bytesAckedPerStream[c.streamIdentifier] = amount + nBytesAcked
  1229. } else {
  1230. bytesAckedPerStream[c.streamIdentifier] = nBytesAcked
  1231. }
  1232. // RFC 4960 sec 6.3.1. RTO Calculation
  1233. // C4) When data is in flight and when allowed by rule C5 below, a new
  1234. // RTT measurement MUST be made each round trip. Furthermore, new
  1235. // RTT measurements SHOULD be made no more than once per round trip
  1236. // for a given destination transport address.
  1237. // C5) Karn's algorithm: RTT measurements MUST NOT be made using
  1238. // packets that were retransmitted (and thus for which it is
  1239. // ambiguous whether the reply was for the first instance of the
  1240. // chunk or for a later instance)
  1241. if c.nSent == 1 && sna32GTE(c.tsn, a.minTSN2MeasureRTT) {
  1242. a.minTSN2MeasureRTT = a.myNextTSN
  1243. rtt := time.Since(c.since).Seconds() * 1000.0
  1244. srtt := a.rtoMgr.setNewRTT(rtt)
  1245. a.srtt.Store(srtt)
  1246. a.log.Tracef("[%s] SACK: measured-rtt=%f srtt=%f new-rto=%f",
  1247. a.name, rtt, srtt, a.rtoMgr.getRTO())
  1248. }
  1249. }
  1250. if a.inFastRecovery && c.tsn == a.fastRecoverExitPoint {
  1251. a.log.Debugf("[%s] exit fast-recovery", a.name)
  1252. a.inFastRecovery = false
  1253. }
  1254. }
  1255. htna := d.cumulativeTSNAck
  1256. // Mark selectively acknowledged chunks as "acked"
  1257. for _, g := range d.gapAckBlocks {
  1258. for i := g.start; i <= g.end; i++ {
  1259. tsn := d.cumulativeTSNAck + uint32(i)
  1260. c, ok := a.inflightQueue.get(tsn)
  1261. if !ok {
  1262. return nil, 0, fmt.Errorf("%w: %v", ErrTSNRequestNotExist, tsn)
  1263. }
  1264. if !c.acked {
  1265. nBytesAcked := a.inflightQueue.markAsAcked(tsn)
  1266. // Sum the number of bytes acknowledged per stream
  1267. if amount, ok := bytesAckedPerStream[c.streamIdentifier]; ok {
  1268. bytesAckedPerStream[c.streamIdentifier] = amount + nBytesAcked
  1269. } else {
  1270. bytesAckedPerStream[c.streamIdentifier] = nBytesAcked
  1271. }
  1272. a.log.Tracef("[%s] tsn=%d has been sacked", a.name, c.tsn)
  1273. if c.nSent == 1 {
  1274. a.minTSN2MeasureRTT = a.myNextTSN
  1275. rtt := time.Since(c.since).Seconds() * 1000.0
  1276. srtt := a.rtoMgr.setNewRTT(rtt)
  1277. a.srtt.Store(srtt)
  1278. a.log.Tracef("[%s] SACK: measured-rtt=%f srtt=%f new-rto=%f",
  1279. a.name, rtt, srtt, a.rtoMgr.getRTO())
  1280. }
  1281. if sna32LT(htna, tsn) {
  1282. htna = tsn
  1283. }
  1284. }
  1285. }
  1286. }
  1287. return bytesAckedPerStream, htna, nil
  1288. }
  1289. // The caller should hold the lock.
  1290. func (a *Association) onCumulativeTSNAckPointAdvanced(totalBytesAcked int) {
  1291. // RFC 4096, sec 6.3.2. Retransmission Timer Rules
  1292. // R2) Whenever all outstanding data sent to an address have been
  1293. // acknowledged, turn off the T3-rtx timer of that address.
  1294. if a.inflightQueue.size() == 0 {
  1295. a.log.Tracef("[%s] SACK: no more packet in-flight (pending=%d)", a.name, a.pendingQueue.size())
  1296. a.t3RTX.stop()
  1297. } else {
  1298. a.log.Tracef("[%s] T3-rtx timer start (pt2)", a.name)
  1299. a.t3RTX.start(a.rtoMgr.getRTO())
  1300. }
  1301. // Update congestion control parameters
  1302. if a.cwnd <= a.ssthresh {
  1303. // RFC 4096, sec 7.2.1. Slow-Start
  1304. // o When cwnd is less than or equal to ssthresh, an SCTP endpoint MUST
  1305. // use the slow-start algorithm to increase cwnd only if the current
  1306. // congestion window is being fully utilized, an incoming SACK
  1307. // advances the Cumulative TSN Ack Point, and the data sender is not
  1308. // in Fast Recovery. Only when these three conditions are met can
  1309. // the cwnd be increased; otherwise, the cwnd MUST not be increased.
  1310. // If these conditions are met, then cwnd MUST be increased by, at
  1311. // most, the lesser of 1) the total size of the previously
  1312. // outstanding DATA chunk(s) acknowledged, and 2) the destination's
  1313. // path MTU.
  1314. if !a.inFastRecovery &&
  1315. a.pendingQueue.size() > 0 {
  1316. a.cwnd += min32(uint32(totalBytesAcked), a.cwnd) // TCP way
  1317. // a.cwnd += min32(uint32(totalBytesAcked), a.mtu) // SCTP way (slow)
  1318. a.log.Tracef("[%s] updated cwnd=%d ssthresh=%d acked=%d (SS)",
  1319. a.name, a.cwnd, a.ssthresh, totalBytesAcked)
  1320. } else {
  1321. a.log.Tracef("[%s] cwnd did not grow: cwnd=%d ssthresh=%d acked=%d FR=%v pending=%d",
  1322. a.name, a.cwnd, a.ssthresh, totalBytesAcked, a.inFastRecovery, a.pendingQueue.size())
  1323. }
  1324. } else {
  1325. // RFC 4096, sec 7.2.2. Congestion Avoidance
  1326. // o Whenever cwnd is greater than ssthresh, upon each SACK arrival
  1327. // that advances the Cumulative TSN Ack Point, increase
  1328. // partial_bytes_acked by the total number of bytes of all new chunks
  1329. // acknowledged in that SACK including chunks acknowledged by the new
  1330. // Cumulative TSN Ack and by Gap Ack Blocks.
  1331. a.partialBytesAcked += uint32(totalBytesAcked)
  1332. // o When partial_bytes_acked is equal to or greater than cwnd and
  1333. // before the arrival of the SACK the sender had cwnd or more bytes
  1334. // of data outstanding (i.e., before arrival of the SACK, flight size
  1335. // was greater than or equal to cwnd), increase cwnd by MTU, and
  1336. // reset partial_bytes_acked to (partial_bytes_acked - cwnd).
  1337. if a.partialBytesAcked >= a.cwnd && a.pendingQueue.size() > 0 {
  1338. a.partialBytesAcked -= a.cwnd
  1339. a.cwnd += a.mtu
  1340. a.log.Tracef("[%s] updated cwnd=%d ssthresh=%d acked=%d (CA)",
  1341. a.name, a.cwnd, a.ssthresh, totalBytesAcked)
  1342. }
  1343. }
  1344. }
  1345. // The caller should hold the lock.
  1346. func (a *Association) processFastRetransmission(cumTSNAckPoint, htna uint32, cumTSNAckPointAdvanced bool) error {
  1347. // HTNA algorithm - RFC 4960 Sec 7.2.4
  1348. // Increment missIndicator of each chunks that the SACK reported missing
  1349. // when either of the following is met:
  1350. // a) Not in fast-recovery
  1351. // miss indications are incremented only for missing TSNs prior to the
  1352. // highest TSN newly acknowledged in the SACK.
  1353. // b) In fast-recovery AND the Cumulative TSN Ack Point advanced
  1354. // the miss indications are incremented for all TSNs reported missing
  1355. // in the SACK.
  1356. if !a.inFastRecovery || (a.inFastRecovery && cumTSNAckPointAdvanced) {
  1357. var maxTSN uint32
  1358. if !a.inFastRecovery {
  1359. // a) increment only for missing TSNs prior to the HTNA
  1360. maxTSN = htna
  1361. } else {
  1362. // b) increment for all TSNs reported missing
  1363. maxTSN = cumTSNAckPoint + uint32(a.inflightQueue.size()) + 1
  1364. }
  1365. for tsn := cumTSNAckPoint + 1; sna32LT(tsn, maxTSN); tsn++ {
  1366. c, ok := a.inflightQueue.get(tsn)
  1367. if !ok {
  1368. return fmt.Errorf("%w: %v", ErrTSNRequestNotExist, tsn)
  1369. }
  1370. if !c.acked && !c.abandoned() && c.missIndicator < 3 {
  1371. c.missIndicator++
  1372. if c.missIndicator == 3 {
  1373. if !a.inFastRecovery {
  1374. // 2) If not in Fast Recovery, adjust the ssthresh and cwnd of the
  1375. // destination address(es) to which the missing DATA chunks were
  1376. // last sent, according to the formula described in Section 7.2.3.
  1377. a.inFastRecovery = true
  1378. a.fastRecoverExitPoint = htna
  1379. a.ssthresh = max32(a.cwnd/2, 4*a.mtu)
  1380. a.cwnd = a.ssthresh
  1381. a.partialBytesAcked = 0
  1382. a.willRetransmitFast = true
  1383. a.log.Tracef("[%s] updated cwnd=%d ssthresh=%d inflight=%d (FR)",
  1384. a.name, a.cwnd, a.ssthresh, a.inflightQueue.getNumBytes())
  1385. }
  1386. }
  1387. }
  1388. }
  1389. }
  1390. if a.inFastRecovery && cumTSNAckPointAdvanced {
  1391. a.willRetransmitFast = true
  1392. }
  1393. return nil
  1394. }
  1395. // The caller should hold the lock.
  1396. func (a *Association) handleSack(d *chunkSelectiveAck) error {
  1397. a.log.Tracef("[%s] SACK: cumTSN=%d a_rwnd=%d", a.name, d.cumulativeTSNAck, d.advertisedReceiverWindowCredit)
  1398. state := a.getState()
  1399. if state != established && state != shutdownPending && state != shutdownReceived {
  1400. return nil
  1401. }
  1402. a.stats.incSACKs()
  1403. if sna32GT(a.cumulativeTSNAckPoint, d.cumulativeTSNAck) {
  1404. // RFC 4960 sec 6.2.1. Processing a Received SACK
  1405. // D)
  1406. // i) If Cumulative TSN Ack is less than the Cumulative TSN Ack
  1407. // Point, then drop the SACK. Since Cumulative TSN Ack is
  1408. // monotonically increasing, a SACK whose Cumulative TSN Ack is
  1409. // less than the Cumulative TSN Ack Point indicates an out-of-
  1410. // order SACK.
  1411. a.log.Debugf("[%s] SACK Cumulative ACK %v is older than ACK point %v",
  1412. a.name,
  1413. d.cumulativeTSNAck,
  1414. a.cumulativeTSNAckPoint)
  1415. return nil
  1416. }
  1417. // Process selective ack
  1418. bytesAckedPerStream, htna, err := a.processSelectiveAck(d)
  1419. if err != nil {
  1420. return err
  1421. }
  1422. var totalBytesAcked int
  1423. for _, nBytesAcked := range bytesAckedPerStream {
  1424. totalBytesAcked += nBytesAcked
  1425. }
  1426. cumTSNAckPointAdvanced := false
  1427. if sna32LT(a.cumulativeTSNAckPoint, d.cumulativeTSNAck) {
  1428. a.log.Tracef("[%s] SACK: cumTSN advanced: %d -> %d",
  1429. a.name,
  1430. a.cumulativeTSNAckPoint,
  1431. d.cumulativeTSNAck)
  1432. a.cumulativeTSNAckPoint = d.cumulativeTSNAck
  1433. cumTSNAckPointAdvanced = true
  1434. a.onCumulativeTSNAckPointAdvanced(totalBytesAcked)
  1435. }
  1436. for si, nBytesAcked := range bytesAckedPerStream {
  1437. if s, ok := a.streams[si]; ok {
  1438. a.lock.Unlock()
  1439. s.onBufferReleased(nBytesAcked)
  1440. a.lock.Lock()
  1441. }
  1442. }
  1443. // New rwnd value
  1444. // RFC 4960 sec 6.2.1. Processing a Received SACK
  1445. // D)
  1446. // ii) Set rwnd equal to the newly received a_rwnd minus the number
  1447. // of bytes still outstanding after processing the Cumulative
  1448. // TSN Ack and the Gap Ack Blocks.
  1449. // bytes acked were already subtracted by markAsAcked() method
  1450. bytesOutstanding := uint32(a.inflightQueue.getNumBytes())
  1451. if bytesOutstanding >= d.advertisedReceiverWindowCredit {
  1452. a.rwnd = 0
  1453. } else {
  1454. a.rwnd = d.advertisedReceiverWindowCredit - bytesOutstanding
  1455. }
  1456. err = a.processFastRetransmission(d.cumulativeTSNAck, htna, cumTSNAckPointAdvanced)
  1457. if err != nil {
  1458. return err
  1459. }
  1460. if a.useForwardTSN {
  1461. // RFC 3758 Sec 3.5 C1
  1462. if sna32LT(a.advancedPeerTSNAckPoint, a.cumulativeTSNAckPoint) {
  1463. a.advancedPeerTSNAckPoint = a.cumulativeTSNAckPoint
  1464. }
  1465. // RFC 3758 Sec 3.5 C2
  1466. for i := a.advancedPeerTSNAckPoint + 1; ; i++ {
  1467. c, ok := a.inflightQueue.get(i)
  1468. if !ok {
  1469. break
  1470. }
  1471. if !c.abandoned() {
  1472. break
  1473. }
  1474. a.advancedPeerTSNAckPoint = i
  1475. }
  1476. // RFC 3758 Sec 3.5 C3
  1477. if sna32GT(a.advancedPeerTSNAckPoint, a.cumulativeTSNAckPoint) {
  1478. a.willSendForwardTSN = true
  1479. }
  1480. a.awakeWriteLoop()
  1481. }
  1482. a.postprocessSack(state, cumTSNAckPointAdvanced)
  1483. return nil
  1484. }
  1485. // The caller must hold the lock. This method was only added because the
  1486. // linter was complaining about the "cognitive complexity" of handleSack.
  1487. func (a *Association) postprocessSack(state uint32, shouldAwakeWriteLoop bool) {
  1488. switch {
  1489. case a.inflightQueue.size() > 0:
  1490. // Start timer. (noop if already started)
  1491. a.log.Tracef("[%s] T3-rtx timer start (pt3)", a.name)
  1492. a.t3RTX.start(a.rtoMgr.getRTO())
  1493. case state == shutdownPending:
  1494. // No more outstanding, send shutdown.
  1495. shouldAwakeWriteLoop = true
  1496. a.willSendShutdown = true
  1497. a.setState(shutdownSent)
  1498. case state == shutdownReceived:
  1499. // No more outstanding, send shutdown ack.
  1500. shouldAwakeWriteLoop = true
  1501. a.willSendShutdownAck = true
  1502. a.setState(shutdownAckSent)
  1503. }
  1504. if shouldAwakeWriteLoop {
  1505. a.awakeWriteLoop()
  1506. }
  1507. }
  1508. // The caller should hold the lock.
  1509. func (a *Association) handleShutdown(_ *chunkShutdown) {
  1510. state := a.getState()
  1511. switch state {
  1512. case established:
  1513. if a.inflightQueue.size() > 0 {
  1514. a.setState(shutdownReceived)
  1515. } else {
  1516. // No more outstanding, send shutdown ack.
  1517. a.willSendShutdownAck = true
  1518. a.setState(shutdownAckSent)
  1519. a.awakeWriteLoop()
  1520. }
  1521. // a.cumulativeTSNAckPoint = c.cumulativeTSNAck
  1522. case shutdownSent:
  1523. a.willSendShutdownAck = true
  1524. a.setState(shutdownAckSent)
  1525. a.awakeWriteLoop()
  1526. }
  1527. }
  1528. // The caller should hold the lock.
  1529. func (a *Association) handleShutdownAck(_ *chunkShutdownAck) {
  1530. state := a.getState()
  1531. if state == shutdownSent || state == shutdownAckSent {
  1532. a.t2Shutdown.stop()
  1533. a.willSendShutdownComplete = true
  1534. a.awakeWriteLoop()
  1535. }
  1536. }
  1537. func (a *Association) handleShutdownComplete(_ *chunkShutdownComplete) error {
  1538. state := a.getState()
  1539. if state == shutdownAckSent {
  1540. a.t2Shutdown.stop()
  1541. return a.close()
  1542. }
  1543. return nil
  1544. }
  1545. func (a *Association) handleAbort(c *chunkAbort) error {
  1546. var errStr string
  1547. for _, e := range c.errorCauses {
  1548. errStr += fmt.Sprintf("(%s)", e)
  1549. }
  1550. _ = a.close()
  1551. return fmt.Errorf("[%s] %w: %s", a.name, ErrChunk, errStr)
  1552. }
  1553. // createForwardTSN generates ForwardTSN chunk.
  1554. // This method will be be called if useForwardTSN is set to false.
  1555. // The caller should hold the lock.
  1556. func (a *Association) createForwardTSN() *chunkForwardTSN {
  1557. // RFC 3758 Sec 3.5 C4
  1558. streamMap := map[uint16]uint16{} // to report only once per SI
  1559. for i := a.cumulativeTSNAckPoint + 1; sna32LTE(i, a.advancedPeerTSNAckPoint); i++ {
  1560. c, ok := a.inflightQueue.get(i)
  1561. if !ok {
  1562. break
  1563. }
  1564. ssn, ok := streamMap[c.streamIdentifier]
  1565. if !ok {
  1566. streamMap[c.streamIdentifier] = c.streamSequenceNumber
  1567. } else if sna16LT(ssn, c.streamSequenceNumber) {
  1568. // to report only once with greatest SSN
  1569. streamMap[c.streamIdentifier] = c.streamSequenceNumber
  1570. }
  1571. }
  1572. fwdtsn := &chunkForwardTSN{
  1573. newCumulativeTSN: a.advancedPeerTSNAckPoint,
  1574. streams: []chunkForwardTSNStream{},
  1575. }
  1576. var streamStr string
  1577. for si, ssn := range streamMap {
  1578. streamStr += fmt.Sprintf("(si=%d ssn=%d)", si, ssn)
  1579. fwdtsn.streams = append(fwdtsn.streams, chunkForwardTSNStream{
  1580. identifier: si,
  1581. sequence: ssn,
  1582. })
  1583. }
  1584. a.log.Tracef("[%s] building fwdtsn: newCumulativeTSN=%d cumTSN=%d - %s", a.name, fwdtsn.newCumulativeTSN, a.cumulativeTSNAckPoint, streamStr)
  1585. return fwdtsn
  1586. }
  1587. // createPacket wraps chunks in a packet.
  1588. // The caller should hold the read lock.
  1589. func (a *Association) createPacket(cs []chunk) *packet {
  1590. return &packet{
  1591. verificationTag: a.peerVerificationTag,
  1592. sourcePort: a.sourcePort,
  1593. destinationPort: a.destinationPort,
  1594. chunks: cs,
  1595. }
  1596. }
  1597. // The caller should hold the lock.
  1598. func (a *Association) handleReconfig(c *chunkReconfig) ([]*packet, error) {
  1599. a.log.Tracef("[%s] handleReconfig", a.name)
  1600. pp := make([]*packet, 0)
  1601. p, err := a.handleReconfigParam(c.paramA)
  1602. if err != nil {
  1603. return nil, err
  1604. }
  1605. if p != nil {
  1606. pp = append(pp, p)
  1607. }
  1608. if c.paramB != nil {
  1609. p, err = a.handleReconfigParam(c.paramB)
  1610. if err != nil {
  1611. return nil, err
  1612. }
  1613. if p != nil {
  1614. pp = append(pp, p)
  1615. }
  1616. }
  1617. return pp, nil
  1618. }
  1619. // The caller should hold the lock.
  1620. func (a *Association) handleForwardTSN(c *chunkForwardTSN) []*packet {
  1621. a.log.Tracef("[%s] FwdTSN: %s", a.name, c.String())
  1622. if !a.useForwardTSN {
  1623. a.log.Warn("[%s] received FwdTSN but not enabled")
  1624. // Return an error chunk
  1625. cerr := &chunkError{
  1626. errorCauses: []errorCause{&errorCauseUnrecognizedChunkType{}},
  1627. }
  1628. outbound := &packet{}
  1629. outbound.verificationTag = a.peerVerificationTag
  1630. outbound.sourcePort = a.sourcePort
  1631. outbound.destinationPort = a.destinationPort
  1632. outbound.chunks = []chunk{cerr}
  1633. return []*packet{outbound}
  1634. }
  1635. // From RFC 3758 Sec 3.6:
  1636. // Note, if the "New Cumulative TSN" value carried in the arrived
  1637. // FORWARD TSN chunk is found to be behind or at the current cumulative
  1638. // TSN point, the data receiver MUST treat this FORWARD TSN as out-of-
  1639. // date and MUST NOT update its Cumulative TSN. The receiver SHOULD
  1640. // send a SACK to its peer (the sender of the FORWARD TSN) since such a
  1641. // duplicate may indicate the previous SACK was lost in the network.
  1642. a.log.Tracef("[%s] should send ack? newCumTSN=%d peerLastTSN=%d",
  1643. a.name, c.newCumulativeTSN, a.peerLastTSN)
  1644. if sna32LTE(c.newCumulativeTSN, a.peerLastTSN) {
  1645. a.log.Tracef("[%s] sending ack on Forward TSN", a.name)
  1646. a.ackState = ackStateImmediate
  1647. a.ackTimer.stop()
  1648. a.awakeWriteLoop()
  1649. return nil
  1650. }
  1651. // From RFC 3758 Sec 3.6:
  1652. // the receiver MUST perform the same TSN handling, including duplicate
  1653. // detection, gap detection, SACK generation, cumulative TSN
  1654. // advancement, etc. as defined in RFC 2960 [2]---with the following
  1655. // exceptions and additions.
  1656. // When a FORWARD TSN chunk arrives, the data receiver MUST first update
  1657. // its cumulative TSN point to the value carried in the FORWARD TSN
  1658. // chunk,
  1659. // Advance peerLastTSN
  1660. for sna32LT(a.peerLastTSN, c.newCumulativeTSN) {
  1661. a.payloadQueue.pop(a.peerLastTSN + 1) // may not exist
  1662. a.peerLastTSN++
  1663. }
  1664. // Report new peerLastTSN value and abandoned largest SSN value to
  1665. // corresponding streams so that the abandoned chunks can be removed
  1666. // from the reassemblyQueue.
  1667. for _, forwarded := range c.streams {
  1668. if s, ok := a.streams[forwarded.identifier]; ok {
  1669. s.handleForwardTSNForOrdered(forwarded.sequence)
  1670. }
  1671. }
  1672. // TSN may be forewared for unordered chunks. ForwardTSN chunk does not
  1673. // report which stream identifier it skipped for unordered chunks.
  1674. // Therefore, we need to broadcast this event to all existing streams for
  1675. // unordered chunks.
  1676. // See https://github.com/pion/sctp/issues/106
  1677. for _, s := range a.streams {
  1678. s.handleForwardTSNForUnordered(c.newCumulativeTSN)
  1679. }
  1680. return a.handlePeerLastTSNAndAcknowledgement(false)
  1681. }
  1682. func (a *Association) sendResetRequest(streamIdentifier uint16) error {
  1683. a.lock.Lock()
  1684. defer a.lock.Unlock()
  1685. state := a.getState()
  1686. if state != established {
  1687. return fmt.Errorf("%w: state=%s", ErrResetPacketInStateNotExist,
  1688. getAssociationStateString(state))
  1689. }
  1690. // Create DATA chunk which only contains valid stream identifier with
  1691. // nil userData and use it as a EOS from the stream.
  1692. c := &chunkPayloadData{
  1693. streamIdentifier: streamIdentifier,
  1694. beginningFragment: true,
  1695. endingFragment: true,
  1696. userData: nil,
  1697. }
  1698. a.pendingQueue.push(c)
  1699. a.awakeWriteLoop()
  1700. return nil
  1701. }
  1702. // The caller should hold the lock.
  1703. func (a *Association) handleReconfigParam(raw param) (*packet, error) {
  1704. switch p := raw.(type) {
  1705. case *paramOutgoingResetRequest:
  1706. a.log.Tracef("[%s] handleReconfigParam (OutgoingResetRequest)", a.name)
  1707. a.reconfigRequests[p.reconfigRequestSequenceNumber] = p
  1708. resp := a.resetStreamsIfAny(p)
  1709. if resp != nil {
  1710. return resp, nil
  1711. }
  1712. return nil, nil //nolint:nilnil
  1713. case *paramReconfigResponse:
  1714. a.log.Tracef("[%s] handleReconfigParam (ReconfigResponse)", a.name)
  1715. delete(a.reconfigs, p.reconfigResponseSequenceNumber)
  1716. if len(a.reconfigs) == 0 {
  1717. a.tReconfig.stop()
  1718. }
  1719. return nil, nil //nolint:nilnil
  1720. default:
  1721. return nil, fmt.Errorf("%w: %t", ErrParamterType, p)
  1722. }
  1723. }
  1724. // The caller should hold the lock.
  1725. func (a *Association) resetStreamsIfAny(p *paramOutgoingResetRequest) *packet {
  1726. result := reconfigResultSuccessPerformed
  1727. if sna32LTE(p.senderLastTSN, a.peerLastTSN) {
  1728. a.log.Debugf("[%s] resetStream(): senderLastTSN=%d <= peerLastTSN=%d",
  1729. a.name, p.senderLastTSN, a.peerLastTSN)
  1730. for _, id := range p.streamIdentifiers {
  1731. s, ok := a.streams[id]
  1732. if !ok {
  1733. continue
  1734. }
  1735. a.lock.Unlock()
  1736. s.onInboundStreamReset()
  1737. a.lock.Lock()
  1738. a.log.Debugf("[%s] deleting stream %d", a.name, id)
  1739. delete(a.streams, s.streamIdentifier)
  1740. }
  1741. delete(a.reconfigRequests, p.reconfigRequestSequenceNumber)
  1742. } else {
  1743. a.log.Debugf("[%s] resetStream(): senderLastTSN=%d > peerLastTSN=%d",
  1744. a.name, p.senderLastTSN, a.peerLastTSN)
  1745. result = reconfigResultInProgress
  1746. }
  1747. return a.createPacket([]chunk{&chunkReconfig{
  1748. paramA: &paramReconfigResponse{
  1749. reconfigResponseSequenceNumber: p.reconfigRequestSequenceNumber,
  1750. result: result,
  1751. },
  1752. }})
  1753. }
  1754. // Move the chunk peeked with a.pendingQueue.peek() to the inflightQueue.
  1755. // The caller should hold the lock.
  1756. func (a *Association) movePendingDataChunkToInflightQueue(c *chunkPayloadData) {
  1757. if err := a.pendingQueue.pop(c); err != nil {
  1758. a.log.Errorf("[%s] failed to pop from pending queue: %s", a.name, err.Error())
  1759. }
  1760. // Mark all fragements are in-flight now
  1761. if c.endingFragment {
  1762. c.setAllInflight()
  1763. }
  1764. // Assign TSN
  1765. c.tsn = a.generateNextTSN()
  1766. c.since = time.Now() // use to calculate RTT and also for maxPacketLifeTime
  1767. c.nSent = 1 // being sent for the first time
  1768. a.checkPartialReliabilityStatus(c)
  1769. a.log.Tracef("[%s] sending ppi=%d tsn=%d ssn=%d sent=%d len=%d (%v,%v)",
  1770. a.name, c.payloadType, c.tsn, c.streamSequenceNumber, c.nSent, len(c.userData), c.beginningFragment, c.endingFragment)
  1771. a.inflightQueue.pushNoCheck(c)
  1772. }
  1773. // popPendingDataChunksToSend pops chunks from the pending queues as many as
  1774. // the cwnd and rwnd allows to send.
  1775. // The caller should hold the lock.
  1776. func (a *Association) popPendingDataChunksToSend() ([]*chunkPayloadData, []uint16) {
  1777. chunks := []*chunkPayloadData{}
  1778. var sisToReset []uint16 // stream identifieres to reset
  1779. if a.pendingQueue.size() > 0 {
  1780. // RFC 4960 sec 6.1. Transmission of DATA Chunks
  1781. // A) At any given time, the data sender MUST NOT transmit new data to
  1782. // any destination transport address if its peer's rwnd indicates
  1783. // that the peer has no buffer space (i.e., rwnd is 0; see Section
  1784. // 6.2.1). However, regardless of the value of rwnd (including if it
  1785. // is 0), the data sender can always have one DATA chunk in flight to
  1786. // the receiver if allowed by cwnd (see rule B, below).
  1787. for {
  1788. c := a.pendingQueue.peek()
  1789. if c == nil {
  1790. break // no more pending data
  1791. }
  1792. dataLen := uint32(len(c.userData))
  1793. if dataLen == 0 {
  1794. sisToReset = append(sisToReset, c.streamIdentifier)
  1795. err := a.pendingQueue.pop(c)
  1796. if err != nil {
  1797. a.log.Errorf("failed to pop from pending queue: %s", err.Error())
  1798. }
  1799. continue
  1800. }
  1801. if uint32(a.inflightQueue.getNumBytes())+dataLen > a.cwnd {
  1802. break // would exceeds cwnd
  1803. }
  1804. if dataLen > a.rwnd {
  1805. break // no more rwnd
  1806. }
  1807. a.rwnd -= dataLen
  1808. a.movePendingDataChunkToInflightQueue(c)
  1809. chunks = append(chunks, c)
  1810. }
  1811. // the data sender can always have one DATA chunk in flight to the receiver
  1812. if len(chunks) == 0 && a.inflightQueue.size() == 0 {
  1813. // Send zero window probe
  1814. c := a.pendingQueue.peek()
  1815. if c != nil {
  1816. a.movePendingDataChunkToInflightQueue(c)
  1817. chunks = append(chunks, c)
  1818. }
  1819. }
  1820. }
  1821. return chunks, sisToReset
  1822. }
  1823. // bundleDataChunksIntoPackets packs DATA chunks into packets. It tries to bundle
  1824. // DATA chunks into a packet so long as the resulting packet size does not exceed
  1825. // the path MTU.
  1826. // The caller should hold the lock.
  1827. func (a *Association) bundleDataChunksIntoPackets(chunks []*chunkPayloadData) []*packet {
  1828. packets := []*packet{}
  1829. chunksToSend := []chunk{}
  1830. bytesInPacket := int(commonHeaderSize)
  1831. for _, c := range chunks {
  1832. // RFC 4960 sec 6.1. Transmission of DATA Chunks
  1833. // Multiple DATA chunks committed for transmission MAY be bundled in a
  1834. // single packet. Furthermore, DATA chunks being retransmitted MAY be
  1835. // bundled with new DATA chunks, as long as the resulting packet size
  1836. // does not exceed the path MTU.
  1837. if bytesInPacket+len(c.userData) > int(a.mtu) {
  1838. packets = append(packets, a.createPacket(chunksToSend))
  1839. chunksToSend = []chunk{}
  1840. bytesInPacket = int(commonHeaderSize)
  1841. }
  1842. chunksToSend = append(chunksToSend, c)
  1843. bytesInPacket += int(dataChunkHeaderSize) + len(c.userData)
  1844. }
  1845. if len(chunksToSend) > 0 {
  1846. packets = append(packets, a.createPacket(chunksToSend))
  1847. }
  1848. return packets
  1849. }
  1850. // sendPayloadData sends the data chunks.
  1851. func (a *Association) sendPayloadData(chunks []*chunkPayloadData) error {
  1852. a.lock.Lock()
  1853. defer a.lock.Unlock()
  1854. state := a.getState()
  1855. if state != established {
  1856. return fmt.Errorf("%w: state=%s", ErrPayloadDataStateNotExist,
  1857. getAssociationStateString(state))
  1858. }
  1859. // Push the chunks into the pending queue first.
  1860. for _, c := range chunks {
  1861. a.pendingQueue.push(c)
  1862. }
  1863. a.awakeWriteLoop()
  1864. return nil
  1865. }
  1866. // The caller should hold the lock.
  1867. func (a *Association) checkPartialReliabilityStatus(c *chunkPayloadData) {
  1868. if !a.useForwardTSN {
  1869. return
  1870. }
  1871. // draft-ietf-rtcweb-data-protocol-09.txt section 6
  1872. // 6. Procedures
  1873. // All Data Channel Establishment Protocol messages MUST be sent using
  1874. // ordered delivery and reliable transmission.
  1875. //
  1876. if c.payloadType == PayloadTypeWebRTCDCEP {
  1877. return
  1878. }
  1879. // PR-SCTP
  1880. if s, ok := a.streams[c.streamIdentifier]; ok {
  1881. s.lock.RLock()
  1882. if s.reliabilityType == ReliabilityTypeRexmit {
  1883. if c.nSent >= s.reliabilityValue {
  1884. c.setAbandoned(true)
  1885. a.log.Tracef("[%s] marked as abandoned: tsn=%d ppi=%d (remix: %d)", a.name, c.tsn, c.payloadType, c.nSent)
  1886. }
  1887. } else if s.reliabilityType == ReliabilityTypeTimed {
  1888. elapsed := int64(time.Since(c.since).Seconds() * 1000)
  1889. if elapsed >= int64(s.reliabilityValue) {
  1890. c.setAbandoned(true)
  1891. a.log.Tracef("[%s] marked as abandoned: tsn=%d ppi=%d (timed: %d)", a.name, c.tsn, c.payloadType, elapsed)
  1892. }
  1893. }
  1894. s.lock.RUnlock()
  1895. } else {
  1896. a.log.Errorf("[%s] stream %d not found)", a.name, c.streamIdentifier)
  1897. }
  1898. }
  1899. // getDataPacketsToRetransmit is called when T3-rtx is timed out and retransmit outstanding data chunks
  1900. // that are not acked or abandoned yet.
  1901. // The caller should hold the lock.
  1902. func (a *Association) getDataPacketsToRetransmit() []*packet {
  1903. awnd := min32(a.cwnd, a.rwnd)
  1904. chunks := []*chunkPayloadData{}
  1905. var bytesToSend int
  1906. var done bool
  1907. for i := 0; !done; i++ {
  1908. c, ok := a.inflightQueue.get(a.cumulativeTSNAckPoint + uint32(i) + 1)
  1909. if !ok {
  1910. break // end of pending data
  1911. }
  1912. if !c.retransmit {
  1913. continue
  1914. }
  1915. if i == 0 && int(a.rwnd) < len(c.userData) {
  1916. // Send it as a zero window probe
  1917. done = true
  1918. } else if bytesToSend+len(c.userData) > int(awnd) {
  1919. break
  1920. }
  1921. // reset the retransmit flag not to retransmit again before the next
  1922. // t3-rtx timer fires
  1923. c.retransmit = false
  1924. bytesToSend += len(c.userData)
  1925. c.nSent++
  1926. a.checkPartialReliabilityStatus(c)
  1927. a.log.Tracef("[%s] retransmitting tsn=%d ssn=%d sent=%d", a.name, c.tsn, c.streamSequenceNumber, c.nSent)
  1928. chunks = append(chunks, c)
  1929. }
  1930. return a.bundleDataChunksIntoPackets(chunks)
  1931. }
  1932. // generateNextTSN returns the myNextTSN and increases it. The caller should hold the lock.
  1933. // The caller should hold the lock.
  1934. func (a *Association) generateNextTSN() uint32 {
  1935. tsn := a.myNextTSN
  1936. a.myNextTSN++
  1937. return tsn
  1938. }
  1939. // generateNextRSN returns the myNextRSN and increases it. The caller should hold the lock.
  1940. // The caller should hold the lock.
  1941. func (a *Association) generateNextRSN() uint32 {
  1942. rsn := a.myNextRSN
  1943. a.myNextRSN++
  1944. return rsn
  1945. }
  1946. func (a *Association) createSelectiveAckChunk() *chunkSelectiveAck {
  1947. sack := &chunkSelectiveAck{}
  1948. sack.cumulativeTSNAck = a.peerLastTSN
  1949. sack.advertisedReceiverWindowCredit = a.getMyReceiverWindowCredit()
  1950. sack.duplicateTSN = a.payloadQueue.popDuplicates()
  1951. sack.gapAckBlocks = a.payloadQueue.getGapAckBlocks(a.peerLastTSN)
  1952. return sack
  1953. }
  1954. func pack(p *packet) []*packet {
  1955. return []*packet{p}
  1956. }
  1957. func (a *Association) handleChunkStart() {
  1958. a.lock.Lock()
  1959. defer a.lock.Unlock()
  1960. a.delayedAckTriggered = false
  1961. a.immediateAckTriggered = false
  1962. }
  1963. func (a *Association) handleChunkEnd() {
  1964. a.lock.Lock()
  1965. defer a.lock.Unlock()
  1966. if a.immediateAckTriggered {
  1967. a.ackState = ackStateImmediate
  1968. a.ackTimer.stop()
  1969. a.awakeWriteLoop()
  1970. } else if a.delayedAckTriggered {
  1971. // Will send delayed ack in the next ack timeout
  1972. a.ackState = ackStateDelay
  1973. a.ackTimer.start()
  1974. }
  1975. }
  1976. func (a *Association) handleChunk(p *packet, c chunk) error {
  1977. a.lock.Lock()
  1978. defer a.lock.Unlock()
  1979. var packets []*packet
  1980. var err error
  1981. if _, err = c.check(); err != nil {
  1982. a.log.Errorf("[ %s ] failed validating chunk: %s ", a.name, err)
  1983. return nil
  1984. }
  1985. isAbort := false
  1986. switch c := c.(type) {
  1987. case *chunkInit:
  1988. packets, err = a.handleInit(p, c)
  1989. case *chunkInitAck:
  1990. err = a.handleInitAck(p, c)
  1991. case *chunkAbort:
  1992. isAbort = true
  1993. err = a.handleAbort(c)
  1994. case *chunkError:
  1995. var errStr string
  1996. for _, e := range c.errorCauses {
  1997. errStr += fmt.Sprintf("(%s)", e)
  1998. }
  1999. a.log.Debugf("[%s] Error chunk, with following errors: %s", a.name, errStr)
  2000. case *chunkHeartbeat:
  2001. packets = a.handleHeartbeat(c)
  2002. case *chunkCookieEcho:
  2003. packets = a.handleCookieEcho(c)
  2004. case *chunkCookieAck:
  2005. a.handleCookieAck()
  2006. case *chunkPayloadData:
  2007. packets = a.handleData(c)
  2008. case *chunkSelectiveAck:
  2009. err = a.handleSack(c)
  2010. case *chunkReconfig:
  2011. packets, err = a.handleReconfig(c)
  2012. case *chunkForwardTSN:
  2013. packets = a.handleForwardTSN(c)
  2014. case *chunkShutdown:
  2015. a.handleShutdown(c)
  2016. case *chunkShutdownAck:
  2017. a.handleShutdownAck(c)
  2018. case *chunkShutdownComplete:
  2019. err = a.handleShutdownComplete(c)
  2020. default:
  2021. err = ErrChunkTypeUnhandled
  2022. }
  2023. // Log and return, the only condition that is fatal is a ABORT chunk
  2024. if err != nil {
  2025. if isAbort {
  2026. return err
  2027. }
  2028. a.log.Errorf("Failed to handle chunk: %v", err)
  2029. return nil
  2030. }
  2031. if len(packets) > 0 {
  2032. a.controlQueue.pushAll(packets)
  2033. a.awakeWriteLoop()
  2034. }
  2035. return nil
  2036. }
  2037. func (a *Association) onRetransmissionTimeout(id int, nRtos uint) {
  2038. a.lock.Lock()
  2039. defer a.lock.Unlock()
  2040. if id == timerT1Init {
  2041. err := a.sendInit()
  2042. if err != nil {
  2043. a.log.Debugf("[%s] failed to retransmit init (nRtos=%d): %v", a.name, nRtos, err)
  2044. }
  2045. return
  2046. }
  2047. if id == timerT1Cookie {
  2048. err := a.sendCookieEcho()
  2049. if err != nil {
  2050. a.log.Debugf("[%s] failed to retransmit cookie-echo (nRtos=%d): %v", a.name, nRtos, err)
  2051. }
  2052. return
  2053. }
  2054. if id == timerT2Shutdown {
  2055. a.log.Debugf("[%s] retransmission of shutdown timeout (nRtos=%d): %v", a.name, nRtos)
  2056. state := a.getState()
  2057. switch state {
  2058. case shutdownSent:
  2059. a.willSendShutdown = true
  2060. a.awakeWriteLoop()
  2061. case shutdownAckSent:
  2062. a.willSendShutdownAck = true
  2063. a.awakeWriteLoop()
  2064. }
  2065. }
  2066. if id == timerT3RTX {
  2067. a.stats.incT3Timeouts()
  2068. // RFC 4960 sec 6.3.3
  2069. // E1) For the destination address for which the timer expires, adjust
  2070. // its ssthresh with rules defined in Section 7.2.3 and set the
  2071. // cwnd <- MTU.
  2072. // RFC 4960 sec 7.2.3
  2073. // When the T3-rtx timer expires on an address, SCTP should perform slow
  2074. // start by:
  2075. // ssthresh = max(cwnd/2, 4*MTU)
  2076. // cwnd = 1*MTU
  2077. a.ssthresh = max32(a.cwnd/2, 4*a.mtu)
  2078. a.cwnd = a.mtu
  2079. a.log.Tracef("[%s] updated cwnd=%d ssthresh=%d inflight=%d (RTO)",
  2080. a.name, a.cwnd, a.ssthresh, a.inflightQueue.getNumBytes())
  2081. // RFC 3758 sec 3.5
  2082. // A5) Any time the T3-rtx timer expires, on any destination, the sender
  2083. // SHOULD try to advance the "Advanced.Peer.Ack.Point" by following
  2084. // the procedures outlined in C2 - C5.
  2085. if a.useForwardTSN {
  2086. // RFC 3758 Sec 3.5 C2
  2087. for i := a.advancedPeerTSNAckPoint + 1; ; i++ {
  2088. c, ok := a.inflightQueue.get(i)
  2089. if !ok {
  2090. break
  2091. }
  2092. if !c.abandoned() {
  2093. break
  2094. }
  2095. a.advancedPeerTSNAckPoint = i
  2096. }
  2097. // RFC 3758 Sec 3.5 C3
  2098. if sna32GT(a.advancedPeerTSNAckPoint, a.cumulativeTSNAckPoint) {
  2099. a.willSendForwardTSN = true
  2100. }
  2101. }
  2102. a.log.Debugf("[%s] T3-rtx timed out: nRtos=%d cwnd=%d ssthresh=%d", a.name, nRtos, a.cwnd, a.ssthresh)
  2103. /*
  2104. a.log.Debugf(" - advancedPeerTSNAckPoint=%d", a.advancedPeerTSNAckPoint)
  2105. a.log.Debugf(" - cumulativeTSNAckPoint=%d", a.cumulativeTSNAckPoint)
  2106. a.inflightQueue.updateSortedKeys()
  2107. for i, tsn := range a.inflightQueue.sorted {
  2108. if c, ok := a.inflightQueue.get(tsn); ok {
  2109. a.log.Debugf(" - [%d] tsn=%d acked=%v abandoned=%v (%v,%v) len=%d",
  2110. i, c.tsn, c.acked, c.abandoned(), c.beginningFragment, c.endingFragment, len(c.userData))
  2111. }
  2112. }
  2113. */
  2114. a.inflightQueue.markAllToRetrasmit()
  2115. a.awakeWriteLoop()
  2116. return
  2117. }
  2118. if id == timerReconfig {
  2119. a.willRetransmitReconfig = true
  2120. a.awakeWriteLoop()
  2121. }
  2122. }
  2123. func (a *Association) onRetransmissionFailure(id int) {
  2124. a.lock.Lock()
  2125. defer a.lock.Unlock()
  2126. if id == timerT1Init {
  2127. a.log.Errorf("[%s] retransmission failure: T1-init", a.name)
  2128. a.handshakeCompletedCh <- ErrHandshakeInitAck
  2129. return
  2130. }
  2131. if id == timerT1Cookie {
  2132. a.log.Errorf("[%s] retransmission failure: T1-cookie", a.name)
  2133. a.handshakeCompletedCh <- ErrHandshakeCookieEcho
  2134. return
  2135. }
  2136. if id == timerT2Shutdown {
  2137. a.log.Errorf("[%s] retransmission failure: T2-shutdown", a.name)
  2138. return
  2139. }
  2140. if id == timerT3RTX {
  2141. // T3-rtx timer will not fail by design
  2142. // Justifications:
  2143. // * ICE would fail if the connectivity is lost
  2144. // * WebRTC spec is not clear how this incident should be reported to ULP
  2145. a.log.Errorf("[%s] retransmission failure: T3-rtx (DATA)", a.name)
  2146. return
  2147. }
  2148. }
  2149. func (a *Association) onAckTimeout() {
  2150. a.lock.Lock()
  2151. defer a.lock.Unlock()
  2152. a.log.Tracef("[%s] ack timed out (ackState: %d)", a.name, a.ackState)
  2153. a.stats.incAckTimeouts()
  2154. a.ackState = ackStateImmediate
  2155. a.awakeWriteLoop()
  2156. }
  2157. // bufferedAmount returns total amount (in bytes) of currently buffered user data.
  2158. // This is used only by testing.
  2159. func (a *Association) bufferedAmount() int {
  2160. a.lock.RLock()
  2161. defer a.lock.RUnlock()
  2162. return a.pendingQueue.getNumBytes() + a.inflightQueue.getNumBytes()
  2163. }
  2164. // MaxMessageSize returns the maximum message size you can send.
  2165. func (a *Association) MaxMessageSize() uint32 {
  2166. return atomic.LoadUint32(&a.maxMessageSize)
  2167. }
  2168. // SetMaxMessageSize sets the maximum message size you can send.
  2169. func (a *Association) SetMaxMessageSize(maxMsgSize uint32) {
  2170. atomic.StoreUint32(&a.maxMessageSize, maxMsgSize)
  2171. }