TCP.Mod 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643
  1. (* Aos, Copyright 2001, Pieter Muller, ETH Zurich *)
  2. MODULE TCP; (** AUTHOR "pjm, mvt"; PURPOSE "TCP protocol"; *)
  3. (*
  4. TCP - Transmission Control Protocol. Based on the 4.4BSD-Lite distribution described in Wright and Stevens, "TCP/IP Illustrated, Volume 2: The Implementation", ISBN 0-201-63354-X. See the BSD copyright statement at the end of this module. From that code it inherits some horrible control flow, which was left mostly intact, to make it easier to compare with the book.
  5. TCP Header
  6. 00 16 source port
  7. 02 16 destination port
  8. 04 32 sequence number
  9. 08 32 acknowledgement number
  10. 12 08 header length & reserved
  11. 07..04 header length (4-byte units)
  12. 03..00 reserved
  13. 13 08 flags
  14. 07..06 reserved
  15. 05..05 URG
  16. 04..04 ACK
  17. 03..03 PSH
  18. 02..02 RST
  19. 01..01 SYN
  20. 00..00 FIN
  21. 14 16 window size
  22. 16 16 TCP checksum
  23. 18 16 urgent pointer
  24. 20 -- options (0-40 bytes)
  25. -- -- data
  26. TCP Pseudo-header (for checksum calculation)
  27. 00 32 source address
  28. 04 32 destination address
  29. 08 08 zero = 0
  30. 09 08 protocol = 17
  31. 10 16 TCP length (duplicate)
  32. Notes:
  33. o Bit numbers above are Intel bit order.
  34. o Avoid use of SET because of PPC bit numbering issues.
  35. o Always access fields as 8-, 16- or 32-bit values and use DIV, MOD, ASH, ODD for bit access.
  36. *)
  37. IMPORT SYSTEM, Machine, KernelLog, Clock, Modules, Objects, Kernel, Commands, Network, IP, Streams, ActiveTimers;
  38. CONST
  39. StrongChecks = FALSE;
  40. TraceProtocol = FALSE;
  41. TraceError = FALSE;
  42. TracePacket = FALSE;
  43. TraceTimer = FALSE;
  44. TraceCongestion = FALSE;
  45. Trace = TraceProtocol OR TraceError OR TracePacket OR TraceTimer;
  46. HandleCongestion = TRUE;
  47. MinEphemeralPort = 1024;
  48. MaxEphemeralPort = 50000;
  49. HashTableSize = 1024 * 16; (* size of connection lookup hash table *)
  50. Acceptable = 500; (* "backlog" on listening connections *)
  51. NilPort* = 0;
  52. (** Error codes *)
  53. Ok* = 0;
  54. ConnectionRefused* = 3701;
  55. ConnectionReset* = 3702;
  56. WrongInterface* = 3703;
  57. TimedOut* = 3704;
  58. NotConnected* = 3705;
  59. NoInterface* = 3706;
  60. InterfaceClosed* = 3707;
  61. MinError = 3700;
  62. MaxError = 3735;
  63. NumErrors = MaxError-MinError+1;
  64. (** TCP connection states *)
  65. NumStates* = 12;
  66. Closed* = 0;
  67. Listen* = 1;
  68. SynSent* = 2;
  69. SynReceived* = 3;
  70. Established* = 4;
  71. CloseWait* = 5;
  72. FinWait1* = 6;
  73. Closing* = 7;
  74. LastAck* = 8;
  75. FinWait2* = 9;
  76. TimeWait* = 10;
  77. Unused* = 11; (* no real state, only used in this implementation *)
  78. OpenStates* = {Listen, SynReceived, Established, CloseWait, FinWait1, FinWait2};
  79. ClosedStates* = {Unused, Closed, Closing, LastAck, TimeWait};
  80. HalfClosedStates* = ClosedStates + {FinWait1, FinWait2};
  81. FinStates* = {Unused, Closed, CloseWait, Closing, LastAck, TimeWait};
  82. Fin = 0; Syn = 1; Rst = 2; Psh = 3; Ack = 4; Urg = 5; (* tcp header flags *)
  83. DoRFC1323 = TRUE; (* handle time stamp option (processing and generating) *)
  84. ProcOptions = TRUE; (* process TCP options *)
  85. GenOptions = TRUE; (* generate TCP options *)
  86. (* Flags in Connection *)
  87. AckNow = 0; (* send Ack immediately *)
  88. DelAck = 1; (* send Ack, but try to delay it *)
  89. NoDelay = 2; (* don't delay packets tocoalesce (disable Nagle algorithm) *)
  90. SentFin = 3; (* have sent Fin *)
  91. Force = 4; (* force out a byte (persist/OOB) *)
  92. RcvdScale = 5; (* set when other side sends window scale option in Syn *)
  93. RcvdTstmp = 6; (* set when other side sends timestamp option in Syn *)
  94. ReqScale = 7; (* have/will request window scale option in Syn *)
  95. ReqTstmp = 8; (* have/will request timestamp option in Syn *)
  96. DoKeepAlive = 9; (* enable keep-alive timer *)
  97. AcceptConn = 10; (* listening for incoming connections *)
  98. (*Notify = 11;*) (* socket wakeup *)
  99. (*Gone = 12;*) (* SS_NOFDREF *)
  100. (*NoMore = 13;*) (* SS_CANTRCVMORE *)
  101. Timeout = 14;
  102. NumTimers = 4;
  103. ReXmt = 0; Persist = 1; Keep = 2; MSL2 = 3;
  104. FastPeriod = 5; (* number of fast ticks per second *)
  105. SlowPeriod = 2; (* number of slow ticks per second *)
  106. TimerPeriod = 10; (* timer ticks per second *)
  107. MinTime = 1*SlowPeriod; (* minimum allowable time value *)
  108. ReXmtMax = 64*SlowPeriod; (* max allowable ReXmt value *)
  109. ReXmtThresh = 3;
  110. KeepInit = 75*SlowPeriod; (* connection establishment timer value (75s) *)
  111. KeepIntvl = 75*SlowPeriod; (* time between probes when no response (75s) *)
  112. KeepIdle = 2*60*60*SlowPeriod; (* default time before probing (2h) *)
  113. KeepCnt = 8; (* max probes before drop *)
  114. MaxIdle = KeepCnt * KeepIntvl; (* max time to send keepalive probes (10min) *)
  115. MSL = 30*SlowPeriod; (* max segment lifetime (30s) *)
  116. MaxPersistIdle = KeepIdle; (* max time to keep dead/unreachable connections (2h) *)
  117. PawsIdle = 24*24*60*60*SlowPeriod;
  118. SRTTBase = 0; (* base round trip time *)
  119. SRTTDflt = 3*SlowPeriod; (* assumed RTT if no info *)
  120. RTTShift = 3;
  121. RTTVarShift = 2;
  122. PersMin = 5*SlowPeriod; (* retransmit persistance *)
  123. PersMax = 60*SlowPeriod; (* maximum persist interval *)
  124. MSS = 536-12; (* maximum segment size for outgoing segments, 12 = size of timestamp option *)
  125. MaxRxtShift = 12; (* maximum retransmits *)
  126. MaxWin = 65535; (* largest value for (unscaled) window *)
  127. MaxWinShift = 14; (* maximum window shift *)
  128. MaxSendSpace = 80000H; (* 512KB, max. 1023MB *)
  129. MaxRecvSpace = 80000H; (* 512KB, max. 1023MB *)
  130. SegsPerBuf = 4; (* number of mss segments per send buffer (potential fragmentation waste is 1/SegsPerBuf) *)
  131. ISSInc = 128000; (* increment for iss each second *)
  132. IPTypeTCP = 6; (* TCP type code for IP packets *)
  133. MinTCPHdrLen = 20;
  134. MaxTCPHdrLen = 60;
  135. MaxPseudoHdrLen = 40; (* IPv4 = 12; IPv6 = 40 *)
  136. NewZeros = FALSE; (* NEW initializes allocated object fields to 0 *)
  137. BroadcastReceived = 3708;
  138. InvalidParameter = 3709;
  139. AllPortsInUse = 3710;
  140. AddressInUse = 3711;
  141. DuplicateSegment = 3712;
  142. DuplicatePartialSegment = 3713;
  143. DuplicateSegmentPAWS = 3714;
  144. DataBeyondWindow1 = 3715;
  145. DataBeyondWindow2 = 3716;
  146. DataBeyondWindow3 = 3717;
  147. BadChecksum = 3718;
  148. DuplicateAck = 3719;
  149. OutOfRangeAck = 3720;
  150. TimeOutKeepAlive = 3721;
  151. TimeoutEstablished = 3722;
  152. SegmentTooBig = 3723;
  153. SegmentTooSmall = 3724;
  154. BadHeaderLength = 3725;
  155. ConnectionGone = 3726;
  156. NIYNewIncarnation = 3727;
  157. NIYOutOfBand = 3728;
  158. NIYMSS = 3729;
  159. ConnectionAborted = 3730;
  160. NotInitialized = 3731;
  161. DataDuplicatePrevComplete = 3732;
  162. DataDuplicatePrevPartial = 3733;
  163. DataDuplicateNextComplete = 3734;
  164. DataDuplicateNextPartial = 3735;
  165. TYPE
  166. (* Send buffer types *)
  167. SendData = IP.Packet;
  168. SendBuffer = POINTER TO RECORD
  169. next: SendBuffer;
  170. ofs, len: LONGINT; (* data[ofs..ofs+len-1] is valid *)
  171. seq: LONGINT; (* sequence number of byte data[ofs] (only valid if len # 0) *)
  172. pf: SET; (* flags of segment *)
  173. data: SendData (* size should be multiple of maxseg *)
  174. END;
  175. TYPE
  176. ISS = OBJECT
  177. VAR iss: LONGINT; (* next iss to use *)
  178. PROCEDURE Update(hz: LONGINT);
  179. BEGIN {EXCLUSIVE}
  180. INC(iss, ISSInc DIV hz)
  181. END Update;
  182. PROCEDURE Get(): LONGINT;
  183. VAR t: LONGINT;
  184. BEGIN {EXCLUSIVE}
  185. t := iss; INC(iss, ISSInc);
  186. RETURN t
  187. END Get;
  188. PROCEDURE &Init*(iss: LONGINT);
  189. BEGIN
  190. SELF.iss := iss
  191. END Init;
  192. END ISS;
  193. TYPE
  194. Timer = OBJECT (* temporary *)
  195. VAR
  196. lastFast, lastSlow: LONGINT; (* time of last execution *)
  197. (*lastTrace: LONGINT;*)
  198. now: LONGINT; (* current tcp "time" - read from other procedures, but only updated inside this object *)
  199. timer: ActiveTimers.Timer;
  200. PROCEDURE CallDelayedAck(p: Connection);
  201. BEGIN
  202. p.DelayedAck();
  203. END CallDelayedAck;
  204. PROCEDURE CallSlowTimer(p: Connection);
  205. BEGIN
  206. p.SlowTimer();
  207. END CallSlowTimer;
  208. PROCEDURE HandleTimeout;
  209. VAR t: LONGINT;
  210. BEGIN {EXCLUSIVE}
  211. t := Kernel.GetTicks();
  212. IF t - lastFast >= Kernel.second DIV FastPeriod THEN
  213. lastFast := t;
  214. pool.Enumerate(CallDelayedAck);
  215. END;
  216. IF t - lastSlow >= Kernel.second DIV SlowPeriod THEN
  217. lastSlow := t;
  218. pool.Enumerate(CallSlowTimer);
  219. issSource.Update(SlowPeriod);
  220. INC(now)
  221. END;
  222. timer.SetTimeout(HandleTimeout, Kernel.second DIV TimerPeriod)
  223. END HandleTimeout;
  224. (* Finalize timer by cancelling it *)
  225. PROCEDURE Finalize;
  226. BEGIN {EXCLUSIVE}
  227. timer.Finalize
  228. END Finalize;
  229. PROCEDURE &Init*;
  230. BEGIN
  231. now := 0;
  232. lastSlow := Kernel.GetTicks() - Kernel.second;
  233. lastFast := lastSlow; (*lastTrace := lastSlow;*)
  234. NEW(timer);
  235. timer.SetTimeout(HandleTimeout, Kernel.second DIV TimerPeriod)
  236. END Init;
  237. END Timer;
  238. TYPE
  239. (** Connection object.
  240. NOTE: Only one process should access a Connection!
  241. *)
  242. Connection* = OBJECT(Streams.Connection)
  243. VAR
  244. poolNext, parent, acceptNext: Connection;
  245. (* assigned interface *)
  246. int-: IP.Interface;
  247. (* local protocol address *)
  248. lport-: LONGINT;
  249. (* foreign protocol address *)
  250. fip-: IP.Adr;
  251. fport-: LONGINT;
  252. state*: SHORTINT; (* TCP state *)
  253. timer: ARRAY NumTimers OF LONGINT;
  254. rxtshift-: LONGINT; (* log(2) of rexmt exponential backoff *)
  255. rxtcur-: LONGINT; (* current retransmission timeout (ticks) *)
  256. dupacks-: LONGINT; (* number of consequtive duplicate acks received *)
  257. maxseg-: LONGINT; (* maximum segment size to send *)
  258. flags: SET; (* various connection and buffer flags *)
  259. error: LONGINT; (* error on connection (socket error) *)
  260. acceptable: LONGINT; (* number of connections that can be before acceptance *)
  261. (* send sequence *)
  262. snduna-: LONGINT; (* send unacknowledged *)
  263. sndnxt-: LONGINT; (* send next *)
  264. sndup: LONGINT; (* send urgent pointer *)
  265. sndwl1-: LONGINT; (* window update seg seq number *)
  266. sndwl2-: LONGINT; (* window update seg ack number *)
  267. iss-: LONGINT; (* initial send sequence number *)
  268. sndwnd-: LONGINT; (* send window *)
  269. sndmax-: LONGINT; (* highest sequence number sent - used to recognize retransmits *)
  270. (* receive sequence *)
  271. rcvwnd-: LONGINT; (* receive window *)
  272. rcvnxt-: LONGINT; (* receive next *)
  273. rcvup: LONGINT; (* receive urgent pointer *)
  274. irs-: LONGINT; (* initial receive sequence number *)
  275. rcvadv-: LONGINT; (* advertised window by other end *)
  276. (* congestion control *)
  277. sndcwnd-: LONGINT; (* congestion-controlled window *)
  278. sndssthresh-: LONGINT; (* sndcwnd threshold for slow start - exponential to linear switch *)
  279. (* transmit timing *)
  280. idle-: LONGINT; (* inactivity time *)
  281. rtt-: LONGINT; (* round trip time *)
  282. rtseq-: LONGINT; (* sequence number being timed *)
  283. srtt-: LONGINT; (* smoothed round trip time *)
  284. rttvar-: LONGINT; (* variance in round trip time *)
  285. rttmin-: LONGINT; (* minimum rtt allowed *)
  286. maxsndwnd: LONGINT; (* largest window peer has offered *)
  287. (* RFC 1323 *)
  288. sndscale: LONGINT; (* scaling for send window (0-14) *)
  289. rcvscale: LONGINT; (* scaling for receive window (0-14) *)
  290. requestrscale: LONGINT; (* our pending window scale *)
  291. requestedsscale: LONGINT; (* peer's pending window scale *)
  292. tsrecent: LONGINT; (* timestamp echo data *)
  293. tsrecentage: LONGINT; (* when last updated *)
  294. lastacksent-: LONGINT; (* sequence number of last ack field *)
  295. (* send buffer *)
  296. sndcc-: LONGINT; (* number of bytes in send buffer *)
  297. sndspace-: LONGINT; (* number of bytes that may still be added before buffer is full *)
  298. sndhead, sndtail: SendBuffer; (* queue of segments (contiguous and in order) *)
  299. sndcontig: SendData; (* maxseg size buffer to make data contiguous *)
  300. (* receive buffer *)
  301. rcvspace-: LONGINT; (* number of bytes that may still be received before buffer is considered full *)
  302. rcvhiwat-: LONGINT; (* receive high water mark (MaxRecvSpace) *)
  303. rcvhead, rcvreasm, rcvtail: Network.Buffer; (* queue of segments - see description at the beginning of this file *)
  304. rcvheadFragment: Network.Buffer; (* current fragment of rcvhead *)
  305. timeout: ActiveTimers.Timer;
  306. traceflow-: LONGINT;
  307. (* Initialization for internal use only. *)
  308. PROCEDURE &Init*;
  309. BEGIN
  310. state := Unused;
  311. END Init;
  312. (** Open a TCP connection (only use once per Connection instance).
  313. Use TCP.NilPort for lport to automatically assign an unused local port.
  314. *)
  315. PROCEDURE Open*(lport: LONGINT; fip: IP.Adr; fport: LONGINT; VAR res: WORD);
  316. BEGIN {EXCLUSIVE}
  317. ASSERT((state = Unused) & (lport >= 0) & (lport < 10000H) & (fport >= 0) & (fport < 10000H));
  318. IF timeSource # NIL THEN
  319. InitConnection(SELF);
  320. IF (~IP.IsNilAdr(fip)) & (fport # NilPort) THEN
  321. (* active open (connect) *)
  322. int := IP.InterfaceByDstIP(fip);
  323. IF int # NIL THEN
  324. SELF.fip := fip;
  325. pool.Add(SELF, lport, fport, res); (* add connection to connection pool *)
  326. IF res = Ok THEN (* address assignment ok, now start the connection *)
  327. Machine.AtomicInc(NTCPConnectAttempt);
  328. state := SynSent; timer[Keep] := KeepInit;
  329. iss := issSource.Get();
  330. snduna := iss; sndnxt := iss; sndmax := iss; sndup := iss;
  331. Output(SELF)
  332. END;
  333. ELSE
  334. res := NoInterface;
  335. END;
  336. ELSE
  337. (* passive open (listen) *)
  338. ASSERT((fport = NilPort) & (IP.IsNilAdr(fip)));
  339. SELF.int := NIL;
  340. SELF.fip := IP.NilAdr;
  341. pool.Add(SELF, lport, NilPort, res);
  342. IF res = Ok THEN
  343. INCL(flags, AcceptConn);
  344. acceptable := Acceptable;
  345. state := Listen;
  346. END
  347. END;
  348. IF TraceProtocol THEN
  349. TraceTCP("Open", SELF, empty^, empty^, 0, 0, 0)
  350. END
  351. ELSE
  352. res := NotInitialized;
  353. END
  354. END Open;
  355. (** Send data on a TCP connection. *)
  356. PROCEDURE Send*(CONST data: ARRAY OF CHAR; ofs, len: LONGINT; propagate: BOOLEAN; VAR res: WORD);
  357. VAR buf: SendBuffer; len0: LONGINT;
  358. BEGIN {EXCLUSIVE}
  359. IF StrongChecks THEN Invariant(SELF) END;
  360. ASSERT(ofs+len <= LEN(data)); (* index check *)
  361. LOOP
  362. IF len <= 0 THEN EXIT END;
  363. IF len <= maxseg THEN len0 := len ELSE len0 := maxseg END;
  364. IF ~((state IN {Established, CloseWait}) & (sndspace >= len0)) THEN (* can not send immediately *)
  365. AWAIT(((state IN {Established, CloseWait}) & (sndspace >= len0)) OR ~(state IN {SynSent..CloseWait}));
  366. IF StrongChecks THEN Invariant(SELF) END;
  367. IF ~(state IN {SynSent..CloseWait}) THEN (* connection broken *)
  368. IF error # Ok THEN res := error ELSE res := NotConnected END;
  369. RETURN
  370. END
  371. END;
  372. buf := sndtail;
  373. IF LEN(buf.data^) - (buf.ofs+buf.len) >= len0 THEN (* last buffer has space for data *)
  374. Network.Copy(data, buf.data^, ofs, buf.ofs+buf.len, len0);
  375. INC(buf.len, len0)
  376. ELSE (* last buffer has no space for data *)
  377. buf := buf.next;
  378. IF buf # sndhead THEN (* is free buffer *)
  379. ASSERT((buf.ofs = 0) & (buf.len = 0)); (* buffer must be unused *)
  380. ASSERT(LEN(buf.data^) >= len0) (* index check *)
  381. ELSE
  382. Machine.AtomicInc(NTCPNewBufs);
  383. NEW(buf); NEW(buf.data, MSS * SegsPerBuf);
  384. IF ~NewZeros THEN buf.ofs := 0; END;
  385. buf.next := sndtail.next; sndtail.next := buf;
  386. ASSERT(LEN(buf.data^) >= len0) (* index check *)
  387. END;
  388. Network.Copy(data, buf.data^, ofs, 0, len0);
  389. buf.len := len0; sndtail := buf
  390. END;
  391. INC(sndcc, len0); DEC(sndspace, len0);
  392. Output(SELF);
  393. INC(ofs, len0); DEC(len, len0)
  394. END;
  395. IF TraceProtocol THEN
  396. TraceTCP("Send", SELF, empty^, data, 0, ofs, len)
  397. END;
  398. res := Ok
  399. END Send;
  400. (** Receive data on a TCP connection. The data parameter specifies the buffer. The ofs parameters specify the position in the buffer where data should be received (usually 0), and the size parameters specifies how many bytes of data can be received in the buffer. The min parameter specifies the minimum number of bytes to receive before Receive returns and must by <= size. The len parameter returns the number of bytes received, and the res parameter returns 0 if ok, or a non-zero error code otherwise (e.g. if the connection is closed by the communication partner, or by a call of the Close method). *)
  401. PROCEDURE Receive*(VAR data: ARRAY OF CHAR; ofs, size, min: LONGINT; VAR len: LONGINT; VAR res: WORD);
  402. VAR
  403. buf: Network.Buffer;
  404. rlen: LONGINT;
  405. BEGIN {EXCLUSIVE}
  406. IF StrongChecks THEN Invariant(SELF) END;
  407. ASSERT((ofs >= 0) & (ofs+size <= LEN(data)) & (min <= size)); (* parameter consistency check *)
  408. len := 0;
  409. LOOP
  410. WHILE (rcvhead # NIL) & (rcvhead # rcvreasm) & (size > 0) DO
  411. IF rcvhead.nextFragment = NIL THEN
  412. (* read all available data until user buffer is full *)
  413. rlen := MIN(rcvhead.len, size);
  414. Network.Copy(rcvhead.data, data, rcvhead.ofs, ofs, rlen);
  415. INC(len, rlen);
  416. INC(ofs, rlen);
  417. DEC(size, rlen);
  418. INC(rcvhead.ofs, rlen);
  419. DEC(rcvhead.len, rlen);
  420. INC(rcvhead.int, rlen);
  421. INC(rcvspace, rlen);
  422. IF rcvhead.len = 0 THEN
  423. (* go to next buffer *)
  424. buf := rcvhead;
  425. rcvhead := rcvhead.next;
  426. IF rcvhead # NIL THEN
  427. rcvhead.prev := NIL;
  428. END;
  429. Network.ReturnBuffer(buf);
  430. Output(SELF); (* enable sending window update segment *)
  431. END;
  432. ELSE
  433. (* rcvhead has fragments *)
  434. (* read all available data until user buffer is full *)
  435. IF rcvheadFragment = NIL THEN
  436. rcvheadFragment := rcvhead;
  437. END;
  438. rlen := MIN(rcvheadFragment.len, size);
  439. Network.Copy(rcvheadFragment.data, data, rcvheadFragment.ofs, ofs, rlen);
  440. INC(len, rlen);
  441. INC(ofs, rlen);
  442. DEC(size, rlen);
  443. INC(rcvheadFragment.ofs, rlen);
  444. DEC(rcvheadFragment.len, rlen);
  445. INC(rcvheadFragment.int, rlen);
  446. INC(rcvspace, rlen);
  447. IF rcvheadFragment.len = 0 THEN
  448. IF rcvheadFragment.nextFragment # NIL THEN
  449. (* go to next fragment *)
  450. rcvheadFragment := rcvheadFragment.nextFragment;
  451. ELSE
  452. (* go to next buffer *)
  453. buf := rcvhead;
  454. rcvhead := rcvhead.next;
  455. IF rcvhead # NIL THEN
  456. rcvhead.prev := NIL;
  457. END;
  458. Network.ReturnBuffer(buf);
  459. Output(SELF); (* enable sending window update segment *)
  460. END;
  461. END;
  462. END;
  463. END;
  464. IF size = 0 THEN
  465. (* user buffer full *)
  466. EXIT;
  467. END;
  468. IF len >= min THEN
  469. (* enough was read *)
  470. EXIT;
  471. ELSE
  472. (* await available data or closed connection state *)
  473. AWAIT(((rcvhead # NIL) & (rcvhead # rcvreasm)) OR ~(state IN {SynSent, SynReceived, Established, FinWait1, FinWait2}));
  474. IF StrongChecks THEN Invariant(SELF) END;
  475. IF (rcvhead # NIL) & (rcvhead # rcvreasm) THEN
  476. (* new data available, start again with LOOP *)
  477. ELSE
  478. (* no data available, and no more can arrive, as we've seen the FIN *)
  479. IF error # Ok THEN res := error ELSE res := Streams.EOF (* end of file *) END;
  480. RETURN;
  481. END;
  482. END;
  483. END;
  484. IF StrongChecks THEN Invariant(SELF) END;
  485. IF TraceProtocol THEN
  486. TraceTCP("Receive", SELF, empty^, data, 0, ofs, len)
  487. END;
  488. res := Ok
  489. END Receive;
  490. (** Enable or disable delayed send (Nagle algorithm).
  491. If enabled, the sending of a segment is delayed if it is not filled by one call to Send, in order to be able to be filled
  492. by further calls to Send. This is the default option.
  493. If disabled, a segment is sent immediatly after a call to Send, even if it is not filled. This option is normally chosen
  494. by applications like telnet or VNC client, which send verly little data but shall not be delayed.
  495. *)
  496. PROCEDURE DelaySend*(enable: BOOLEAN);
  497. BEGIN {EXCLUSIVE}
  498. IF enable THEN
  499. EXCL(flags, NoDelay);
  500. ELSE
  501. INCL(flags, NoDelay);
  502. END;
  503. END DelaySend;
  504. (** Enable or disable keep-alive. (default: disabled) *)
  505. PROCEDURE KeepAlive*(enable: BOOLEAN);
  506. BEGIN {EXCLUSIVE}
  507. IF enable THEN
  508. INCL(flags, DoKeepAlive);
  509. ELSE
  510. EXCL(flags, DoKeepAlive);
  511. END;
  512. END KeepAlive;
  513. (** Return number of bytes that may be read without blocking. *)
  514. PROCEDURE Available*(): LONGINT;
  515. VAR
  516. len: LONGINT;
  517. item: Network.Buffer;
  518. fragmentBuffer: Network.Buffer;
  519. reassembledLength: LONGINT;
  520. BEGIN {EXCLUSIVE}
  521. len := 0;
  522. item := rcvhead;
  523. WHILE(item # NIL) & (item # rcvreasm) DO
  524. IF item.nextFragment # NIL THEN
  525. INC(len, item.len);
  526. ELSE
  527. (* fragmented packet *)
  528. fragmentBuffer := item;
  529. reassembledLength := 0;
  530. WHILE fragmentBuffer # NIL DO
  531. INC(len, fragmentBuffer.len);
  532. fragmentBuffer := fragmentBuffer.nextFragment;
  533. END;
  534. END;
  535. item := item.next;
  536. END;
  537. RETURN len;
  538. END Available;
  539. (** Return connection state. *)
  540. PROCEDURE State*(): LONGINT;
  541. BEGIN {EXCLUSIVE}
  542. IF (state IN FinStates) & (rcvhead # NIL) & (rcvhead.len # 0) THEN (* workaround for client errors *)
  543. IF state = CloseWait THEN (* act as if we haven't seen a FIN yet *)
  544. RETURN Established
  545. ELSE
  546. RETURN FinWait1
  547. END
  548. ELSE
  549. RETURN state
  550. END
  551. END State;
  552. (** Wait until the connection state is either in the good or bad set, up to "ms" milliseconds. *)
  553. PROCEDURE AwaitState*(good, bad: SET; ms: LONGINT; VAR res: WORD);
  554. BEGIN {EXCLUSIVE}
  555. IF ~(state IN (good+bad)) THEN
  556. IF ms # -1 THEN
  557. IF timeout = NIL THEN NEW(timeout) END;
  558. timeout.SetTimeout(SELF.HandleTimeout, ms);
  559. END;
  560. EXCL(flags, Timeout);
  561. AWAIT((state IN (good+bad)) OR (Timeout IN flags));
  562. IF ms # -1 THEN timeout.CancelTimeout(); END
  563. END;
  564. IF state IN good THEN
  565. res := Ok
  566. ELSIF state IN bad THEN
  567. res := NotConnected
  568. ELSE
  569. res := TimedOut
  570. END
  571. END AwaitState;
  572. PROCEDURE HandleTimeout;
  573. BEGIN {EXCLUSIVE}
  574. INCL(flags, Timeout)
  575. END HandleTimeout;
  576. (** Close a TCP connection (half-close). *)
  577. PROCEDURE Close*;
  578. BEGIN {EXCLUSIVE}
  579. IF state < Established THEN
  580. CloseConnection(SELF)
  581. ELSIF FALSE (* linger *) THEN
  582. Drop(SELF, 0)
  583. ELSE
  584. UsrClosed(SELF);
  585. IF state # Closed THEN Output(SELF) END
  586. END;
  587. IF TraceProtocol THEN
  588. TraceTCP("Close", SELF, empty^, empty^, 0, 0, 0)
  589. END
  590. END Close;
  591. (** Discard a TCP connection (shutdown). *)
  592. PROCEDURE Discard*;
  593. BEGIN {EXCLUSIVE}
  594. IF state < Established THEN
  595. CloseConnection(SELF)
  596. ELSE
  597. Drop(SELF, ConnectionReset) (* ??? *)
  598. END;
  599. IF TraceProtocol THEN
  600. TraceTCP("Discard", SELF, empty^, empty^, 0, 0, 0)
  601. END
  602. END Discard;
  603. (** Accept a client waiting on a listening connection. Blocks until a client is available or the connection is closed. *)
  604. PROCEDURE Accept*(VAR client: Connection; VAR res: WORD);
  605. BEGIN {EXCLUSIVE}
  606. AWAIT((state # Listen) OR (acceptNext # NIL));
  607. IF acceptNext # NIL THEN
  608. client := acceptNext; acceptNext := acceptNext.acceptNext;
  609. INC(acceptable); res := Ok
  610. ELSE
  611. client := NIL; res := ConnectionRefused
  612. END
  613. END Accept;
  614. (** Return TRUE iff a listening connection has clients waiting to be accepted. *)
  615. PROCEDURE Requested*(): BOOLEAN;
  616. BEGIN {EXCLUSIVE}
  617. RETURN (state = Listen) & (acceptNext # NIL)
  618. END Requested;
  619. (* Process a received segment for the current Connection. *)
  620. PROCEDURE Input(int: IP.Interface; fip: IP.Adr; hdrLen: LONGINT; buffer: Network.Buffer);
  621. VAR
  622. bufferQueued: BOOLEAN; (* was buffer queued by ProcessInput() ? *)
  623. p: Connection;
  624. BEGIN {EXCLUSIVE}
  625. (* to do: move header prediction code here *)
  626. IF StrongChecks THEN Invariant(SELF) END;
  627. bufferQueued := FALSE;
  628. IF AcceptConn IN flags THEN
  629. IF acceptable > 0 THEN
  630. NEW(p); InitConnection(p); (* fig. 28.7 *)
  631. p.int := int;
  632. p.fip := fip;
  633. p.state := Listen; p.parent := SELF;
  634. ProcessInput(p, hdrLen, buffer, TRUE, bufferQueued);
  635. IF p.state = SynReceived THEN (* packet was accepted *)
  636. DEC(acceptable) (* limit number of "temporary" Connections *)
  637. END
  638. ELSE
  639. Machine.AtomicInc(NTCPUnacceptable)
  640. END
  641. ELSE
  642. IF SELF = nilpcb THEN
  643. (* set info for "Respond" *)
  644. SELF.int := int;
  645. SELF.fport := Network.GetNet2(buffer.data, buffer.ofs);
  646. SELF.lport := Network.GetNet2(buffer.data, buffer.ofs+2);
  647. END;
  648. IF SELF.int # int THEN
  649. (* packet must be received by interface attached to this connection *)
  650. Error(WrongInterface, 0, SELF);
  651. ELSE
  652. SELF.fip := fip;
  653. ProcessInput(SELF, hdrLen, buffer, FALSE, bufferQueued);
  654. END;
  655. END;
  656. IF StrongChecks THEN Invariant(SELF) END;
  657. IF ~bufferQueued THEN
  658. Network.ReturnBuffer(buffer);
  659. END;
  660. END Input;
  661. (* Schedule a delayed ack. *)
  662. PROCEDURE DelayedAck;
  663. BEGIN {EXCLUSIVE}
  664. IF StrongChecks THEN Invariant(SELF) END;
  665. IF DelAck IN flags THEN
  666. flags := (flags - {DelAck}) + {AckNow};
  667. Machine.AtomicInc(NTCPDelAck);
  668. Output(SELF)
  669. END
  670. END DelayedAck;
  671. (* Schedule a slow timer event (fig. 25.8). *)
  672. PROCEDURE SlowTimer;
  673. VAR dropit: BOOLEAN;
  674. oldie: LONGINT;
  675. BEGIN {EXCLUSIVE}
  676. oldie := sndnxt;
  677. IF StrongChecks THEN Invariant(SELF) END;
  678. IF Expired(timer[ReXmt]) THEN (* fig. 25.26 *)
  679. INC(rxtshift);
  680. IF rxtshift > MaxRxtShift THEN
  681. rxtshift := MaxRxtShift; Error(TimedOut, 0, SELF); Drop(SELF, TimedOut)
  682. ELSE
  683. Machine.AtomicInc(NTCPReXmtTimer);
  684. RangeSet(rxtcur, (ASH(srtt, -RTTShift) + rttvar) * backoff[rxtshift], rttmin, ReXmtMax);
  685. timer[ReXmt] := rxtcur;
  686. IF rxtshift > MaxRxtShift DIV 4 THEN
  687. (* to do: drop current route *)
  688. INC(rttvar, ASH(srtt, -RTTShift));
  689. srtt := 0
  690. END;
  691. sndnxt := snduna; rtt := 0;
  692. sndcwnd := maxseg; dupacks := 0;
  693. sndssthresh := MAX(MIN(sndwnd, sndcwnd) DIV 2 DIV maxseg, 2) * maxseg;
  694. IF TraceCongestion THEN
  695. KernelLog.String("ST sndssthresh := "); KernelLog.Int(sndssthresh, 1); KernelLog.Ln
  696. END;
  697. Output(SELF)
  698. END
  699. END;
  700. IF Expired(timer[Persist]) THEN (* fig. 25.13 *)
  701. Machine.AtomicInc(NTCPPersistTimer);
  702. IF (rxtshift = MaxRxtShift) & ((idle >= MaxPersistIdle) OR (idle >= (ASH(srtt, -RTTShift) + rttvar) * totbackoff)) THEN
  703. Machine.AtomicInc(NTCPPersistDrop); (* vol. 3 fig. 14.17 *)
  704. Drop(SELF, TimedOut)
  705. ELSE
  706. SetPersist(SELF); INCL(flags, Force); Output(SELF); EXCL(flags, Force)
  707. END
  708. END;
  709. traceflow := 0;
  710. IF Expired(timer[Keep]) THEN (* fig. 25.16 *)
  711. Machine.AtomicInc(NTCPKeepTimer); dropit := FALSE;
  712. IF state >= Established THEN
  713. IF (DoKeepAlive IN flags) & (state <= CloseWait) THEN
  714. IF idle < KeepIdle + MaxIdle THEN
  715. traceflow := 1;
  716. Machine.AtomicInc(NTCPKeepProbe);
  717. Respond(SELF, rcvnxt, snduna-1, {});
  718. timer[Keep] := KeepIntvl
  719. ELSE
  720. traceflow := 2;
  721. dropit := TRUE; Error(TimeOutKeepAlive, 0, SELF)
  722. END
  723. ELSE
  724. traceflow := 3;
  725. timer[Keep] := KeepIdle
  726. END
  727. ELSE
  728. traceflow := 4;
  729. dropit := TRUE; Error(TimeoutEstablished, 0, SELF)
  730. END;
  731. IF dropit THEN Drop(SELF, TimedOut) END
  732. END;
  733. IF Expired(timer[MSL2]) THEN (* fig. 25.10 *)
  734. IF (state # TimeWait) & (idle <= MaxIdle) THEN
  735. timer[MSL2] := KeepIntvl
  736. ELSE
  737. IF state = FinWait2 THEN Machine.AtomicInc(NTCPFinWait2Timer) ELSE Machine.AtomicInc(NTCPTimeWaitTimer) END;
  738. CloseConnection(SELF)
  739. END
  740. END;
  741. INC(idle);
  742. IF rtt # 0 THEN INC(rtt) END;
  743. (* check if interface wasn't closed/removed in meantime *)
  744. IF (int # NIL) & (int.closed) THEN
  745. Drop(SELF, InterfaceClosed);
  746. END;
  747. END SlowTimer;
  748. (* Finalize the Connection object *)
  749. PROCEDURE Finalize;
  750. BEGIN
  751. IF timeout # NIL THEN timeout.Finalize; END;
  752. Discard();
  753. END Finalize;
  754. END Connection;
  755. TYPE
  756. ConnectionHandler* = PROCEDURE {DELEGATE} (p: Connection);
  757. ConnectionPool* = OBJECT
  758. VAR
  759. eport: LONGINT;
  760. table: ARRAY HashTableSize OF Connection;
  761. (* Initialization for internal use only. *)
  762. PROCEDURE &Init*;
  763. VAR i: LONGINT;
  764. BEGIN
  765. FOR i:= 0 TO HashTableSize-1 DO
  766. table[i] := NIL;
  767. END;
  768. eport := MinEphemeralPort;
  769. END Init;
  770. (* Finalize all connections in this pool *)
  771. PROCEDURE Finalize;
  772. VAR i: LONGINT;
  773. BEGIN
  774. FOR i:= 0 TO HashTableSize-1 DO
  775. WHILE table[i] # NIL DO
  776. table[i].Finalize();
  777. END;
  778. END;
  779. END Finalize;
  780. (* Look for the specified Connection. *)
  781. PROCEDURE Lookup(lport, fport: LONGINT; fip: IP.Adr): Connection;
  782. VAR
  783. item: Connection;
  784. BEGIN
  785. item := table[HashPool(lport, fport, fip)];
  786. WHILE (item # NIL) & ((~IP.AdrsEqual(item.fip, fip)) OR (item.fport # fport) OR (item.lport # lport)) DO
  787. item := item.poolNext;
  788. END;
  789. IF item = NIL THEN
  790. RETURN nilpcb;
  791. ELSE
  792. RETURN item;
  793. END;
  794. END Lookup;
  795. (** Enumerate all Connections. Only for tracing, due to concurrent updates data may be stale. *)
  796. PROCEDURE Enumerate*(handle: ConnectionHandler);
  797. VAR
  798. i: LONGINT;
  799. item: Connection;
  800. BEGIN
  801. FOR i:= 0 TO HashTableSize-1 DO
  802. item := table[i];
  803. WHILE item # NIL DO
  804. handle(item);
  805. item := item.poolNext;
  806. END;
  807. END;
  808. END Enumerate;
  809. (* Add the connection p to the pool (attach). Assumes the caller has exclusive access to p.
  810. IF (fport = NilPort) & (fip = IP.NilAdr), a listening connection is assumed.
  811. ELSE an active open is assumed.
  812. IF (lport = NilPort), an ephemeral port is assigned.
  813. *)
  814. PROCEDURE Add(p: Connection; lport, fport: LONGINT; VAR res: WORD);
  815. VAR i, sport: LONGINT;
  816. BEGIN {EXCLUSIVE}
  817. IF ((fport # NilPort) & (IP.IsNilAdr(p.fip))) OR (* workaround for XOR *)
  818. ((fport = NilPort) & (~IP.IsNilAdr(p.fip))) THEN
  819. (* both must be "nil" or both must not be "nil" *)
  820. res := InvalidParameter;
  821. Error(res, 0, p);
  822. RETURN;
  823. END;
  824. IF lport = NilPort THEN
  825. (* find an ephemeral port *)
  826. sport := eport;
  827. LOOP
  828. lport := eport;
  829. INC(eport);
  830. IF eport > MaxEphemeralPort THEN
  831. eport := MinEphemeralPort;
  832. END;
  833. IF Lookup(lport, fport, p.fip) = nilpcb THEN
  834. (* found port that is not in use *)
  835. EXIT;
  836. END;
  837. IF eport = sport THEN
  838. res := AllPortsInUse;
  839. Error(res, 0, p);
  840. RETURN;
  841. END;
  842. END;
  843. ELSE
  844. IF Lookup(lport, fport, p.fip) # nilpcb THEN
  845. res := AddressInUse;
  846. Error(res, 0, p);
  847. RETURN;
  848. END;
  849. END;
  850. p.lport := lport;
  851. p.fport := fport;
  852. (* add to pool *)
  853. i := HashPool(lport, fport, p.fip);
  854. p.poolNext := table[i];
  855. table[i] := p;
  856. res := Ok;
  857. END Add;
  858. (* Remove a Connection from the queue (detach), making its address re-usable. *)
  859. PROCEDURE Remove(p: Connection);
  860. VAR
  861. i: LONGINT;
  862. item: Connection;
  863. BEGIN {EXCLUSIVE}
  864. i := HashPool(p.lport, p.fport, p.fip);
  865. IF table[i] # NIL THEN
  866. IF table[i] = p THEN
  867. (* remove first item *)
  868. table[i] := table[i].poolNext;
  869. RETURN;
  870. ELSE
  871. (* search list for connection *)
  872. item := table[i];
  873. WHILE (item.poolNext # NIL) & (item.poolNext # p) DO
  874. item := item.poolNext;
  875. END;
  876. IF item.poolNext # NIL THEN
  877. (* found - remove *)
  878. item.poolNext := item.poolNext.poolNext;
  879. RETURN;
  880. END;
  881. END;
  882. END;
  883. Error(ConnectionGone, 0, p); (* pcb gone, e.g. Rst received *)
  884. END Remove;
  885. END ConnectionPool;
  886. TYPE
  887. (** Install a procedure to be called when no matching port was found for an incoming connection request.
  888. The buffer MUST NOT be returned by the listener, it is returned automatically by the caller afterwards.
  889. *)
  890. PacketDumpListener* = PROCEDURE (fip: IP.Adr; buffer: Network.Buffer);
  891. VAR
  892. pool*: ConnectionPool; (* pool of all Connections *)
  893. timeSource: Timer; (* global timer *)
  894. issSource: ISS; (* source for ISS numbers *)
  895. lastpcb: Connection; (* cache last used pcb (never NIL). Note that it is possible that a deleted pcb can be ressurrected by a packet arriving for it. As soon as a packet for another connection arrives, the deleted pcb will vanish. *)
  896. nilpcb: Connection; (* never NIL *)
  897. empty: SendData; (* never NIL *)
  898. backoff: ARRAY MaxRxtShift+1 OF LONGINT; (* exponential backoff multipliers *)
  899. totbackoff: LONGINT;
  900. outflags: ARRAY NumStates OF SET; (* output header flags *)
  901. (* TCP counters *)
  902. NTCPError-: ARRAY NumErrors OF LONGINT;
  903. NTCPConnectAttempt-, NTCPPersistTimer-, NTCPFinWait2Timer-, NTCPSendProbe-, NTCPReXmtPack-,
  904. NTCPReXmtByte-, NTCPSendPack-, NTCPSendByte-, NTCPAcks-, NTCPSendCtrl-, NTCPSendUrg-,
  905. NTCPSendWinUp-, NTCPSegsTimed-, NTCPSendTotal-, NTCPKeepTimer-, NTCPKeepProbe-,
  906. NTCPReXmtTimer-, NTCPRcvTotal-, NTCPRcvOptions-, NTCPCacheMiss-, NTCPPredAck-, NTCPAckPack-,
  907. NTCPAckByte-, NTCPPredData-, NTCPRcvPackFast-, NTCPRcvByteFast-, NTCPConnects-, NTCPRcvWinProbe-,
  908. NTCPDrops-, NTCPRcvWinUpd-, NTCPRTTUpdated-, NTCPDelAck-, NTCPConnDrops-, NTCPClosed-, NTCPSplitBuffer-,
  909. NTCPRcvPackSlow-, NTCPRcvByteSlow-, NTCPNewBufs-, NTCPTimeWaitTimer-,
  910. NTCPUnacceptable-, NTCPAccepts-, NTCPPersistDrop-: LONGINT;
  911. trace: BOOLEAN;
  912. packetDumpListener : PacketDumpListener;
  913. (* Trace installer *)
  914. (** Install a procedure to be called when no matching port was found for an incoming connection request.
  915. The buffer doesn't have to be returned by the listener, it is returned automatically by the caller afterwards.
  916. *)
  917. PROCEDURE SetDefaultListener*(pdl : PacketDumpListener);
  918. BEGIN
  919. packetDumpListener := pdl
  920. END SetDefaultListener;
  921. (* --- Utility procedures. *)
  922. PROCEDURE Invariant(p: Connection);
  923. VAR
  924. rcvbuf: Network.Buffer;
  925. sndbuf: SendBuffer;
  926. found: BOOLEAN;
  927. BEGIN
  928. IF StrongChecks & (p # nilpcb) THEN
  929. (* receive buffers *)
  930. rcvbuf := p.rcvhead;
  931. IF rcvbuf # NIL THEN
  932. (* not empty *)
  933. ASSERT((rcvbuf.len > 0) OR (Fin IN rcvbuf.set));
  934. ASSERT(rcvbuf.prev = NIL);
  935. IF rcvbuf.next = NIL THEN
  936. (* the only buffer *)
  937. ASSERT(p.rcvtail = rcvbuf);
  938. ELSE
  939. rcvbuf := rcvbuf.next;
  940. IF rcvbuf.next = NIL THEN
  941. (* 2 buffers *)
  942. ASSERT(rcvbuf.prev.next = rcvbuf);
  943. ASSERT(p.rcvtail = rcvbuf);
  944. ELSE
  945. (* check chain (more than 2 buffers *)
  946. REPEAT
  947. ASSERT(rcvbuf.next.prev = rcvbuf);
  948. ASSERT(rcvbuf.prev.next = rcvbuf);
  949. rcvbuf := rcvbuf.next;
  950. UNTIL rcvbuf.next = NIL;
  951. (* last buffer *)
  952. ASSERT(p.rcvtail = rcvbuf);
  953. END;
  954. END;
  955. END;
  956. (* send buffers *)
  957. sndbuf := p.sndhead; found := FALSE;
  958. LOOP
  959. found := found OR (sndbuf = p.sndtail);
  960. sndbuf := sndbuf.next;
  961. ASSERT(sndbuf # NIL);
  962. IF sndbuf = p.sndhead THEN EXIT END;
  963. ASSERT(~found OR ((sndbuf.ofs = 0) & (sndbuf.len = 0)))
  964. END;
  965. ASSERT(found);
  966. END
  967. END Invariant;
  968. (* Hash function for ConnectionPool *)
  969. PROCEDURE HashPool(lport, fport: LONGINT; fip:IP.Adr): LONGINT;
  970. VAR
  971. i: LONGINT;
  972. hash: LONGINT;
  973. BEGIN
  974. (* hash := (lport + fport + fip) MOD HashTableSize; *)
  975. hash := lport + fport;
  976. CASE fip.usedProtocol OF
  977. IP.IPv4:
  978. INC(hash, fip.ipv4Adr);
  979. |IP.IPv6:
  980. FOR i := 0 TO 15 DO
  981. INC(hash, ORD(fip.ipv6Adr[i]));
  982. END;
  983. ELSE
  984. END;
  985. RETURN hash MOD HashTableSize;
  986. END HashPool;
  987. (*
  988. (* Hash function for ConnectionPool. *)
  989. PROCEDURE -HashPool(lport, fport: LONGINT; fip: IP.Adr): LONGINT;
  990. CODE {SYSTEM.i386}
  991. (* hash := (lport + fport + fip) MOD HashTableSize; *)
  992. POP ECX
  993. POP EBX
  994. POP EAX
  995. ; Convert IP to host byte order
  996. XCHG CL, CH
  997. ROL ECX, 16
  998. XCHG CL, CH
  999. ; Calculate sum
  1000. ADD EAX, EBX
  1001. ADD EAX, ECX
  1002. ; MOD operation
  1003. MOV EBX, HashTableSize
  1004. XOR EDX, EDX
  1005. DIV EBX
  1006. MOV EAX, EDX
  1007. END HashPool;
  1008. *)
  1009. (* Set x to val, but keep it between min and max. *)
  1010. PROCEDURE RangeSet(VAR x: LONGINT; val, min, max: LONGINT);
  1011. BEGIN
  1012. IF val < min THEN x := min
  1013. ELSIF val > max THEN x := max
  1014. ELSE x := val
  1015. END
  1016. END RangeSet;
  1017. PROCEDURE WriteTime(t: LONGINT);
  1018. VAR s: ARRAY 8 OF CHAR;
  1019. BEGIN
  1020. KernelLog.Int(t DIV Kernel.second, 1);
  1021. s[0] := "."; t := (t MOD Kernel.second)*1000 DIV Kernel.second;
  1022. s[1] := CHR(48+t DIV 100 MOD 10); s[2] := CHR(48+t DIV 10 MOD 10);
  1023. s[3] := CHR(48+t MOD 10); s[4] := 0X;
  1024. KernelLog.String(s)
  1025. END WriteTime;
  1026. (* TCP error function. *)
  1027. PROCEDURE Error(err: WORD; n: LONGINT; p: Connection);
  1028. BEGIN
  1029. IF trace THEN
  1030. KernelLog.Enter; KernelLog.String("TCP: "); WriteTime(Kernel.GetTicks());
  1031. KernelLog.String(" result "); KernelLog.Int(err, 1);
  1032. KernelLog.Char(" "); KernelLog.Int(n, 1); KernelLog.Exit
  1033. END;
  1034. IF TraceError & (p # NIL) THEN TraceTCP("", p, empty^, empty^, 0, 0, 0) END;
  1035. Machine.AtomicInc(NTCPError[0]); Machine.AtomicInc(NTCPError[err-MinError])
  1036. END Error;
  1037. (* Calculate and store new value for persist timer. *)
  1038. PROCEDURE SetPersist(p: Connection);
  1039. BEGIN
  1040. ASSERT(p.timer[ReXmt] = 0);
  1041. RangeSet(p.timer[Persist], (p.srtt DIV 4 + p.rttvar) DIV 2 * backoff[p.rxtshift], PersMin, PersMax);
  1042. IF p.rxtshift < MaxRxtShift THEN INC(p.rxtshift) END
  1043. END SetPersist;
  1044. (* Trace Connection fields. *)
  1045. PROCEDURE TraceConnection(p: Connection);
  1046. VAR i: LONGINT;
  1047. BEGIN
  1048. IF Trace THEN
  1049. KernelLog.String(" state=");
  1050. CASE p.state OF
  1051. Closed: KernelLog.String("Closed")
  1052. |Listen: KernelLog.String("Listen")
  1053. |SynSent: KernelLog.String("SynSent")
  1054. |SynReceived: KernelLog.String("SynReceived")
  1055. |Established: KernelLog.String("Established")
  1056. |CloseWait: KernelLog.String("CloseWait")
  1057. |FinWait1: KernelLog.String("FinWait1")
  1058. |Closing: KernelLog.String("Closing")
  1059. |LastAck: KernelLog.String("LastAck")
  1060. |FinWait2: KernelLog.String("FinWait2")
  1061. |TimeWait: KernelLog.String("TimeWait")
  1062. END;
  1063. KernelLog.String(" maxseg="); KernelLog.Int(p.maxseg, 1);
  1064. KernelLog.String(" flags={");
  1065. IF AckNow IN p.flags THEN KernelLog.String(" AckNow") END;
  1066. IF DelAck IN p.flags THEN KernelLog.String(" DelAck") END;
  1067. IF NoDelay IN p.flags THEN KernelLog.String(" NoDelay") END;
  1068. IF SentFin IN p.flags THEN KernelLog.String(" SentFin") END;
  1069. IF Force IN p.flags THEN KernelLog.String(" Force") END;
  1070. IF RcvdScale IN p.flags THEN KernelLog.String(" RcvdScale") END;
  1071. IF RcvdTstmp IN p.flags THEN KernelLog.String(" RcvdTstmp") END;
  1072. IF ReqScale IN p.flags THEN KernelLog.String(" ReqScale") END;
  1073. IF ReqTstmp IN p.flags THEN KernelLog.String(" ReqTstmp") END;
  1074. IF DoKeepAlive IN p.flags THEN KernelLog.String(" DoKeepAlive") END;
  1075. IF AcceptConn IN p.flags THEN KernelLog.String(" AcceptConn") END;
  1076. FOR i := 11 TO 31 DO
  1077. IF i IN p.flags THEN KernelLog.Char(" "); KernelLog.Int(i, 1) END
  1078. END;
  1079. KernelLog.String(" } error="); KernelLog.Int(p.error, 1);
  1080. KernelLog.Ln;
  1081. KernelLog.String(" iss="); KernelLog.Int(p.iss, 1);
  1082. KernelLog.String(" snduna="); KernelLog.Int(p.snduna-p.iss, 1);
  1083. KernelLog.String(" sndnxt="); KernelLog.Int(p.sndnxt-p.iss, 1);
  1084. KernelLog.String(" sndmax="); KernelLog.Int(p.sndmax-p.iss, 1);
  1085. KernelLog.String(" sndup="); KernelLog.Int(p.sndup-p.iss, 1);
  1086. KernelLog.String(" sndwl2="); KernelLog.Int(p.sndwl2-p.iss, 1);
  1087. KernelLog.String(" rtseq="); KernelLog.Int(p.rtseq-p.iss, 1);
  1088. KernelLog.Ln;
  1089. KernelLog.String(" sndwnd="); KernelLog.Int(p.sndwnd, 1);
  1090. KernelLog.String(" sndcwnd="); KernelLog.Int(p.sndcwnd, 1);
  1091. KernelLog.String(" sndcc="); KernelLog.Int(p.sndcc, 1);
  1092. KernelLog.String(" sndspace="); KernelLog.Int(p.sndspace, 1);
  1093. KernelLog.String(" sndssthresh="); KernelLog.Int(p.sndssthresh, 1);
  1094. KernelLog.Ln;
  1095. KernelLog.String(" irs="); KernelLog.Int(p.irs, 1);
  1096. KernelLog.String(" rcvnxt="); KernelLog.Int(p.rcvnxt-p.irs, 1);
  1097. KernelLog.String(" rcvup="); KernelLog.Int(p.rcvup-p.irs, 1);
  1098. KernelLog.String(" sndwl1="); KernelLog.Int(p.sndwl1-p.irs, 1);
  1099. KernelLog.String(" rcvadv="); KernelLog.Int(p.rcvadv-p.irs, 1);
  1100. KernelLog.String(" lastacksent="); KernelLog.Int(p.lastacksent-p.irs, 1);
  1101. KernelLog.Ln;
  1102. KernelLog.String(" rcvwnd="); KernelLog.Int(p.rcvwnd, 1);
  1103. KernelLog.String(" rcvspace="); KernelLog.Int(p.rcvspace, 1);
  1104. KernelLog.String(" rcvhiwat="); KernelLog.Int(p.rcvhiwat, 1);
  1105. KernelLog.String(" idle="); KernelLog.Int(p.idle, 1);
  1106. KernelLog.String(" rtt="); KernelLog.Int(p.rtt, 1);
  1107. KernelLog.String(" srtt="); KernelLog.Int(p.srtt, 1);
  1108. KernelLog.Ln;
  1109. KernelLog.String(" rttvar="); KernelLog.Int(p.rttvar, 1);
  1110. KernelLog.String(" rttmin="); KernelLog.Int(p.rttmin, 1);
  1111. KernelLog.String(" maxsndwnd="); KernelLog.Int(p.maxsndwnd, 1);
  1112. KernelLog.String(" sndscale="); KernelLog.Int(p.sndscale, 1);
  1113. KernelLog.String(" rcvscale="); KernelLog.Int(p.rcvscale, 1);
  1114. KernelLog.String(" requestrscale="); KernelLog.Int(p.requestrscale, 1);
  1115. KernelLog.Ln;
  1116. KernelLog.String(" requestedsscale="); KernelLog.Int(p.requestedsscale, 1);
  1117. KernelLog.String(" tsrecent="); KernelLog.Int(p.tsrecent, 1);
  1118. KernelLog.String(" tsrecentage="); KernelLog.Int(p.tsrecentage, 1);
  1119. KernelLog.String(" rxtshift="); KernelLog.Int(p.rxtshift, 1);
  1120. KernelLog.String(" rxtcur="); KernelLog.Int(p.rxtcur, 1);
  1121. KernelLog.String(" dupacks="); KernelLog.Int(p.dupacks, 1);
  1122. KernelLog.Ln; KernelLog.Ln
  1123. END
  1124. END TraceConnection;
  1125. (* Trace the protocol. *)
  1126. PROCEDURE TraceTCP(msg: ARRAY OF CHAR; p: Connection; CONST hdr, data: ARRAY OF CHAR; hlen, ofs, len: LONGINT);
  1127. BEGIN
  1128. IF Trace THEN
  1129. WriteTime(Kernel.GetTicks()); KernelLog.Char(" ");
  1130. KernelLog.String(msg); TraceConnection(p);
  1131. IF TracePacket THEN
  1132. KernelLog.Memory(ADDRESSOF(hdr[0]), hlen);
  1133. KernelLog.Memory(ADDRESSOF(data[ofs]), len)
  1134. END
  1135. END
  1136. END TraceTCP;
  1137. (* Output a TCP segment. *)
  1138. PROCEDURE Output(p: Connection);
  1139. VAR
  1140. idle, sendalot: BOOLEAN;
  1141. optLen, off, sum, win, len, adv, x, startseq, left: LONGINT;
  1142. pf: SET; buf: SendBuffer; data: SendData;
  1143. pseudoHdr: ARRAY MaxPseudoHdrLen OF CHAR;
  1144. hdr: ARRAY MaxTCPHdrLen OF CHAR;
  1145. pseudoHdrLen: LONGINT;
  1146. BEGIN
  1147. idle := (p.sndmax = p.snduna);
  1148. IF idle & (p.idle >= p.rxtcur) THEN p.sndcwnd := p.maxseg END;
  1149. REPEAT
  1150. sendalot := FALSE;
  1151. LOOP (* look for reason to send a segment (not a real loop, just a goto-substitute) *)
  1152. off := p.sndnxt - p.snduna; (* the first off bytes from the buffer have been sent and are waiting for Ack *)
  1153. win := p.sndwnd; (* minimum of window advertised by receiver and the congestion window *)
  1154. IF HandleCongestion & (p.sndcwnd < win) THEN win := p.sndcwnd END;
  1155. pf := outflags[p.state];
  1156. IF Force IN p.flags THEN
  1157. IF win = 0 THEN
  1158. IF off < p.sndcc THEN EXCL(pf, Fin) END;
  1159. win := 1
  1160. ELSE
  1161. p.timer[Persist] := 0; p.rxtshift := 0
  1162. END
  1163. END;
  1164. len := p.sndcc; (* minimum of bytes in send buffer and win *)
  1165. IF win < len THEN len := win END;
  1166. DEC(len, off); (* off bytes have already been sent and are waiting for Ack *)
  1167. IF len < 0 THEN
  1168. len := 0;
  1169. IF win = 0 THEN p.timer[ReXmt] := 0; p.sndnxt := p.snduna END;
  1170. END;
  1171. IF len > p.maxseg THEN len := p.maxseg; sendalot := TRUE END;
  1172. IF (p.sndnxt + len) - (p.snduna + p.sndcc) < 0 THEN EXCL(pf, Fin) END; (* not emptying send buffer *)
  1173. win := p.rcvspace; (* now win is receive window advertised *)
  1174. IF len # 0 THEN
  1175. IF len = p.maxseg THEN EXIT END;
  1176. IF (idle OR (NoDelay IN p.flags)) & (len + off >= p.sndcc) THEN EXIT END;
  1177. IF Force IN p.flags THEN EXIT END;
  1178. IF len >= p.maxsndwnd DIV 2 THEN EXIT END;
  1179. IF p.sndnxt - p.sndmax < 0 THEN EXIT END
  1180. END;
  1181. IF win > 0 THEN
  1182. adv := ASH(MaxWin, p.rcvscale);
  1183. IF win < adv THEN adv := win END;
  1184. DEC(adv, p.rcvadv - p.rcvnxt);
  1185. IF adv >= 2*p.maxseg THEN EXIT END;
  1186. IF 2*adv >= p.rcvhiwat THEN EXIT END
  1187. END;
  1188. IF AckNow IN p.flags THEN EXIT END;
  1189. IF pf * {Syn,Rst} # {} THEN EXIT END;
  1190. IF p.sndup - p.snduna > 0 THEN EXIT END;
  1191. IF (Fin IN pf) & (~(SentFin IN p.flags) OR (p.sndnxt = p.snduna)) THEN EXIT END;
  1192. IF (p.sndcc # 0) & (p.timer[ReXmt] = 0) & (p.timer[Persist] = 0) THEN
  1193. p.rxtshift := 0; SetPersist(p)
  1194. END;
  1195. RETURN (* 0 *) (* no reason to send a segment *)
  1196. END; (* LOOP *)
  1197. (* form output segment *)
  1198. optLen := 0;
  1199. IF Syn IN pf THEN
  1200. p.sndnxt := p.iss;
  1201. IF GenOptions THEN
  1202. (* generate MSS option *)
  1203. hdr[MinTCPHdrLen+optLen] := 2X; (* MSS option *)
  1204. hdr[MinTCPHdrLen+optLen+1] := 4X; (* option length *)
  1205. Network.PutNet2(hdr, MinTCPHdrLen+optLen+2, p.int.dev.mtu-120); (* MSS = dev.mtu-120 *)
  1206. INC(optLen, 4);
  1207. (* generate window scale option *)
  1208. IF ((ReqScale IN p.flags) & (~(Ack IN pf) OR (RcvdScale IN p.flags))) THEN
  1209. hdr[MinTCPHdrLen+optLen] := 1X; (* NOP *)
  1210. hdr[MinTCPHdrLen+optLen+1] := 3X; (* window scale option *)
  1211. hdr[MinTCPHdrLen+optLen+2] := 3X; (* option length *)
  1212. hdr[MinTCPHdrLen+optLen+3] := CHR(p.requestrscale); (* window scale *)
  1213. INC(optLen, 4);
  1214. END;
  1215. END;
  1216. END;
  1217. (* generate timestamp option *)
  1218. IF GenOptions & DoRFC1323 & (ReqTstmp IN p.flags) & ~(Rst IN pf) & ((pf * {Syn, Ack} = {Syn}) OR (RcvdTstmp IN p.flags)) THEN
  1219. hdr[MinTCPHdrLen+optLen] := 1X; (* NOP *)
  1220. hdr[MinTCPHdrLen+optLen+1] := 1X; (* NOP *)
  1221. hdr[MinTCPHdrLen+optLen+2] := 8X; (* timestamp option *)
  1222. hdr[MinTCPHdrLen+optLen+3] := 0AX; (* option length *)
  1223. Network.PutNet4(hdr, MinTCPHdrLen+optLen+4, timeSource.now);
  1224. Network.PutNet4(hdr, MinTCPHdrLen+optLen+8, p.tsrecent);
  1225. INC(optLen, 12);
  1226. END;
  1227. (* This doesn't work if Fin was set before !! (bug in TCP/IP Illustrated Vol. 2, p. 873, fig. 26.24)
  1228. Solved by setting MSS = 536 - 12 (size of timestamp option) and commenting this out.
  1229. (mvt, 28.02.2004)
  1230. IF len > p.maxseg - optLen THEN
  1231. len := p.maxseg - optLen;
  1232. sendalot := TRUE;
  1233. END;
  1234. *)
  1235. IF len # 0 THEN
  1236. IF (Force IN p.flags) & (len = 1) THEN Machine.AtomicInc(NTCPSendProbe)
  1237. ELSIF p.sndnxt - p.sndmax < 0 THEN Machine.AtomicInc(NTCPReXmtPack); Machine.AtomicAdd(NTCPReXmtByte, len)
  1238. ELSE Machine.AtomicInc(NTCPSendPack); Machine.AtomicAdd(NTCPSendByte, len)
  1239. END;
  1240. IF off + len = p.sndcc THEN INCL(pf, Psh) END;
  1241. (* data to send is in buffer[off..off+len-1] *)
  1242. buf := p.sndhead; WHILE off >= buf.len DO DEC(off, buf.len); buf := buf.next END;
  1243. IF off+len <= buf.len THEN (* all data is this buffer *)
  1244. data := buf.data; INC(off, buf.ofs)
  1245. ELSE (* data is spread over more buffers *)
  1246. Machine.AtomicInc(NTCPSplitBuffer);
  1247. data := p.sndcontig;
  1248. ASSERT(len <= LEN(data^));
  1249. ASSERT(buf.len-off <= len); (* index check *)
  1250. Network.Copy(buf.data^, data^, off+buf.ofs, 0, buf.len-off);
  1251. off := buf.len-off; left := len-off;
  1252. WHILE left # 0 DO
  1253. buf := buf.next; IF left <= buf.len THEN x := left ELSE x := buf.len END;
  1254. ASSERT(off+x <= len); (* index check *)
  1255. Network.Copy(buf.data^, data^, buf.ofs, off, x);
  1256. INC(off, x); DEC(left, x)
  1257. END;
  1258. off := 0
  1259. END
  1260. ELSE
  1261. IF AckNow IN p.flags THEN Machine.AtomicInc(NTCPAcks)
  1262. ELSIF pf * {Syn,Fin,Rst} # {} THEN Machine.AtomicInc(NTCPSendCtrl)
  1263. ELSIF p.sndup - p.snduna > 0 THEN Machine.AtomicInc(NTCPSendUrg)
  1264. ELSE Machine.AtomicInc(NTCPSendWinUp)
  1265. END;
  1266. data := empty; off := 0
  1267. END;
  1268. IF (Fin IN pf) & (SentFin IN p.flags) & (p.sndnxt = p.sndmax) THEN DEC(p.sndnxt) END;
  1269. IF (len # 0) OR (pf * {Syn,Fin} # {}) OR (p.timer[Persist] # 0) THEN
  1270. Network.PutNet4(hdr, 4, p.sndnxt) (* sequence number *)
  1271. ELSE
  1272. Network.PutNet4(hdr, 4, p.sndmax)
  1273. END;
  1274. Network.PutNet4(hdr, 8, p.rcvnxt); (* acknowledgement number *)
  1275. IF (win < p.rcvhiwat DIV 4) & (win < p.maxseg) THEN win := 0 END;
  1276. IF win > ASH(MaxWin, p.rcvscale) THEN win := ASH(MaxWin, p.rcvscale) END;
  1277. IF win < p.rcvadv - p.rcvnxt THEN win := p.rcvadv - p.rcvnxt END;
  1278. Network.PutNet2(hdr, 14, ASH(win, -p.rcvscale));
  1279. IF p.sndup - p.sndnxt > 0 THEN
  1280. x := p.sndup - p.sndnxt;
  1281. IF x > 65535 THEN x := 65535 END;
  1282. Network.PutNet2(hdr, 18, x);
  1283. INCL(pf, Urg)
  1284. ELSE
  1285. p.sndup := p.snduna
  1286. END;
  1287. hdr[13] := CHR(SHORT(SHORT(SYSTEM.VAL(LONGINT, pf))));
  1288. (* set rest of TCP header *)
  1289. Network.PutNet2(hdr, 0, p.lport);
  1290. Network.PutNet2(hdr, 2, p.fport);
  1291. hdr[12] := CHR((MinTCPHdrLen+optLen) DIV 4*10H);
  1292. Network.Put2(hdr, 16, 0); (* checksum := 0; *)
  1293. IF ~(Network.ChecksumTCP IN p.int.dev.calcChecksum) THEN
  1294. (* set pseudo header *)
  1295. pseudoHdrLen := p.int.WritePseudoHeader(pseudoHdr, p.int.localAdr, p.fip, IPTypeTCP, MinTCPHdrLen+optLen+len);
  1296. sum := IP.Checksum1(pseudoHdr, 0, pseudoHdrLen, 0);
  1297. sum := IP.Checksum1(hdr, 0, MinTCPHdrLen+optLen, sum);
  1298. sum := IP.Checksum2(data^, off, len, sum);
  1299. Network.Put2(hdr, 16, sum); (* checksum := sum *)
  1300. END;
  1301. IF ~(Force IN p.flags) OR (p.timer[Persist] = 0) THEN
  1302. startseq := p.sndnxt;
  1303. IF pf * {Syn,Fin} # {} THEN
  1304. IF Syn IN pf THEN INC(p.sndnxt) END;
  1305. IF Fin IN pf THEN INC(p.sndnxt); INCL(p.flags, SentFin) END
  1306. END;
  1307. INC(p.sndnxt, len);
  1308. IF p.sndnxt - p.sndmax > 0 THEN
  1309. p.sndmax := p.sndnxt;
  1310. IF p.rtt = 0 THEN p.rtt := 1; p.rtseq := startseq; Machine.AtomicInc(NTCPSegsTimed) END
  1311. END;
  1312. IF (p.timer[ReXmt] = 0) & (p.sndnxt # p.snduna) THEN
  1313. p.timer[ReXmt] := p.rxtcur;
  1314. IF p.timer[Persist] # 0 THEN p.timer[Persist] := 0; p.rxtshift := 0 END
  1315. END
  1316. ELSIF (p.sndnxt + len) - p.sndmax > 0 THEN
  1317. p.sndmax := p.sndnxt + len
  1318. ELSE (* skip *)
  1319. END;
  1320. IF TraceProtocol THEN
  1321. TraceTCP("Output", p, hdr, data^, MinTCPHdrLen+optLen, off, len)
  1322. END;
  1323. (* Send packet *)
  1324. p.int.Send(IPTypeTCP, p.fip, hdr, data^, MinTCPHdrLen+optLen, off, len, IP.MaxTTL);
  1325. (* old code:
  1326. IP.IPOutput(IP.default, p.hdr, data^, IP.MinIPHdrLen+MinTCPHdrLen, off, len);
  1327. IF FALSE THEN (* error in IPOutput *)
  1328. IF FALSE THEN (* out of buffers *)
  1329. p.sndcwnd := p.maxseg; (* close congestion window *)
  1330. RETURN (* 0 *)
  1331. END;
  1332. IF FALSE & (p.state >= SynReceived) THEN (* host unreachable or network down *)
  1333. (*p.softerror := error;*) RETURN (* 0 *)
  1334. END;
  1335. RETURN (* error *)
  1336. END;
  1337. *)
  1338. Machine.AtomicInc(NTCPSendTotal);
  1339. IF (win > 0) & ((p.rcvnxt + win) - p.rcvadv > 0) THEN p.rcvadv := p.rcvnxt + win END;
  1340. p.lastacksent := p.rcvnxt;
  1341. p.flags := p.flags - {AckNow,DelAck}
  1342. UNTIL ~sendalot;
  1343. (* RETURN 0 *)
  1344. END Output;
  1345. (* Special output function for Rst and KeepAlive packets (fig. 26.34). *)
  1346. PROCEDURE Respond(p: Connection; ack, seq: LONGINT; rf: SET);
  1347. VAR
  1348. win, sum: LONGINT;
  1349. pseudoHdr: ARRAY MaxPseudoHdrLen OF CHAR;
  1350. hdr: ARRAY MaxTCPHdrLen OF CHAR;
  1351. pseudoHdrLen: LONGINT;
  1352. BEGIN
  1353. win := ASH(p.rcvspace, -p.rcvscale); (* zero in nilpcb *)
  1354. IF rf = {} THEN
  1355. (* keepalive probe *)
  1356. INCL(rf, Ack)
  1357. ELSE
  1358. (* Rst segment *)
  1359. END;
  1360. (* set TCP header *)
  1361. Network.PutNet2(hdr, 0, p.lport);
  1362. Network.PutNet2(hdr, 2, p.fport);
  1363. Network.PutNet4(hdr, 4, seq);
  1364. Network.PutNet4(hdr, 8, ack);
  1365. hdr[12] := CHR(MinTCPHdrLen DIV 4*10H);
  1366. hdr[13] := CHR(SHORT(SHORT(SYSTEM.VAL(LONGINT, rf))));
  1367. Network.PutNet2(hdr, 14, win);
  1368. Network.Put2(hdr, 16, 0); (* checksum := 0 *)
  1369. Network.Put2(hdr, 18, 0); (* urgent pointer := 0 *)
  1370. IF ~(Network.ChecksumTCP IN p.int.dev.calcChecksum) THEN
  1371. (* set pseudo header *)
  1372. pseudoHdrLen := p.int.WritePseudoHeader(pseudoHdr, p.int.localAdr, p.fip, IPTypeTCP, MinTCPHdrLen);
  1373. sum := IP.Checksum1(pseudoHdr, 0, pseudoHdrLen, 0);
  1374. sum := IP.Checksum2(hdr, 0, MinTCPHdrLen, sum);
  1375. Network.Put2(hdr, 16, sum); (* checksum := sum; *)
  1376. END;
  1377. p.int.Send(IPTypeTCP, p.fip, hdr, hdr, MinTCPHdrLen, 0, 0, IP.MaxTTL);
  1378. END Respond;
  1379. (* Cancel all timers. *)
  1380. PROCEDURE CancelTimers(p: Connection);
  1381. VAR i: LONGINT;
  1382. BEGIN
  1383. FOR i := 0 TO NumTimers-1 DO p.timer[i] := 0 END
  1384. END CancelTimers;
  1385. (* Apply new RTT measurement to smoothed estimators. *)
  1386. (*
  1387. PROCEDURE XmitTimer(p: Connection; rtt: LONGINT);
  1388. VAR delta: LONGINT;
  1389. BEGIN
  1390. Machine.AtomicInc(NTCPRTTUpdated);
  1391. IF p.srtt # 0 THEN
  1392. delta := rtt - 1 - ASH(p.srtt, -RTTShift);
  1393. INC(p.srtt, delta);
  1394. IF p.srtt <= 0 THEN p.srtt := 1 END;
  1395. IF delta < 0 THEN delta := -delta END;
  1396. DEC(delta, ASH(p.rttvar, -RTTVarShift));
  1397. INC(p.rttvar, delta);
  1398. IF p.rttvar <= 0 THEN p.rttvar := 1 END
  1399. ELSE
  1400. p.srtt := ASH(rtt, RTTShift); p.rttvar := ASH(rtt, RTTVarShift-1)
  1401. END;
  1402. p.rtt := 0; p.rxtshift := 0;
  1403. RangeSet(p.rxtcur, ASH(p.srtt, -RTTShift) + p.rttvar, p.rttmin, ReXmtMax);
  1404. (*p.softerror := 0*)
  1405. END XmitTimer;
  1406. *)
  1407. PROCEDURE XmitTimer(p: Connection; rtt: LONGINT);
  1408. (*
  1409. m -> rtt
  1410. sa -> p.srtt
  1411. sd -> p.rttvar
  1412. *)
  1413. VAR delta: LONGINT;
  1414. BEGIN
  1415. Machine.AtomicInc(NTCPRTTUpdated);
  1416. IF p.srtt # 0 THEN
  1417. (* delta := (rtt*4) - ASH(p.srtt, -RTTShift);*)
  1418. delta := rtt - 1 - ASH(p.srtt, -RTTShift);
  1419. INC(p.srtt, delta);
  1420. IF p.srtt <= 0 THEN p.srtt := 1 END;
  1421. IF delta < 0 THEN delta := -delta END;
  1422. DEC(delta, ASH(p.rttvar, -RTTVarShift));
  1423. INC(p.rttvar, delta);
  1424. IF p.rttvar <= 0 THEN p.rttvar := 1 END
  1425. ELSE
  1426. p.srtt := ASH(rtt, RTTShift); p.rttvar := ASH(rtt, RTTVarShift-1)
  1427. END;
  1428. p.rtt := 0; p.rxtshift := 0;
  1429. (* p.rxtcur:=((p.srtt DIV 8)+ p.rttvar) DIV 4;
  1430. IF p.rxtcur < (rtt+2) THEN p.rxtcur:=rtt; END;*)
  1431. RangeSet(p.rxtcur, ASH(p.srtt, -RTTShift) + p.rttvar, MinTime, ReXmtMax);
  1432. (*p.softerror := 0*)
  1433. END XmitTimer;
  1434. (* Drop len bytes from the front of the send buffer. *)
  1435. PROCEDURE SbDrop(p: Connection; len: LONGINT);
  1436. VAR buf: SendBuffer;
  1437. BEGIN
  1438. DEC(p.sndcc, len); INC(p.sndspace, len);
  1439. buf := p.sndhead;
  1440. LOOP
  1441. IF buf.len > len THEN (* part of buffer will remain *)
  1442. INC(buf.ofs, len); DEC(buf.len, len); (* ignore buf.seq (later: why?) *)
  1443. EXIT
  1444. END;
  1445. DEC(len, buf.len);
  1446. buf.ofs := 0; buf.len := 0; (* make buffer ready for re-use *)
  1447. IF buf # p.sndtail THEN buf := buf.next END;
  1448. IF len = 0 THEN EXIT END
  1449. END;
  1450. p.sndhead := buf
  1451. END SbDrop;
  1452. (* Close a connection (fig. 27.4-6). *)
  1453. PROCEDURE CloseConnection(p: Connection);
  1454. VAR
  1455. buf: Network.Buffer;
  1456. BEGIN
  1457. IF FALSE (* we sent enough data to update rtt in route *) THEN
  1458. END;
  1459. pool.Remove(p);
  1460. (* can not remove from parent's accept list, because of possible deadlock *)
  1461. IF p = lastpcb THEN lastpcb := nilpcb END; (* only for GC -- race does not matter *)
  1462. (* can not clear any pcb pointer fields, because Lookup is non-exclusive *)
  1463. (*SoIsDisconnected(p);*)
  1464. p.state := Closed;
  1465. (* return the buffers still in receive queue *)
  1466. p.rcvreasm := NIL;
  1467. p.rcvtail := NIL;
  1468. WHILE p.rcvhead # NIL DO
  1469. buf := p.rcvhead;
  1470. p.rcvhead := p.rcvhead.next;
  1471. Network.ReturnBuffer(buf);
  1472. END;
  1473. Machine.AtomicInc(NTCPClosed);
  1474. END CloseConnection;
  1475. (* Drop a connection (fig. 27.2). *)
  1476. PROCEDURE Drop(p: Connection; err: LONGINT);
  1477. BEGIN
  1478. IF p.state >= SynReceived THEN
  1479. p.state := Closed; Output(p); Machine.AtomicInc(NTCPDrops)
  1480. ELSE
  1481. Machine.AtomicInc(NTCPConnDrops)
  1482. END;
  1483. (* IF (err = TimedOut) & (p.softerror # Ok) THEN err := p.softerror END; *)
  1484. p.error := err; CloseConnection(p)
  1485. END Drop;
  1486. PROCEDURE SetMSS(p: Connection; mss: LONGINT);
  1487. (* Error(NIYMSS, 0, p); *)
  1488. (* Processing of received MSS option not necessary as long as sending is always done with MSS=536. *)
  1489. END SetMSS;
  1490. (* Process a received TCP segment. *)
  1491. PROCEDURE Input(int: IP.Interface; type: LONGINT; fip, lip: IP.Adr; buffer: Network.Buffer);
  1492. VAR
  1493. lport, fport, hdrLen: LONGINT;
  1494. p: Connection;
  1495. BEGIN
  1496. ASSERT(type = IPTypeTCP);
  1497. Machine.AtomicInc(NTCPRcvTotal);
  1498. IF IP.AdrsEqual(int.localAdr, lip) THEN
  1499. IF buffer.len >= MinTCPHdrLen THEN
  1500. hdrLen := LONG(ORD(buffer.data[buffer.ofs+12])) DIV 10H * 4;
  1501. IF (hdrLen < MinTCPHdrLen) OR (hdrLen > buffer.len) THEN
  1502. (* bad header length *)
  1503. Error(BadHeaderLength, hdrLen, NIL);
  1504. (*GotoDrop;*)
  1505. ELSE
  1506. (* findpcb *)
  1507. p := lastpcb;
  1508. fport := Network.GetNet2(buffer.data, buffer.ofs);
  1509. lport := Network.GetNet2(buffer.data, buffer.ofs+2);
  1510. IF (p = nilpcb) OR (~IP.AdrsEqual(p.fip, fip)) OR (p.lport # lport) OR (p.fport # fport) THEN
  1511. p := pool.Lookup(lport, fport, fip);
  1512. IF p = nilpcb THEN
  1513. (* look for listening connection *)
  1514. p := pool.Lookup(lport, NilPort, IP.NilAdr);
  1515. END;
  1516. lastpcb := p;
  1517. Machine.AtomicInc(NTCPCacheMiss);
  1518. END;
  1519. p.Input(int, fip, hdrLen, buffer);
  1520. RETURN; (* w/o returning buffer *)
  1521. END;
  1522. ELSE
  1523. Error(SegmentTooSmall, buffer.len, NIL);
  1524. END;
  1525. ELSE
  1526. Error(BroadcastReceived, buffer.len, NIL);
  1527. END;
  1528. Network.ReturnBuffer(buffer);
  1529. END Input;
  1530. (* Process a received TCP segment for the specified Connection. *)
  1531. PROCEDURE ProcessInput(p: Connection; hdrLen: LONGINT; buffer: Network.Buffer; drop: BOOLEAN; VAR bufferQueued: BOOLEAN);
  1532. CONST
  1533. Options = 0; TSPresent = 1; NeedOutput = 2;
  1534. VAR
  1535. win, sum, urp, seq, ack, tsval, tsecr, acked, discard, tlen, optLen: LONGINT;
  1536. pseudoHdr: ARRAY MaxPseudoHdrLen OF CHAR;
  1537. pseudoHdrLen: LONGINT;
  1538. pf, lf: SET;
  1539. reassembledLength: LONGINT;
  1540. fragmentBuffer: Network.Buffer;
  1541. PROCEDURE GotoDrop; (* fig. 29.27 *)
  1542. BEGIN
  1543. IF TraceProtocol THEN TraceTCP("Drop", p, empty^, empty^, 0, 0, 0) END;
  1544. IF drop THEN Drop(p, ConnectionAborted) END
  1545. END GotoDrop;
  1546. PROCEDURE GotoDropReset; (* fig. 29.27 - may be called with p = nilpcb (at start) *)
  1547. BEGIN
  1548. IF (Rst IN pf) THEN
  1549. GotoDrop
  1550. ELSE
  1551. IF Ack IN pf THEN
  1552. Respond(p, 0, ack, {Rst})
  1553. ELSE
  1554. IF Syn IN pf THEN INC(tlen) END;
  1555. Respond(p, seq + tlen, 0, {Rst,Ack})
  1556. END;
  1557. IF drop THEN Drop(p, ConnectionAborted) END
  1558. END
  1559. END GotoDropReset;
  1560. PROCEDURE GotoDropAfterAck; (* fig. 29.26 *)
  1561. BEGIN
  1562. IF Rst IN pf THEN
  1563. GotoDrop
  1564. ELSE
  1565. INCL(p.flags, AckNow); Output(p)
  1566. END
  1567. END GotoDropAfterAck;
  1568. PROCEDURE ProcessOptions; (* fig. 28.9 & 28.10 *)
  1569. VAR opt: CHAR; i, m, optlen: LONGINT;
  1570. BEGIN
  1571. i := buffer.ofs+MinTCPHdrLen; m := buffer.ofs+hdrLen;
  1572. LOOP
  1573. IF i >= m THEN EXIT END;
  1574. opt := buffer.data[i];
  1575. IF opt = 0X THEN
  1576. EXIT; (* EOL *)
  1577. ELSIF opt = 1X THEN
  1578. optlen := 1; (* NOP *)
  1579. ELSE
  1580. optlen := ORD(buffer.data[i+1]);
  1581. IF optlen = 0 THEN EXIT END;
  1582. END;
  1583. CASE opt OF
  1584. 2X: (* MaxSeg *)
  1585. IF (optlen = 4) & (Syn IN pf) THEN
  1586. SetMSS(p, Network.GetNet2(buffer.data, i+2));
  1587. END;
  1588. |3X: (* Window Scaling *)
  1589. IF (optlen = 3) & (Syn IN pf) THEN
  1590. INCL(p.flags, RcvdScale);
  1591. p.requestedsscale := MIN(LONG(ORD(buffer.data[i+2])), MaxWinShift);
  1592. END;
  1593. |8X: (* Timestamp *)
  1594. IF DoRFC1323 & (optlen = 10) THEN
  1595. INCL(lf, TSPresent);
  1596. tsval := Network.GetNet4(buffer.data, i+2);
  1597. tsecr := Network.GetNet4(buffer.data, i+6);
  1598. IF Syn IN pf THEN
  1599. INCL(p.flags, RcvdTstmp);
  1600. p.tsrecent := tsval;
  1601. p.tsrecentage := timeSource.now;
  1602. END;
  1603. END;
  1604. ELSE
  1605. (* skip *)
  1606. END;
  1607. INC(i, optlen);
  1608. END
  1609. END ProcessOptions;
  1610. PROCEDURE ProcessListen(): BOOLEAN; (* fig. 28.15-17 *)
  1611. VAR
  1612. res: WORD;
  1613. q: Connection;
  1614. BEGIN
  1615. IF Rst IN pf THEN GotoDrop; RETURN FALSE END;
  1616. IF Ack IN pf THEN GotoDropReset; RETURN FALSE END;
  1617. IF ~(Syn IN pf) THEN GotoDrop; RETURN FALSE END;
  1618. pool.Add(p, Network.GetNet2(buffer.data, buffer.ofs+2), Network.GetNet2(buffer.data, buffer.ofs), res);
  1619. IF res # Ok THEN
  1620. GotoDrop;
  1621. RETURN FALSE;
  1622. END;
  1623. IF ProcOptions & (Options IN lf) THEN ProcessOptions END;
  1624. p.iss := issSource.Get();
  1625. p.snduna := p.iss; p.sndnxt := p.iss; p.sndmax := p.iss; p.sndup := p.iss;
  1626. p.irs := seq; p.rcvnxt := seq+1; p.rcvadv := p.rcvnxt;
  1627. INCL(p.flags, AckNow);
  1628. p.state := SynReceived;
  1629. p.timer[Keep] := KeepInit;
  1630. drop := FALSE; (* commit *)
  1631. (* put on accept queue *)
  1632. ASSERT(Objects.LockedByCurrent(p.parent)); (* came here via Connection.Input of parent *)
  1633. q := p.parent.acceptNext; p.acceptNext := NIL;
  1634. IF q = NIL THEN
  1635. p.parent.acceptNext := p
  1636. ELSE
  1637. WHILE q.acceptNext # NIL DO q := q.acceptNext END; (* find last entry in queue *)
  1638. q.acceptNext := p
  1639. END;
  1640. Machine.AtomicInc(NTCPAccepts);
  1641. RETURN TRUE
  1642. END ProcessListen;
  1643. PROCEDURE ProcessSynSent(): BOOLEAN;
  1644. BEGIN
  1645. IF (Ack IN pf) & ((ack - p.iss <= 0) OR (ack - p.sndmax > 0)) THEN GotoDropReset; RETURN FALSE END;
  1646. IF Rst IN pf THEN
  1647. IF Ack IN pf THEN Error(ConnectionRefused, 0, p); Drop(p, ConnectionRefused) END;
  1648. GotoDrop; RETURN FALSE
  1649. END;
  1650. IF ~(Syn IN pf) THEN GotoDrop; RETURN FALSE END;
  1651. IF Ack IN pf THEN
  1652. p.snduna := ack;
  1653. IF p.sndnxt - p.snduna < 0 THEN p.sndnxt := p.snduna END;
  1654. END;
  1655. p.timer[ReXmt] := 0;
  1656. p.irs := seq; p.rcvnxt := seq+1; p.rcvadv := p.rcvnxt;
  1657. INCL(p.flags, AckNow);
  1658. IF (Ack IN pf) & (p.snduna - p.iss > 0) THEN
  1659. Machine.AtomicInc(NTCPConnects); (*SoIsConnected(p);*)
  1660. p.state := Established;
  1661. IF p.flags * {RcvdScale,ReqScale} = {RcvdScale,ReqScale} THEN
  1662. p.sndscale := p.requestedsscale; p.rcvscale := p.requestrscale
  1663. END;
  1664. (*GotoPresent;*) (* not necessary, processed later *)
  1665. IF p.rtt # 0 THEN XmitTimer(p, p.rtt) END
  1666. ELSE
  1667. p.state := SynReceived
  1668. END;
  1669. RETURN TRUE
  1670. END ProcessSynSent;
  1671. PROCEDURE Trim1; (* fig. 28.21 *)
  1672. BEGIN
  1673. INC(seq);
  1674. IF tlen > p.rcvwnd THEN
  1675. Error(DataBeyondWindow1, tlen - p.rcvwnd, p); (* data received beyond window (with Syn) *)
  1676. tlen := p.rcvwnd; EXCL(pf, Fin)
  1677. END;
  1678. p.sndwl1 := seq-1; p.rcvup := seq
  1679. END Trim1;
  1680. PROCEDURE Paws(): BOOLEAN; (* fig. 28.22 *)
  1681. BEGIN
  1682. IF (TSPresent IN lf) & ~(Rst IN pf) & (p.tsrecent # 0) & (tsval - p.tsrecent < 0) THEN
  1683. IF (timeSource.now - p.tsrecentage) > PawsIdle THEN
  1684. p.tsrecent := 0
  1685. ELSE
  1686. Error(DuplicateSegmentPAWS, tlen, p); (* duplicate segment (PAWS) *)
  1687. GotoDropAfterAck; RETURN FALSE
  1688. END
  1689. END;
  1690. RETURN TRUE
  1691. END Paws;
  1692. PROCEDURE Trim2(todrop: LONGINT): BOOLEAN; (* fig. 28.24-25, corrected fig. 28.30*)
  1693. BEGIN
  1694. IF Syn IN pf THEN
  1695. EXCL(pf, Syn); INC(seq);
  1696. IF urp > 1 THEN DEC(urp) ELSE EXCL(pf, Urg) END;
  1697. DEC(todrop)
  1698. END;
  1699. IF (todrop > tlen) OR ((todrop = tlen) & ~(Fin IN pf)) THEN
  1700. EXCL(pf, Fin); INCL(p.flags, AckNow); todrop := tlen;
  1701. Error(DuplicateSegment, todrop, p) (* duplicate segment *)
  1702. ELSE
  1703. Error(DuplicatePartialSegment, todrop, p) (* partially duplicate segment *)
  1704. END;
  1705. INC(discard, todrop); INC(seq, todrop); DEC(tlen, todrop);
  1706. IF urp > todrop THEN DEC(urp, todrop) ELSE EXCL(pf, Urg); urp := 0 END;
  1707. RETURN TRUE
  1708. END Trim2;
  1709. PROCEDURE Trim3(todrop: LONGINT): BOOLEAN; (* fig. 28.29 *)
  1710. BEGIN
  1711. IF todrop >= tlen THEN
  1712. IF (Syn IN pf) & (p.state = TimeWait) & (seq - p.rcvnxt > 0) THEN
  1713. (*iss := p.rcvnxt + ISSInc; CloseConnection(p); goto findpcb*)
  1714. Error(NIYNewIncarnation, 0, p); (* new incarnation NIY - also read p. 945-946 *)
  1715. GotoDropAfterAck; RETURN FALSE
  1716. END;
  1717. IF (p.rcvwnd = 0) & (seq = p.rcvnxt) THEN
  1718. INCL(p.flags, AckNow); Machine.AtomicInc(NTCPRcvWinProbe)
  1719. ELSE
  1720. Error(DataBeyondWindow2, tlen, p); (* data received beyond window (complete) *)
  1721. GotoDropAfterAck; RETURN FALSE
  1722. END
  1723. ELSE
  1724. Error(DataBeyondWindow3, todrop, p) (* data received beyond window (partial) *)
  1725. END;
  1726. DEC(tlen, todrop); pf := pf - {Psh,Fin};
  1727. RETURN TRUE
  1728. END Trim3;
  1729. PROCEDURE RecordTS; (* fig. 28.35 *)
  1730. VAR x: LONGINT;
  1731. BEGIN
  1732. IF DoRFC1323 THEN
  1733. IF pf * {Syn,Fin} # {} THEN x := 1 ELSE x := 0 END;
  1734. IF p.lastacksent - (seq + tlen + x) < 0 THEN
  1735. p.tsrecentage := timeSource.now;
  1736. p.tsrecent := tsval;
  1737. END
  1738. END
  1739. END RecordTS;
  1740. PROCEDURE ProcessRst(): BOOLEAN; (* fig. 28.36 *)
  1741. BEGIN
  1742. CASE p.state OF
  1743. SynReceived, Established, FinWait1, FinWait2, CloseWait:
  1744. IF p.state = SynReceived THEN p.error := ConnectionRefused ELSE p.error := ConnectionReset END;
  1745. p.state := Closed; Error(p.error, 0, p); (* connection reset *)
  1746. CloseConnection(p); GotoDrop; RETURN FALSE
  1747. |Closing, LastAck:
  1748. CloseConnection(p); GotoDrop; RETURN FALSE
  1749. ELSE (* skip *)
  1750. END;
  1751. RETURN TRUE
  1752. END ProcessRst;
  1753. PROCEDURE ProcessAck(): BOOLEAN; (* fig. 29.2-29.14 *)
  1754. VAR onxt, cw, incr: LONGINT; finacked: BOOLEAN;
  1755. BEGIN
  1756. IF p.state IN {SynReceived..TimeWait} THEN
  1757. IF p.state = SynReceived THEN
  1758. IF (p.snduna - ack > 0) OR (ack - p.sndmax > 0) THEN
  1759. GotoDropReset; RETURN FALSE
  1760. END;
  1761. Machine.AtomicInc(NTCPConnects);
  1762. (*SoIsConnected(p);*)
  1763. p.state := Established;
  1764. IF p.flags * {RcvdScale,ReqScale} = {RcvdScale,ReqScale} THEN
  1765. p.sndscale := p.requestedsscale; p.rcvscale := p.requestrscale
  1766. END;
  1767. (* IF tlen > 0 THEN (* would inc of twice by the header size *)
  1768. Reasm;
  1769. END; *)
  1770. p.sndwl1 := seq-1;
  1771. END;
  1772. IF ack - p.snduna <= 0 THEN
  1773. IF (tlen = 0) & (win = p.sndwnd) THEN
  1774. Error(DuplicateAck, 0, p); (* duplicate ack *)
  1775. IF (p.timer[ReXmt] = 0) OR (ack # p.snduna) THEN
  1776. p.dupacks := 0
  1777. ELSE
  1778. INC(p.dupacks);
  1779. IF p.dupacks = ReXmtThresh THEN
  1780. onxt := p.sndnxt;
  1781. p.sndssthresh := MAX(MIN(p.sndwnd, p.sndcwnd) DIV 2 DIV p.maxseg, 2) * p.maxseg;
  1782. IF TraceCongestion THEN
  1783. KernelLog.String("DA sndssthresh := "); KernelLog.Int(p.sndssthresh, 1); KernelLog.Ln
  1784. END;
  1785. p.timer[ReXmt] := 0; p.rtt := 0; p.sndnxt := ack; p.sndcwnd := p.maxseg;
  1786. Output(p);
  1787. p.sndcwnd := p.sndssthresh + p.maxseg * p.dupacks;
  1788. IF onxt - p.sndnxt > 0 THEN p.sndnxt := onxt END;
  1789. GotoDrop; RETURN FALSE
  1790. ELSIF p.dupacks > ReXmtThresh THEN
  1791. INC(p.sndcwnd, p.maxseg);
  1792. Output(p);
  1793. GotoDrop; RETURN FALSE
  1794. ELSE (* skip *)
  1795. END
  1796. END
  1797. ELSE
  1798. p.dupacks := 0
  1799. END;
  1800. RETURN TRUE (* skip rest of Ack processing - goto step 6 *)
  1801. END;
  1802. IF (p.dupacks > ReXmtThresh) & (p.sndcwnd > p.sndssthresh) THEN
  1803. p.sndcwnd := p.sndssthresh
  1804. END;
  1805. p.dupacks := 0;
  1806. IF ack - p.sndmax > 0 THEN
  1807. Error(OutOfRangeAck, ack - p.sndmax, p); GotoDropAfterAck;
  1808. RETURN FALSE;
  1809. END;
  1810. acked := ack - p.snduna;
  1811. Machine.AtomicInc(NTCPAckPack); Machine.AtomicAdd(NTCPAckByte, acked);
  1812. IF TSPresent IN lf THEN XmitTimer(p, timeSource.now - tsecr + 1)
  1813. ELSIF (p.rtt # 0) & (ack - p.rtseq > 0) THEN XmitTimer(p, p.rtt)
  1814. ELSE (* skip *)
  1815. END;
  1816. IF ack = p.sndmax THEN p.timer[ReXmt] := 0; INCL(lf, NeedOutput)
  1817. ELSIF p.timer[Persist] = 0 THEN
  1818. p.timer[ReXmt] := p.rxtcur;
  1819. ELSE (* skip *)
  1820. END;
  1821. cw := p.sndcwnd; incr := p.maxseg;
  1822. IF cw > p.sndssthresh THEN incr := incr * incr DIV cw END;
  1823. p.sndcwnd := MIN(cw + incr, ASH(MaxWin, p.sndscale));
  1824. IF acked > p.sndcc THEN
  1825. DEC(p.sndwnd, p.sndcc); SbDrop(p, p.sndcc); finacked := TRUE
  1826. ELSE
  1827. SbDrop(p, acked); DEC(p.sndwnd, acked); finacked := FALSE
  1828. END;
  1829. (*IF Notify IN p.flags THEN SoWakeup(p) END;*)
  1830. p.snduna := ack;
  1831. IF p.sndnxt - p.snduna < 0 THEN p.sndnxt := p.snduna END;
  1832. CASE p.state OF
  1833. FinWait1:
  1834. IF finacked THEN
  1835. (*IF NoMore IN p.flags THEN SoIsDisconnected(p); p.timer[MSL2] := MaxIdle END;*)
  1836. p.timer[MSL2] := MaxIdle; (* otherwise we hang in FinWait2 *)
  1837. p.state := FinWait2
  1838. END
  1839. |Closing:
  1840. IF finacked THEN
  1841. p.state := TimeWait; CancelTimers(p); p.timer[MSL2] := 2 * MSL;
  1842. (*SoIsDisconnected(p)*)
  1843. END
  1844. |LastAck:
  1845. IF finacked THEN
  1846. CloseConnection(p); GotoDrop; RETURN FALSE
  1847. END
  1848. |TimeWait:
  1849. p.timer[MSL2] := 2 * MSL; GotoDropAfterAck; RETURN FALSE
  1850. ELSE (* skip *)
  1851. END (* CASE *)
  1852. END;
  1853. RETURN TRUE
  1854. END ProcessAck;
  1855. PROCEDURE GotoPresent;
  1856. VAR
  1857. buf: Network.Buffer;
  1858. BEGIN
  1859. buf := p.rcvreasm; (* first buffer on reassembly list *)
  1860. IF (p.state >= Established) & (buf # NIL) & (buf.int = p.rcvnxt) THEN
  1861. REPEAT
  1862. DEC(p.rcvspace, buf.len);
  1863. INC(p.rcvnxt, buf.len);
  1864. pf := buf.set * {Fin};
  1865. buf := buf.next;
  1866. UNTIL (buf = NIL) OR (buf.int # p.rcvnxt);
  1867. p.rcvreasm := buf;
  1868. ELSE
  1869. EXCL(pf, Fin);
  1870. END;
  1871. END GotoPresent;
  1872. PROCEDURE Reasm;
  1873. VAR
  1874. pos, last: Network.Buffer;
  1875. lap: LONGINT;
  1876. BEGIN
  1877. buffer.set := pf;
  1878. buffer.int := seq;
  1879. INC(buffer.ofs, hdrLen + discard);
  1880. buffer.len := tlen;
  1881. IF p.rcvhead = NIL THEN
  1882. (* insert into empty queue *)
  1883. buffer.next := NIL;
  1884. buffer.prev := NIL;
  1885. p.rcvhead := buffer;
  1886. p.rcvreasm := buffer;
  1887. p.rcvtail := buffer;
  1888. bufferQueued := TRUE;
  1889. ELSE
  1890. (* go to insert position, insert in front of pos and after last. *)
  1891. pos := p.rcvreasm;
  1892. IF pos = NIL THEN
  1893. (* no reasm part of queue *)
  1894. last := p.rcvtail;
  1895. ELSE
  1896. last := pos.prev;
  1897. WHILE (pos # NIL) & (pos.int < seq) DO
  1898. last := pos;
  1899. pos := pos.next;
  1900. END;
  1901. END;
  1902. IF last # NIL THEN
  1903. (* check for overlap with previous buffer *)
  1904. lap := (last.int + last.len) - seq;
  1905. IF lap > 0 THEN
  1906. (* some overlap - drop new data *)
  1907. IF lap >= tlen THEN
  1908. (* complete duplicate *)
  1909. Error(DataDuplicatePrevComplete, tlen, p);
  1910. RETURN;
  1911. ELSE
  1912. (* partial duplicate *)
  1913. Error(DataDuplicatePrevPartial, lap, p);
  1914. INC(buffer.ofs, lap);
  1915. DEC(buffer.len, lap);
  1916. DEC(tlen, lap);
  1917. INC(seq, lap);
  1918. buffer.int := seq;
  1919. END;
  1920. END;
  1921. END;
  1922. IF pos # NIL THEN
  1923. (* check for overlap with next buffer *)
  1924. lap := (seq + tlen) - pos.int;
  1925. IF lap > 0 THEN
  1926. (* some overlap - drop new data *)
  1927. IF lap >= tlen THEN
  1928. (* complete duplicate *)
  1929. Error(DataDuplicateNextComplete, lap, p);
  1930. RETURN;
  1931. ELSE
  1932. (* partial duplicate *)
  1933. Error(DataDuplicateNextPartial, lap, p);
  1934. DEC(tlen, lap);
  1935. DEC(buffer.len, lap);
  1936. END;
  1937. END;
  1938. END;
  1939. Machine.AtomicInc(NTCPRcvPackSlow);
  1940. Machine.AtomicAdd(NTCPRcvByteSlow, tlen);
  1941. (* insert buffer into correct position in queue *)
  1942. IF pos = NIL THEN
  1943. (* insert at the end of the queue *)
  1944. ASSERT(last = p.rcvtail);
  1945. buffer.next := NIL;
  1946. buffer.prev := last;
  1947. buffer.prev.next := buffer;
  1948. p.rcvtail := buffer;
  1949. IF p.rcvreasm = NIL THEN
  1950. p.rcvreasm := buffer;
  1951. END;
  1952. ELSIF last = NIL THEN
  1953. (* insert at the beginning of the queue *)
  1954. ASSERT((pos = p.rcvhead) & (pos = p.rcvreasm));
  1955. buffer.prev := NIL;
  1956. buffer.next := pos;
  1957. buffer.next.prev := buffer;
  1958. p.rcvhead := buffer;
  1959. p.rcvreasm := buffer;
  1960. ELSE
  1961. (* insert somewhere in the middle *)
  1962. ASSERT((last.next = pos) & (pos.prev = last));
  1963. last.next := buffer;
  1964. buffer.prev := last;
  1965. pos.prev := buffer;
  1966. buffer.next := pos;
  1967. IF buffer.next = p.rcvreasm THEN
  1968. p.rcvreasm := buffer;
  1969. END;
  1970. END;
  1971. bufferQueued := TRUE;
  1972. END;
  1973. GotoPresent;
  1974. END Reasm;
  1975. PROCEDURE DoData;
  1976. BEGIN
  1977. IF ((tlen # 0) OR (Fin IN pf)) & (p.state < TimeWait) THEN
  1978. IF (seq = p.rcvnxt) & (p.rcvreasm = NIL) & (p.state = Established) THEN
  1979. INCL(p.flags, DelAck)
  1980. ELSE
  1981. INCL(p.flags, AckNow) (* cf. fig. 27.15 *)
  1982. END;
  1983. Reasm();
  1984. ELSE
  1985. EXCL(pf, Fin)
  1986. END;
  1987. IF Fin IN pf THEN
  1988. IF p.state < TimeWait THEN
  1989. (*SoCantRcvMore(p);*)
  1990. INCL(p.flags, AckNow); INC(p.rcvnxt)
  1991. END;
  1992. CASE p.state OF
  1993. SynReceived, Established:
  1994. p.state := CloseWait
  1995. |FinWait1:
  1996. p.state := Closing
  1997. |FinWait2:
  1998. p.state := TimeWait; CancelTimers(p); p.timer[MSL2] := 2 * MSL;
  1999. (*SoIsDisconnected(p)*)
  2000. |TimeWait:
  2001. p.timer[MSL2] := 2 * MSL
  2002. ELSE (* skip *)
  2003. END (* CASE *)
  2004. END;
  2005. IF TraceProtocol THEN
  2006. TraceTCP("Input", p, buffer.data, empty^, buffer.ofs+hdrLen, 0, 0)
  2007. END;
  2008. IF (NeedOutput IN lf) OR (AckNow IN p.flags) THEN Output(p) END
  2009. END DoData;
  2010. PROCEDURE Step6(): BOOLEAN;
  2011. BEGIN
  2012. IF (Ack IN pf) & ((p.sndwl1 - seq < 0) OR ((p.sndwl1 = seq) & ((p.sndwl2 - ack < 0) OR
  2013. ((p.sndwl2 = ack) & (win > p.sndwnd))))) THEN
  2014. IF (tlen = 0) & (p.sndwl2 = ack) & (win > p.sndwnd) THEN Machine.AtomicInc(NTCPRcvWinUpd) END;
  2015. p.sndwnd := win; p.sndwl1 := seq; p.sndwl2 := ack;
  2016. IF p.sndwnd > p.maxsndwnd THEN p.maxsndwnd := p.sndwnd END;
  2017. INCL(lf, NeedOutput)
  2018. END;
  2019. IF (Urg IN pf) & (urp # 0) & (p.state < TimeWait) THEN
  2020. Error(NIYOutOfBand, 0, p); (* out-of-band data NIY *)
  2021. (*IF urp + p.rcvcc > sbmax THEN*)
  2022. urp := 0; EXCL(pf, Urg); DoData; RETURN FALSE;
  2023. (*END;*)
  2024. ELSE
  2025. IF p.rcvnxt - p.rcvup > 0 THEN p.rcvup := p.rcvnxt END
  2026. END;
  2027. RETURN TRUE
  2028. END Step6;
  2029. BEGIN
  2030. lf := {};
  2031. discard := 0; (* data from 0 to discard has to be thrown away. *)
  2032. tlen := buffer.len-hdrLen; (* length of user data. *)
  2033. optLen := hdrLen - MinTCPHdrLen; (* length of options *)
  2034. pf := SYSTEM.VAL(SET, LONG(ORD(buffer.data[buffer.ofs+13])));
  2035. IF optLen > 0 THEN (* TCP options present *)
  2036. Machine.AtomicInc(NTCPRcvOptions);
  2037. IF ProcOptions THEN
  2038. IF DoRFC1323 THEN
  2039. (* quick processing of timestamp option, fig. 28.4 *)
  2040. IF ((optLen = 12) OR ((optLen > 12) & (buffer.data[buffer.ofs+MinTCPHdrLen+12] = 0X))) & ~(Syn IN pf) &
  2041. (buffer.data[buffer.ofs+MinTCPHdrLen] = 1X) &
  2042. (buffer.data[buffer.ofs+MinTCPHdrLen+1] = 1X) &
  2043. (buffer.data[buffer.ofs+MinTCPHdrLen+2] = 8X) &
  2044. (buffer.data[buffer.ofs+MinTCPHdrLen+3] = 0AX) THEN
  2045. INCL(lf, TSPresent);
  2046. tsval := Network.GetNet4(buffer.data, buffer.ofs+MinTCPHdrLen+4);
  2047. tsecr := Network.GetNet4(buffer.data, buffer.ofs+MinTCPHdrLen+8);
  2048. ELSE
  2049. INCL(lf, Options);
  2050. END;
  2051. ELSE
  2052. INCL(lf, Options);
  2053. END
  2054. END
  2055. END;
  2056. (* initialize variables needed for GotoDropReset *)
  2057. seq := Network.GetNet4(buffer.data, buffer.ofs+4);
  2058. ack := Network.GetNet4(buffer.data, buffer.ofs+8);
  2059. (* pf := SYSTEM.VAL(SET, LONG(ORD(buffer.data[buffer.ofs+13])));*)
  2060. IF p = nilpcb THEN
  2061. IF packetDumpListener # NIL THEN packetDumpListener(p.fip, buffer) END;
  2062. GotoDropReset; RETURN
  2063. END;
  2064. IF p.state <= Closed THEN GotoDrop; RETURN END;
  2065. IF ~(Network.ChecksumTCP IN buffer.calcChecksum) THEN
  2066. (* calculate checksum *)
  2067. (* set pseudo header *)
  2068. reassembledLength := 0;
  2069. fragmentBuffer := buffer;
  2070. WHILE fragmentBuffer # NIL DO
  2071. INC(reassembledLength, fragmentBuffer.len);
  2072. fragmentBuffer := fragmentBuffer.nextFragment;
  2073. END;
  2074. pseudoHdrLen := p.int.WritePseudoHeader(pseudoHdr, p.fip, p.int.localAdr, IPTypeTCP, reassembledLength);
  2075. sum := IP.Checksum1(pseudoHdr, 0, pseudoHdrLen, 0);
  2076. IF buffer.nextFragment # NIL THEN
  2077. (* fragmented packets *)
  2078. fragmentBuffer := buffer;
  2079. WHILE fragmentBuffer.nextFragment # NIL DO
  2080. sum := IP.Checksum1(fragmentBuffer.data, fragmentBuffer.ofs, fragmentBuffer.len, sum);
  2081. fragmentBuffer := fragmentBuffer.nextFragment;
  2082. END;
  2083. sum := IP.Checksum2(fragmentBuffer.data, fragmentBuffer.ofs, fragmentBuffer.len, sum);
  2084. ELSE
  2085. sum := IP.Checksum2(buffer.data, buffer.ofs, buffer.len, sum);
  2086. END;
  2087. IF sum # 0 THEN
  2088. Error(BadChecksum, 0, p);
  2089. GotoDrop;
  2090. RETURN;
  2091. END;
  2092. END;
  2093. win := Network.GetNet2(buffer.data, buffer.ofs+14);
  2094. urp := Network.GetNet2(buffer.data, buffer.ofs+18);
  2095. IF ~(Syn IN pf) THEN win := ASH(win, p.sndscale) END;
  2096. p.idle := 0; p.timer[Keep] := KeepIdle;
  2097. IF ProcOptions & (Options IN lf) & (p.state # Listen) THEN ProcessOptions END;
  2098. (* header prediction (fig. 28.11-13) *)
  2099. IF (p.state = Established) & (pf * {Syn,Fin,Rst,Urg,Ack} = {Ack}) &
  2100. (~DoRFC1323 OR ~(TSPresent IN lf) OR (tsval - p.tsrecent >= 0)) & (seq = p.rcvnxt) &
  2101. (win # 0) & (win = p.sndwnd) & (p.sndnxt = p.sndmax) THEN
  2102. IF DoRFC1323 & (TSPresent IN lf) & (seq - p.lastacksent <= 0) THEN
  2103. p.tsrecentage := timeSource.now;
  2104. p.tsrecent := tsval; (* see p. 937 & fig. 26.20 *)
  2105. END;
  2106. IF tlen = 0 THEN
  2107. IF (ack - p.snduna > 0) & (ack - p.sndmax <= 0) & (p.sndcwnd >= p.sndwnd) & (p.dupacks < ReXmtThresh) THEN
  2108. (* p.dupacks < ReXmtThres fix from "Performance Problems in 4.4BSD TCP" *)
  2109. Machine.AtomicInc(NTCPPredAck);
  2110. IF DoRFC1323 & (TSPresent IN lf) THEN XmitTimer(p, timeSource.now - tsecr + 1)
  2111. ELSIF (p.rtt # 0) & (ack - p.rtseq > 0) THEN XmitTimer(p, p.rtt)
  2112. ELSE (* skip *)
  2113. END;
  2114. acked := ack - p.snduna;
  2115. Machine.AtomicInc(NTCPAckPack); Machine.AtomicAdd(NTCPAckByte, acked);
  2116. SbDrop(p, acked);
  2117. p.snduna := ack;
  2118. IF ack = p.sndmax THEN p.timer[ReXmt] := 0
  2119. ELSIF p.timer[Persist] = 0 THEN
  2120. p.timer[ReXmt] := p.rxtcur;
  2121. ELSE (* skip *)
  2122. END;
  2123. (*IF Notify IN p.flags THEN SoWakeup(p) END;*)
  2124. IF p.sndcc # 0 THEN Output(p) END;
  2125. RETURN
  2126. END
  2127. ELSIF (ack = p.snduna) & (p.rcvreasm = NIL) & (tlen <= p.rcvspace) THEN
  2128. Machine.AtomicInc(NTCPPredData);
  2129. Machine.AtomicInc(NTCPRcvPackFast);
  2130. Machine.AtomicAdd(NTCPRcvByteFast, tlen);
  2131. (* can assume no overlap with last or next buffers *)
  2132. Reasm; (* queue the buffer directly *)
  2133. (*SoWakeup(p);*)
  2134. INCL(p.flags, DelAck);
  2135. RETURN
  2136. ELSE
  2137. (* skip - continue to slow path *)
  2138. END
  2139. END;
  2140. (* slow path *)
  2141. p.rcvwnd := MAX(MAX(p.rcvspace, 0), p.rcvadv - p.rcvnxt);
  2142. CASE p.state OF
  2143. Listen:
  2144. IF ProcessListen() THEN Trim1 ELSE RETURN END
  2145. |SynSent:
  2146. IF ProcessSynSent() THEN Trim1 ELSE RETURN END
  2147. ELSE
  2148. IF DoRFC1323 & ~Paws() THEN RETURN END;
  2149. IF (p.rcvnxt - seq > 0) & ~Trim2(p.rcvnxt - seq) THEN RETURN END;
  2150. (*IF (Gone IN p.flags) & (p.state > CloseWait) & (tlen # 0) THEN
  2151. CloseConnection(p); Machine.AtomicInc(NTCPRcvAfterClose); GotoDropReset; RETURN
  2152. END;*)
  2153. IF ((seq + tlen) - (p.rcvnxt + p.rcvwnd) > 0) & ~Trim3((seq + tlen) - (p.rcvnxt + p.rcvwnd)) THEN RETURN END;
  2154. IF DoRFC1323 & (TSPresent IN lf) & (seq - p.lastacksent <= 0) THEN RecordTS END;
  2155. IF (Rst IN pf) & ~ProcessRst() THEN RETURN END;
  2156. IF Syn IN pf THEN Drop(p, ConnectionReset); GotoDropReset; RETURN END;
  2157. IF ~(Ack IN pf) THEN GotoDrop; RETURN END;
  2158. IF ~ProcessAck() THEN RETURN END;
  2159. END; (* CASE *)
  2160. IF ~Step6() THEN RETURN END;
  2161. DoData;
  2162. END ProcessInput;
  2163. (* Initialize a new Connection. *)
  2164. PROCEDURE InitConnection(p: Connection);
  2165. VAR
  2166. buf: SendBuffer;
  2167. BEGIN
  2168. IF ~NewZeros THEN (* clear all fields *)
  2169. CancelTimers(p);
  2170. p.fip := IP.NilAdr; p.fport := NilPort; p.rxtshift := 0; p.dupacks := 0;
  2171. p.snduna := 0; p.sndnxt := 0; p.sndup := 0; p.sndwl1 := 0; p.sndwl2 := 0; p.iss := 0;
  2172. p.sndwnd := 0; p.rcvwnd := 0; p.rcvnxt := 0; p.rcvup := 0; p.irs := 0; p.rcvadv := 0;
  2173. p.sndmax := 0; p.idle := 0; p.rtt := 0; p.rtseq := 0; p.maxsndwnd := 0;
  2174. p.sndscale := 0; p.rcvscale := 0; p.requestrscale := 0; p.requestedsscale := 0;
  2175. p.tsrecent := 0; p.tsrecentage := 0; p.lastacksent := 0; p.error := 0; p.acceptable := 0;
  2176. p.sndcc := 0; p.poolNext := NIL; p.parent := NIL; p.acceptNext := NIL
  2177. END;
  2178. (* initialize fields *)
  2179. p.maxseg := MSS; p.state := Closed;
  2180. IF DoRFC1323 THEN p.flags := {ReqScale,ReqTstmp} ELSE p.flags := {} END;
  2181. p.srtt := SRTTBase; p.rttvar := SRTTDflt * 4; p.rttmin := MinTime;
  2182. RangeSet(p.rxtcur, (SRTTBase DIV 4 + SRTTDflt * 4) DIV 2, MinTime, ReXmtMax);
  2183. p.sndcwnd := ASH(MaxWin, MaxWinShift);
  2184. p.sndssthresh := ASH(MaxWin, MaxWinShift);
  2185. p.sndspace := MaxSendSpace;
  2186. p.rcvspace := MaxRecvSpace;
  2187. p.rcvhiwat := MaxRecvSpace;
  2188. WHILE (p.requestrscale < MaxWinShift) & (ASH(MaxWin, p.requestrscale) < p.rcvhiwat) DO
  2189. INC(p.requestrscale)
  2190. END;
  2191. Machine.AtomicInc(NTCPNewBufs);
  2192. (* allocate send buffer *)
  2193. NEW(buf); NEW(buf.data, MSS * SegsPerBuf);
  2194. IF ~NewZeros THEN buf.ofs := 0; buf.len := 0; END;
  2195. buf.next := buf; p.sndhead := buf; p.sndtail := buf;
  2196. NEW(p.sndcontig, MSS);
  2197. (* init receive buffer *)
  2198. p.rcvhead := NIL;
  2199. END InitConnection;
  2200. (* Move connection to next state in close process. *)
  2201. PROCEDURE UsrClosed(p: Connection);
  2202. BEGIN
  2203. CASE p.state OF
  2204. Closed, Listen, SynSent:
  2205. p.state := Closed; CloseConnection(p)
  2206. |SynReceived, Established:
  2207. p.state := FinWait1
  2208. |CloseWait:
  2209. p.state := LastAck
  2210. ELSE (* skip *)
  2211. END;
  2212. (*IF p.state >= FinWait2 THEN SoIsDisconnected(p) END*)
  2213. END UsrClosed;
  2214. (* If t is not zero, decrement it. Return true if it has reached 0, false otherwise. *)
  2215. PROCEDURE Expired(VAR t: LONGINT): BOOLEAN;
  2216. BEGIN
  2217. IF t # 0 THEN DEC(t); RETURN t = 0 ELSE RETURN FALSE END
  2218. END Expired;
  2219. PROCEDURE GetID(): LONGINT;
  2220. VAR id, time, date: LONGINT;
  2221. BEGIN
  2222. Clock.Get(time, date);
  2223. id := SYSTEM.VAL(LONGINT, SYSTEM.VAL(SET, time) / SYSTEM.VAL(SET, date));
  2224. RETURN id;
  2225. END GetID;
  2226. (** Aos command - display all errors *)
  2227. PROCEDURE DisplayErrors*(context : Commands.Context);
  2228. VAR i: LONGINT;
  2229. BEGIN
  2230. FOR i := 1 TO NumErrors-1 DO
  2231. IF NTCPError[i] # 0 THEN
  2232. context.out.String("TCP: Error "); context.out.Int(i+MinError, 1);
  2233. context.out.String(" "); context.out.Int(NTCPError[i], 1); context.out.Ln;
  2234. END;
  2235. END;
  2236. END DisplayErrors;
  2237. (** Aos command - discard and finalize all connections *)
  2238. PROCEDURE DiscardAll*;
  2239. BEGIN
  2240. pool.Finalize();
  2241. END DiscardAll;
  2242. (** Temporary trace procedure. *)
  2243. PROCEDURE ToggleTrace*;
  2244. BEGIN
  2245. trace := ~trace;
  2246. KernelLog.Enter; KernelLog.String("TCP trace ");
  2247. IF trace THEN KernelLog.String("on") ELSE KernelLog.String("off") END;
  2248. KernelLog.Exit
  2249. END ToggleTrace;
  2250. PROCEDURE Init;
  2251. VAR i: LONGINT;
  2252. BEGIN
  2253. FOR i := 0 TO MaxRxtShift DO
  2254. IF i < 6 THEN backoff[i] := ASH(1, i) ELSE backoff[i] := 64 END;
  2255. INC(totbackoff, backoff[i])
  2256. END;
  2257. (* maxdiff := 0;*)
  2258. (* backoff[0]:=1;
  2259. backoff[1]:=1;
  2260. backoff[2]:=2;
  2261. backoff[3]:=3;
  2262. backoff[4]:=5;
  2263. backoff[5]:=10;
  2264. backoff[6]:=18;
  2265. backoff[7]:=30;
  2266. backoff[8]:=60;
  2267. backoff[9]:=120;
  2268. backoff[10]:=240;
  2269. backoff[11]:=240;
  2270. backoff[12]:=240;*)
  2271. ASSERT(MaxRxtShift=12);
  2272. totbackoff := 0;
  2273. FOR i:=0 TO MaxRxtShift DO
  2274. INC(totbackoff, backoff[i]);
  2275. END;
  2276. (* Flags used when sending segments in tcp_output. Basic flags {Rst, Ack, Syn, Fin} are totally determined by state, with the proviso that Fin is sent only if all data queued for output is included in the segment. The {Psh,Urg} flags are set as necessary.
  2277. *)
  2278. outflags[Closed] := {Rst,Ack}; outflags[Listen] := {}; outflags[SynSent] := {Syn};
  2279. outflags[SynReceived] := {Syn,Ack}; outflags[Established] := {Ack};
  2280. outflags[CloseWait] := {Ack}; outflags[FinWait1] := {Fin,Ack}; outflags[Closing] := {Fin,Ack};
  2281. outflags[LastAck] := {Fin,Ack}; outflags[FinWait2] := {Ack}; outflags[TimeWait] := {Ack};
  2282. (* other globals *)
  2283. NEW(nilpcb);
  2284. nilpcb.lport := -1; (* can never match *)
  2285. nilpcb.int := NIL;
  2286. IF ~NewZeros THEN nilpcb.rcvspace := 0; nilpcb.rcvscale := 0 END; (* for Respond *)
  2287. lastpcb := nilpcb;
  2288. NEW(empty, 1);
  2289. NEW(pool);
  2290. NEW(issSource, GetID());
  2291. NEW(timeSource)
  2292. END Init;
  2293. PROCEDURE Cleanup;
  2294. BEGIN
  2295. IP.RemoveReceiver(IPTypeTCP);
  2296. pool.Finalize();
  2297. timeSource.Finalize();
  2298. END Cleanup;
  2299. BEGIN
  2300. ASSERT(~DoRFC1323 OR (ProcOptions & GenOptions)); (* constants should make sense *)
  2301. ASSERT(SYSTEM.VAL(LONGINT, {Fin}) = 1); (* bit order for flags cast in Input, Output and Respond *)
  2302. ASSERT((TimerPeriod MOD FastPeriod = 0) & (TimerPeriod MOD SlowPeriod = 0));
  2303. trace := FALSE;
  2304. Init();
  2305. IP.InstallReceiver(IPTypeTCP, Input);
  2306. Modules.InstallTermHandler(Cleanup);
  2307. END TCP.
  2308. (*
  2309. History:
  2310. 08.11.2003 mvt Changed for new interface of IP and Network.
  2311. 08.11.2003 mvt Fixed array position error in ProcessOptions().
  2312. 09.11.2003 mvt Min()/Max() functions now in inline assembler.
  2313. 10.11.2003 mvt Added InterfaceClosed detection in Connection.SlowTimer().
  2314. 10.11.2003 mvt Added correct finalization of Connection, ConnectionPool, Timer and the module itself.
  2315. 11.11.2003 mvt Completely changed receive buffer queueing, integrated Network buffers directly.
  2316. 12.11.2003 mvt Completely changed ConnectionPool, now working with a hash table.
  2317. 12.12.2003 mvt Bugfixed entire module by comparing it with the book.
  2318. 12.12.2003 mvt Completed header prediction code according to the book.
  2319. 12.12.2003 mvt Added support for RFC1323 (timestamp, PAWS).
  2320. 12.12.2003 mvt Added support for window scaling (for windows >64KB).
  2321. 14.02.2004 mvt Fixed reassembly bug in Reasm().
  2322. 14.02.2004 mvt Fixed MSS option sending bug in Output().
  2323. 28.02.2004 mvt Fixed early Fin sending bug in Output().
  2324. 04.03.2004 rp Fixed & (p.dupacks < ReXmtThresh) in Step6 according to ftp://ftp.cs.arizona.edu/xkernel/papers/tcp_problems.ps
  2325. 04.03.2004 rp Fixed XmitTimer according to ftp://ftp.cs.arizona.edu/xkernel/papers/tcp_problems.ps
  2326. 02.05.2005 eb Supports IPv6 (WritePseudoHdr) and fragmented IP packets.
  2327. *)
  2328. (*
  2329. * Copyright (c) 1982, 1986, 1993
  2330. * The Regents of the University of California. All rights reserved.
  2331. *
  2332. * Redistribution and use in source and binary forms, with or without
  2333. * modification, are permitted provided that the following conditions
  2334. * are met:
  2335. * 1. Redistributions of source code must retain the above copyright
  2336. * notice, this list of conditions and the following disclaimer.
  2337. * 2. Redistributions in binary form must reproduce the above copyright
  2338. * notice, this list of conditions and the following disclaimer in the
  2339. * documentation and/or other materials provided with the distribution.
  2340. * 3. All advertising materials mentioning features or use of this software
  2341. * must display the following acknowledgement:
  2342. * This product includes software developed by the University of
  2343. * California, Berkeley and its contributors.
  2344. * 4. Neither the name of the University nor the names of its contributors
  2345. * may be used to endorse or promote products derived from this software
  2346. * without specific prior written permission.
  2347. *
  2348. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  2349. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  2350. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  2351. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  2352. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  2353. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  2354. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  2355. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  2356. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  2357. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  2358. * SUCH DAMAGE.
  2359. *)
  2360. (* pjm:
  2361. Gigabit:
  2362. Alteon AceNIC / 3Com 3C985 / NetGear GA620 Gigabit Ethernet Adapter
  2363. http://sanjose.alteon.com/open.shtml
  2364. Linux Driver
  2365. http://home.cern.ch/~jes/gige/acenic.html
  2366. Packet Engines Hamachi Driver
  2367. http://www.nscl.msu.edu/~kasten/perf/hamachi/
  2368. A Connection has to react to external and internal events
  2369. 1. User calls (external)
  2370. Connection.Open
  2371. Connection.Send
  2372. Connection.Receive
  2373. Connection.Available
  2374. Connection.Close
  2375. 2. Timer.HandleTimeout (internal)
  2376. Connection.DelayedAck
  2377. Connection.SlowTimer
  2378. 3. Packet arrival (external)
  2379. Connection.Input (from Input)
  2380. The Timer reacts to external and internal events
  2381. 1. Timer.HandleTimeout (external)
  2382. 2. Timer.GetISS (internal - only called from Connection.Open, which is only called externally)
  2383. The ConnectionPool reacts to external and internal events
  2384. 1. Lookup (internal)
  2385. 2. Enumerate (external)
  2386. 3. Add (internal)
  2387. 4. Remove (internal)
  2388. *)