tcp_subr.c 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523
  1. /*-
  2. * SPDX-License-Identifier: BSD-3-Clause
  3. *
  4. * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
  5. * The Regents of the University of California. All rights reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions
  9. * are met:
  10. * 1. Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. * 2. Redistributions in binary form must reproduce the above copyright
  13. * notice, this list of conditions and the following disclaimer in the
  14. * documentation and/or other materials provided with the distribution.
  15. * 3. Neither the name of the University nor the names of its contributors
  16. * may be used to endorse or promote products derived from this software
  17. * without specific prior written permission.
  18. *
  19. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  20. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  21. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  22. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  23. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  24. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  25. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  26. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  27. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  28. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  29. * SUCH DAMAGE.
  30. *
  31. * @(#)tcp_subr.c 8.2 (Berkeley) 5/24/95
  32. */
  33. #include <sys/cdefs.h>
  34. __FBSDID("$FreeBSD$");
  35. #include "opt_inet.h"
  36. #include "opt_inet6.h"
  37. #include "opt_ipsec.h"
  38. #include "opt_kern_tls.h"
  39. #include "opt_tcpdebug.h"
  40. #include <sys/param.h>
  41. #include <sys/systm.h>
  42. #include <sys/arb.h>
  43. #include <sys/callout.h>
  44. #include <sys/eventhandler.h>
  45. #ifdef TCP_HHOOK
  46. #include <sys/hhook.h>
  47. #endif
  48. #include <sys/kernel.h>
  49. #ifdef TCP_HHOOK
  50. #include <sys/khelp.h>
  51. #endif
  52. #ifdef KERN_TLS
  53. #include <sys/ktls.h>
  54. #endif
  55. #include <sys/qmath.h>
  56. #include <sys/stats.h>
  57. #include <sys/sysctl.h>
  58. #include <sys/jail.h>
  59. #include <sys/malloc.h>
  60. #include <sys/refcount.h>
  61. #include <sys/mbuf.h>
  62. #ifdef INET6
  63. #include <sys/domain.h>
  64. #endif
  65. #include <sys/priv.h>
  66. #include <sys/proc.h>
  67. #include <sys/sdt.h>
  68. #include <sys/socket.h>
  69. #include <sys/socketvar.h>
  70. #include <sys/protosw.h>
  71. #include <sys/random.h>
  72. #include <vm/uma.h>
  73. #include <net/route.h>
  74. #include <net/route/nhop.h>
  75. #include <net/if.h>
  76. #include <net/if_var.h>
  77. #include <net/vnet.h>
  78. #include <netinet/in.h>
  79. #include <netinet/in_fib.h>
  80. #include <netinet/in_kdtrace.h>
  81. #include <netinet/in_pcb.h>
  82. #include <netinet/in_systm.h>
  83. #include <netinet/in_var.h>
  84. #include <netinet/ip.h>
  85. #include <netinet/ip_icmp.h>
  86. #include <netinet/ip_var.h>
  87. #ifdef INET6
  88. #include <netinet/icmp6.h>
  89. #include <netinet/ip6.h>
  90. #include <netinet6/in6_fib.h>
  91. #include <netinet6/in6_pcb.h>
  92. #include <netinet6/ip6_var.h>
  93. #include <netinet6/scope6_var.h>
  94. #include <netinet6/nd6.h>
  95. #endif
  96. #include <netinet/tcp.h>
  97. #include <netinet/tcp_fsm.h>
  98. #include <netinet/tcp_seq.h>
  99. #include <netinet/tcp_timer.h>
  100. #include <netinet/tcp_var.h>
  101. #include <netinet/tcp_log_buf.h>
  102. #include <netinet/tcp_syncache.h>
  103. #include <netinet/tcp_hpts.h>
  104. #include <netinet/cc/cc.h>
  105. #ifdef INET6
  106. #include <netinet6/tcp6_var.h>
  107. #endif
  108. #include <netinet/tcpip.h>
  109. #include <netinet/tcp_fastopen.h>
  110. #ifdef TCPPCAP
  111. #include <netinet/tcp_pcap.h>
  112. #endif
  113. #ifdef TCPDEBUG
  114. #include <netinet/tcp_debug.h>
  115. #endif
  116. #ifdef INET6
  117. #include <netinet6/ip6protosw.h>
  118. #endif
  119. #ifdef TCP_OFFLOAD
  120. #include <netinet/tcp_offload.h>
  121. #endif
  122. #include <netipsec/ipsec_support.h>
  123. #include <machine/in_cksum.h>
  124. #include <crypto/siphash/siphash.h>
  125. #include <security/mac/mac_framework.h>
  126. VNET_DEFINE(int, tcp_mssdflt) = TCP_MSS;
  127. #ifdef INET6
  128. VNET_DEFINE(int, tcp_v6mssdflt) = TCP6_MSS;
  129. #endif
  130. #ifdef NETFLIX_EXP_DETECTION
  131. /* Sack attack detection thresholds and such */
  132. SYSCTL_NODE(_net_inet_tcp, OID_AUTO, sack_attack,
  133. CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
  134. "Sack Attack detection thresholds");
  135. int32_t tcp_force_detection = 0;
  136. SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, force_detection,
  137. CTLFLAG_RW,
  138. &tcp_force_detection, 0,
  139. "Do we force detection even if the INP has it off?");
  140. int32_t tcp_sack_to_ack_thresh = 700; /* 70 % */
  141. SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, sack_to_ack_thresh,
  142. CTLFLAG_RW,
  143. &tcp_sack_to_ack_thresh, 700,
  144. "Percentage of sacks to acks we must see above (10.1 percent is 101)?");
  145. int32_t tcp_sack_to_move_thresh = 600; /* 60 % */
  146. SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, move_thresh,
  147. CTLFLAG_RW,
  148. &tcp_sack_to_move_thresh, 600,
  149. "Percentage of sack moves we must see above (10.1 percent is 101)");
  150. int32_t tcp_restoral_thresh = 650; /* 65 % (sack:2:ack -5%) */
  151. SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, restore_thresh,
  152. CTLFLAG_RW,
  153. &tcp_restoral_thresh, 550,
  154. "Percentage of sack to ack percentage we must see below to restore(10.1 percent is 101)");
  155. int32_t tcp_sad_decay_val = 800;
  156. SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, decay_per,
  157. CTLFLAG_RW,
  158. &tcp_sad_decay_val, 800,
  159. "The decay percentage (10.1 percent equals 101 )");
  160. int32_t tcp_map_minimum = 500;
  161. SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, nummaps,
  162. CTLFLAG_RW,
  163. &tcp_map_minimum, 500,
  164. "Number of Map enteries before we start detection");
  165. int32_t tcp_attack_on_turns_on_logging = 0;
  166. SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, attacks_logged,
  167. CTLFLAG_RW,
  168. &tcp_attack_on_turns_on_logging, 0,
  169. "When we have a positive hit on attack, do we turn on logging?");
  170. int32_t tcp_sad_pacing_interval = 2000;
  171. SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, sad_pacing_int,
  172. CTLFLAG_RW,
  173. &tcp_sad_pacing_interval, 2000,
  174. "What is the minimum pacing interval for a classified attacker?");
  175. int32_t tcp_sad_low_pps = 100;
  176. SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, sad_low_pps,
  177. CTLFLAG_RW,
  178. &tcp_sad_low_pps, 100,
  179. "What is the input pps that below which we do not decay?");
  180. #endif
  181. struct rwlock tcp_function_lock;
  182. static int
  183. sysctl_net_inet_tcp_mss_check(SYSCTL_HANDLER_ARGS)
  184. {
  185. int error, new;
  186. new = V_tcp_mssdflt;
  187. error = sysctl_handle_int(oidp, &new, 0, req);
  188. if (error == 0 && req->newptr) {
  189. if (new < TCP_MINMSS)
  190. error = EINVAL;
  191. else
  192. V_tcp_mssdflt = new;
  193. }
  194. return (error);
  195. }
  196. SYSCTL_PROC(_net_inet_tcp, TCPCTL_MSSDFLT, mssdflt,
  197. CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
  198. &VNET_NAME(tcp_mssdflt), 0, &sysctl_net_inet_tcp_mss_check, "I",
  199. "Default TCP Maximum Segment Size");
  200. #ifdef INET6
  201. static int
  202. sysctl_net_inet_tcp_mss_v6_check(SYSCTL_HANDLER_ARGS)
  203. {
  204. int error, new;
  205. new = V_tcp_v6mssdflt;
  206. error = sysctl_handle_int(oidp, &new, 0, req);
  207. if (error == 0 && req->newptr) {
  208. if (new < TCP_MINMSS)
  209. error = EINVAL;
  210. else
  211. V_tcp_v6mssdflt = new;
  212. }
  213. return (error);
  214. }
  215. SYSCTL_PROC(_net_inet_tcp, TCPCTL_V6MSSDFLT, v6mssdflt,
  216. CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
  217. &VNET_NAME(tcp_v6mssdflt), 0, &sysctl_net_inet_tcp_mss_v6_check, "I",
  218. "Default TCP Maximum Segment Size for IPv6");
  219. #endif /* INET6 */
  220. /*
  221. * Minimum MSS we accept and use. This prevents DoS attacks where
  222. * we are forced to a ridiculous low MSS like 20 and send hundreds
  223. * of packets instead of one. The effect scales with the available
  224. * bandwidth and quickly saturates the CPU and network interface
  225. * with packet generation and sending. Set to zero to disable MINMSS
  226. * checking. This setting prevents us from sending too small packets.
  227. */
  228. VNET_DEFINE(int, tcp_minmss) = TCP_MINMSS;
  229. SYSCTL_INT(_net_inet_tcp, OID_AUTO, minmss, CTLFLAG_VNET | CTLFLAG_RW,
  230. &VNET_NAME(tcp_minmss), 0,
  231. "Minimum TCP Maximum Segment Size");
  232. VNET_DEFINE(int, tcp_do_rfc1323) = 1;
  233. SYSCTL_INT(_net_inet_tcp, TCPCTL_DO_RFC1323, rfc1323, CTLFLAG_VNET | CTLFLAG_RW,
  234. &VNET_NAME(tcp_do_rfc1323), 0,
  235. "Enable rfc1323 (high performance TCP) extensions");
  236. VNET_DEFINE(int, tcp_tolerate_missing_ts) = 0;
  237. SYSCTL_INT(_net_inet_tcp, OID_AUTO, tolerate_missing_ts, CTLFLAG_VNET | CTLFLAG_RW,
  238. &VNET_NAME(tcp_tolerate_missing_ts), 0,
  239. "Tolerate missing TCP timestamps");
  240. VNET_DEFINE(int, tcp_ts_offset_per_conn) = 1;
  241. SYSCTL_INT(_net_inet_tcp, OID_AUTO, ts_offset_per_conn, CTLFLAG_VNET | CTLFLAG_RW,
  242. &VNET_NAME(tcp_ts_offset_per_conn), 0,
  243. "Initialize TCP timestamps per connection instead of per host pair");
  244. static int tcp_log_debug = 0;
  245. SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_debug, CTLFLAG_RW,
  246. &tcp_log_debug, 0, "Log errors caused by incoming TCP segments");
  247. static int tcp_tcbhashsize;
  248. SYSCTL_INT(_net_inet_tcp, OID_AUTO, tcbhashsize, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
  249. &tcp_tcbhashsize, 0, "Size of TCP control-block hashtable");
  250. static int do_tcpdrain = 1;
  251. SYSCTL_INT(_net_inet_tcp, OID_AUTO, do_tcpdrain, CTLFLAG_RW, &do_tcpdrain, 0,
  252. "Enable tcp_drain routine for extra help when low on mbufs");
  253. SYSCTL_UINT(_net_inet_tcp, OID_AUTO, pcbcount, CTLFLAG_VNET | CTLFLAG_RD,
  254. &VNET_NAME(tcbinfo.ipi_count), 0, "Number of active PCBs");
  255. VNET_DEFINE_STATIC(int, icmp_may_rst) = 1;
  256. #define V_icmp_may_rst VNET(icmp_may_rst)
  257. SYSCTL_INT(_net_inet_tcp, OID_AUTO, icmp_may_rst, CTLFLAG_VNET | CTLFLAG_RW,
  258. &VNET_NAME(icmp_may_rst), 0,
  259. "Certain ICMP unreachable messages may abort connections in SYN_SENT");
  260. VNET_DEFINE_STATIC(int, tcp_isn_reseed_interval) = 0;
  261. #define V_tcp_isn_reseed_interval VNET(tcp_isn_reseed_interval)
  262. SYSCTL_INT(_net_inet_tcp, OID_AUTO, isn_reseed_interval, CTLFLAG_VNET | CTLFLAG_RW,
  263. &VNET_NAME(tcp_isn_reseed_interval), 0,
  264. "Seconds between reseeding of ISN secret");
  265. static int tcp_soreceive_stream;
  266. SYSCTL_INT(_net_inet_tcp, OID_AUTO, soreceive_stream, CTLFLAG_RDTUN,
  267. &tcp_soreceive_stream, 0, "Using soreceive_stream for TCP sockets");
  268. VNET_DEFINE(uma_zone_t, sack_hole_zone);
  269. #define V_sack_hole_zone VNET(sack_hole_zone)
  270. VNET_DEFINE(uint32_t, tcp_map_entries_limit) = 0; /* unlimited */
  271. static int
  272. sysctl_net_inet_tcp_map_limit_check(SYSCTL_HANDLER_ARGS)
  273. {
  274. int error;
  275. uint32_t new;
  276. new = V_tcp_map_entries_limit;
  277. error = sysctl_handle_int(oidp, &new, 0, req);
  278. if (error == 0 && req->newptr) {
  279. /* only allow "0" and value > minimum */
  280. if (new > 0 && new < TCP_MIN_MAP_ENTRIES_LIMIT)
  281. error = EINVAL;
  282. else
  283. V_tcp_map_entries_limit = new;
  284. }
  285. return (error);
  286. }
  287. SYSCTL_PROC(_net_inet_tcp, OID_AUTO, map_limit,
  288. CTLFLAG_VNET | CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
  289. &VNET_NAME(tcp_map_entries_limit), 0,
  290. &sysctl_net_inet_tcp_map_limit_check, "IU",
  291. "Total sendmap entries limit");
  292. VNET_DEFINE(uint32_t, tcp_map_split_limit) = 0; /* unlimited */
  293. SYSCTL_UINT(_net_inet_tcp, OID_AUTO, split_limit, CTLFLAG_VNET | CTLFLAG_RW,
  294. &VNET_NAME(tcp_map_split_limit), 0,
  295. "Total sendmap split entries limit");
  296. #ifdef TCP_HHOOK
  297. VNET_DEFINE(struct hhook_head *, tcp_hhh[HHOOK_TCP_LAST+1]);
  298. #endif
  299. #define TS_OFFSET_SECRET_LENGTH SIPHASH_KEY_LENGTH
  300. VNET_DEFINE_STATIC(u_char, ts_offset_secret[TS_OFFSET_SECRET_LENGTH]);
  301. #define V_ts_offset_secret VNET(ts_offset_secret)
  302. static int tcp_default_fb_init(struct tcpcb *tp);
  303. static void tcp_default_fb_fini(struct tcpcb *tp, int tcb_is_purged);
  304. static int tcp_default_handoff_ok(struct tcpcb *tp);
  305. static struct inpcb *tcp_notify(struct inpcb *, int);
  306. static struct inpcb *tcp_mtudisc_notify(struct inpcb *, int);
  307. static void tcp_mtudisc(struct inpcb *, int);
  308. static char * tcp_log_addr(struct in_conninfo *inc, struct tcphdr *th,
  309. void *ip4hdr, const void *ip6hdr);
  310. static struct tcp_function_block tcp_def_funcblk = {
  311. .tfb_tcp_block_name = "freebsd",
  312. .tfb_tcp_output = tcp_output,
  313. .tfb_tcp_do_segment = tcp_do_segment,
  314. .tfb_tcp_ctloutput = tcp_default_ctloutput,
  315. .tfb_tcp_handoff_ok = tcp_default_handoff_ok,
  316. .tfb_tcp_fb_init = tcp_default_fb_init,
  317. .tfb_tcp_fb_fini = tcp_default_fb_fini,
  318. };
  319. static int tcp_fb_cnt = 0;
  320. struct tcp_funchead t_functions;
  321. static struct tcp_function_block *tcp_func_set_ptr = &tcp_def_funcblk;
  322. static struct tcp_function_block *
  323. find_tcp_functions_locked(struct tcp_function_set *fs)
  324. {
  325. struct tcp_function *f;
  326. struct tcp_function_block *blk=NULL;
  327. TAILQ_FOREACH(f, &t_functions, tf_next) {
  328. if (strcmp(f->tf_name, fs->function_set_name) == 0) {
  329. blk = f->tf_fb;
  330. break;
  331. }
  332. }
  333. return(blk);
  334. }
  335. static struct tcp_function_block *
  336. find_tcp_fb_locked(struct tcp_function_block *blk, struct tcp_function **s)
  337. {
  338. struct tcp_function_block *rblk=NULL;
  339. struct tcp_function *f;
  340. TAILQ_FOREACH(f, &t_functions, tf_next) {
  341. if (f->tf_fb == blk) {
  342. rblk = blk;
  343. if (s) {
  344. *s = f;
  345. }
  346. break;
  347. }
  348. }
  349. return (rblk);
  350. }
  351. struct tcp_function_block *
  352. find_and_ref_tcp_functions(struct tcp_function_set *fs)
  353. {
  354. struct tcp_function_block *blk;
  355. rw_rlock(&tcp_function_lock);
  356. blk = find_tcp_functions_locked(fs);
  357. if (blk)
  358. refcount_acquire(&blk->tfb_refcnt);
  359. rw_runlock(&tcp_function_lock);
  360. return(blk);
  361. }
  362. struct tcp_function_block *
  363. find_and_ref_tcp_fb(struct tcp_function_block *blk)
  364. {
  365. struct tcp_function_block *rblk;
  366. rw_rlock(&tcp_function_lock);
  367. rblk = find_tcp_fb_locked(blk, NULL);
  368. if (rblk)
  369. refcount_acquire(&rblk->tfb_refcnt);
  370. rw_runlock(&tcp_function_lock);
  371. return(rblk);
  372. }
  373. static struct tcp_function_block *
  374. find_and_ref_tcp_default_fb(void)
  375. {
  376. struct tcp_function_block *rblk;
  377. rw_rlock(&tcp_function_lock);
  378. rblk = tcp_func_set_ptr;
  379. refcount_acquire(&rblk->tfb_refcnt);
  380. rw_runlock(&tcp_function_lock);
  381. return (rblk);
  382. }
  383. void
  384. tcp_switch_back_to_default(struct tcpcb *tp)
  385. {
  386. struct tcp_function_block *tfb;
  387. KASSERT(tp->t_fb != &tcp_def_funcblk,
  388. ("%s: called by the built-in default stack", __func__));
  389. /*
  390. * Release the old stack. This function will either find a new one
  391. * or panic.
  392. */
  393. if (tp->t_fb->tfb_tcp_fb_fini != NULL)
  394. (*tp->t_fb->tfb_tcp_fb_fini)(tp, 0);
  395. refcount_release(&tp->t_fb->tfb_refcnt);
  396. /*
  397. * Now, we'll find a new function block to use.
  398. * Start by trying the current user-selected
  399. * default, unless this stack is the user-selected
  400. * default.
  401. */
  402. tfb = find_and_ref_tcp_default_fb();
  403. if (tfb == tp->t_fb) {
  404. refcount_release(&tfb->tfb_refcnt);
  405. tfb = NULL;
  406. }
  407. /* Does the stack accept this connection? */
  408. if (tfb != NULL && tfb->tfb_tcp_handoff_ok != NULL &&
  409. (*tfb->tfb_tcp_handoff_ok)(tp)) {
  410. refcount_release(&tfb->tfb_refcnt);
  411. tfb = NULL;
  412. }
  413. /* Try to use that stack. */
  414. if (tfb != NULL) {
  415. /* Initialize the new stack. If it succeeds, we are done. */
  416. tp->t_fb = tfb;
  417. if (tp->t_fb->tfb_tcp_fb_init == NULL ||
  418. (*tp->t_fb->tfb_tcp_fb_init)(tp) == 0)
  419. return;
  420. /*
  421. * Initialization failed. Release the reference count on
  422. * the stack.
  423. */
  424. refcount_release(&tfb->tfb_refcnt);
  425. }
  426. /*
  427. * If that wasn't feasible, use the built-in default
  428. * stack which is not allowed to reject anyone.
  429. */
  430. tfb = find_and_ref_tcp_fb(&tcp_def_funcblk);
  431. if (tfb == NULL) {
  432. /* there always should be a default */
  433. panic("Can't refer to tcp_def_funcblk");
  434. }
  435. if (tfb->tfb_tcp_handoff_ok != NULL) {
  436. if ((*tfb->tfb_tcp_handoff_ok) (tp)) {
  437. /* The default stack cannot say no */
  438. panic("Default stack rejects a new session?");
  439. }
  440. }
  441. tp->t_fb = tfb;
  442. if (tp->t_fb->tfb_tcp_fb_init != NULL &&
  443. (*tp->t_fb->tfb_tcp_fb_init)(tp)) {
  444. /* The default stack cannot fail */
  445. panic("Default stack initialization failed");
  446. }
  447. }
  448. static int
  449. sysctl_net_inet_default_tcp_functions(SYSCTL_HANDLER_ARGS)
  450. {
  451. int error=ENOENT;
  452. struct tcp_function_set fs;
  453. struct tcp_function_block *blk;
  454. memset(&fs, 0, sizeof(fs));
  455. rw_rlock(&tcp_function_lock);
  456. blk = find_tcp_fb_locked(tcp_func_set_ptr, NULL);
  457. if (blk) {
  458. /* Found him */
  459. strcpy(fs.function_set_name, blk->tfb_tcp_block_name);
  460. fs.pcbcnt = blk->tfb_refcnt;
  461. }
  462. rw_runlock(&tcp_function_lock);
  463. error = sysctl_handle_string(oidp, fs.function_set_name,
  464. sizeof(fs.function_set_name), req);
  465. /* Check for error or no change */
  466. if (error != 0 || req->newptr == NULL)
  467. return(error);
  468. rw_wlock(&tcp_function_lock);
  469. blk = find_tcp_functions_locked(&fs);
  470. if ((blk == NULL) ||
  471. (blk->tfb_flags & TCP_FUNC_BEING_REMOVED)) {
  472. error = ENOENT;
  473. goto done;
  474. }
  475. tcp_func_set_ptr = blk;
  476. done:
  477. rw_wunlock(&tcp_function_lock);
  478. return (error);
  479. }
  480. SYSCTL_PROC(_net_inet_tcp, OID_AUTO, functions_default,
  481. CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
  482. NULL, 0, sysctl_net_inet_default_tcp_functions, "A",
  483. "Set/get the default TCP functions");
  484. static int
  485. sysctl_net_inet_list_available(SYSCTL_HANDLER_ARGS)
  486. {
  487. int error, cnt, linesz;
  488. struct tcp_function *f;
  489. char *buffer, *cp;
  490. size_t bufsz, outsz;
  491. bool alias;
  492. cnt = 0;
  493. rw_rlock(&tcp_function_lock);
  494. TAILQ_FOREACH(f, &t_functions, tf_next) {
  495. cnt++;
  496. }
  497. rw_runlock(&tcp_function_lock);
  498. bufsz = (cnt+2) * ((TCP_FUNCTION_NAME_LEN_MAX * 2) + 13) + 1;
  499. buffer = malloc(bufsz, M_TEMP, M_WAITOK);
  500. error = 0;
  501. cp = buffer;
  502. linesz = snprintf(cp, bufsz, "\n%-32s%c %-32s %s\n", "Stack", 'D',
  503. "Alias", "PCB count");
  504. cp += linesz;
  505. bufsz -= linesz;
  506. outsz = linesz;
  507. rw_rlock(&tcp_function_lock);
  508. TAILQ_FOREACH(f, &t_functions, tf_next) {
  509. alias = (f->tf_name != f->tf_fb->tfb_tcp_block_name);
  510. linesz = snprintf(cp, bufsz, "%-32s%c %-32s %u\n",
  511. f->tf_fb->tfb_tcp_block_name,
  512. (f->tf_fb == tcp_func_set_ptr) ? '*' : ' ',
  513. alias ? f->tf_name : "-",
  514. f->tf_fb->tfb_refcnt);
  515. if (linesz >= bufsz) {
  516. error = EOVERFLOW;
  517. break;
  518. }
  519. cp += linesz;
  520. bufsz -= linesz;
  521. outsz += linesz;
  522. }
  523. rw_runlock(&tcp_function_lock);
  524. if (error == 0)
  525. error = sysctl_handle_string(oidp, buffer, outsz + 1, req);
  526. free(buffer, M_TEMP);
  527. return (error);
  528. }
  529. SYSCTL_PROC(_net_inet_tcp, OID_AUTO, functions_available,
  530. CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT,
  531. NULL, 0, sysctl_net_inet_list_available, "A",
  532. "list available TCP Function sets");
  533. /*
  534. * Exports one (struct tcp_function_info) for each alias/name.
  535. */
  536. static int
  537. sysctl_net_inet_list_func_info(SYSCTL_HANDLER_ARGS)
  538. {
  539. int cnt, error;
  540. struct tcp_function *f;
  541. struct tcp_function_info tfi;
  542. /*
  543. * We don't allow writes.
  544. */
  545. if (req->newptr != NULL)
  546. return (EINVAL);
  547. /*
  548. * Wire the old buffer so we can directly copy the functions to
  549. * user space without dropping the lock.
  550. */
  551. if (req->oldptr != NULL) {
  552. error = sysctl_wire_old_buffer(req, 0);
  553. if (error)
  554. return (error);
  555. }
  556. /*
  557. * Walk the list and copy out matching entries. If INVARIANTS
  558. * is compiled in, also walk the list to verify the length of
  559. * the list matches what we have recorded.
  560. */
  561. rw_rlock(&tcp_function_lock);
  562. cnt = 0;
  563. #ifndef INVARIANTS
  564. if (req->oldptr == NULL) {
  565. cnt = tcp_fb_cnt;
  566. goto skip_loop;
  567. }
  568. #endif
  569. TAILQ_FOREACH(f, &t_functions, tf_next) {
  570. #ifdef INVARIANTS
  571. cnt++;
  572. #endif
  573. if (req->oldptr != NULL) {
  574. bzero(&tfi, sizeof(tfi));
  575. tfi.tfi_refcnt = f->tf_fb->tfb_refcnt;
  576. tfi.tfi_id = f->tf_fb->tfb_id;
  577. (void)strlcpy(tfi.tfi_alias, f->tf_name,
  578. sizeof(tfi.tfi_alias));
  579. (void)strlcpy(tfi.tfi_name,
  580. f->tf_fb->tfb_tcp_block_name, sizeof(tfi.tfi_name));
  581. error = SYSCTL_OUT(req, &tfi, sizeof(tfi));
  582. /*
  583. * Don't stop on error, as that is the
  584. * mechanism we use to accumulate length
  585. * information if the buffer was too short.
  586. */
  587. }
  588. }
  589. KASSERT(cnt == tcp_fb_cnt,
  590. ("%s: cnt (%d) != tcp_fb_cnt (%d)", __func__, cnt, tcp_fb_cnt));
  591. #ifndef INVARIANTS
  592. skip_loop:
  593. #endif
  594. rw_runlock(&tcp_function_lock);
  595. if (req->oldptr == NULL)
  596. error = SYSCTL_OUT(req, NULL,
  597. (cnt + 1) * sizeof(struct tcp_function_info));
  598. return (error);
  599. }
  600. SYSCTL_PROC(_net_inet_tcp, OID_AUTO, function_info,
  601. CTLTYPE_OPAQUE | CTLFLAG_SKIP | CTLFLAG_RD | CTLFLAG_MPSAFE,
  602. NULL, 0, sysctl_net_inet_list_func_info, "S,tcp_function_info",
  603. "List TCP function block name-to-ID mappings");
  604. /*
  605. * tfb_tcp_handoff_ok() function for the default stack.
  606. * Note that we'll basically try to take all comers.
  607. */
  608. static int
  609. tcp_default_handoff_ok(struct tcpcb *tp)
  610. {
  611. return (0);
  612. }
  613. /*
  614. * tfb_tcp_fb_init() function for the default stack.
  615. *
  616. * This handles making sure we have appropriate timers set if you are
  617. * transitioning a socket that has some amount of setup done.
  618. *
  619. * The init() fuction from the default can *never* return non-zero i.e.
  620. * it is required to always succeed since it is the stack of last resort!
  621. */
  622. static int
  623. tcp_default_fb_init(struct tcpcb *tp)
  624. {
  625. struct socket *so;
  626. INP_WLOCK_ASSERT(tp->t_inpcb);
  627. KASSERT(tp->t_state >= 0 && tp->t_state < TCPS_TIME_WAIT,
  628. ("%s: connection %p in unexpected state %d", __func__, tp,
  629. tp->t_state));
  630. /*
  631. * Nothing to do for ESTABLISHED or LISTEN states. And, we don't
  632. * know what to do for unexpected states (which includes TIME_WAIT).
  633. */
  634. if (tp->t_state <= TCPS_LISTEN || tp->t_state >= TCPS_TIME_WAIT)
  635. return (0);
  636. /*
  637. * Make sure some kind of transmission timer is set if there is
  638. * outstanding data.
  639. */
  640. so = tp->t_inpcb->inp_socket;
  641. if ((!TCPS_HAVEESTABLISHED(tp->t_state) || sbavail(&so->so_snd) ||
  642. tp->snd_una != tp->snd_max) && !(tcp_timer_active(tp, TT_REXMT) ||
  643. tcp_timer_active(tp, TT_PERSIST))) {
  644. /*
  645. * If the session has established and it looks like it should
  646. * be in the persist state, set the persist timer. Otherwise,
  647. * set the retransmit timer.
  648. */
  649. if (TCPS_HAVEESTABLISHED(tp->t_state) && tp->snd_wnd == 0 &&
  650. (int32_t)(tp->snd_nxt - tp->snd_una) <
  651. (int32_t)sbavail(&so->so_snd))
  652. tcp_setpersist(tp);
  653. else
  654. tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
  655. }
  656. /* All non-embryonic sessions get a keepalive timer. */
  657. if (!tcp_timer_active(tp, TT_KEEP))
  658. tcp_timer_activate(tp, TT_KEEP,
  659. TCPS_HAVEESTABLISHED(tp->t_state) ? TP_KEEPIDLE(tp) :
  660. TP_KEEPINIT(tp));
  661. /*
  662. * Make sure critical variables are initialized
  663. * if transitioning while in Recovery.
  664. */
  665. if IN_FASTRECOVERY(tp->t_flags) {
  666. if (tp->sackhint.recover_fs == 0)
  667. tp->sackhint.recover_fs = max(1,
  668. tp->snd_nxt - tp->snd_una);
  669. }
  670. return (0);
  671. }
  672. /*
  673. * tfb_tcp_fb_fini() function for the default stack.
  674. *
  675. * This changes state as necessary (or prudent) to prepare for another stack
  676. * to assume responsibility for the connection.
  677. */
  678. static void
  679. tcp_default_fb_fini(struct tcpcb *tp, int tcb_is_purged)
  680. {
  681. INP_WLOCK_ASSERT(tp->t_inpcb);
  682. return;
  683. }
  684. /*
  685. * Target size of TCP PCB hash tables. Must be a power of two.
  686. *
  687. * Note that this can be overridden by the kernel environment
  688. * variable net.inet.tcp.tcbhashsize
  689. */
  690. #ifndef TCBHASHSIZE
  691. #define TCBHASHSIZE 0
  692. #endif
  693. /*
  694. * XXX
  695. * Callouts should be moved into struct tcp directly. They are currently
  696. * separate because the tcpcb structure is exported to userland for sysctl
  697. * parsing purposes, which do not know about callouts.
  698. */
  699. struct tcpcb_mem {
  700. struct tcpcb tcb;
  701. struct tcp_timer tt;
  702. struct cc_var ccv;
  703. #ifdef TCP_HHOOK
  704. struct osd osd;
  705. #endif
  706. };
  707. VNET_DEFINE_STATIC(uma_zone_t, tcpcb_zone);
  708. #define V_tcpcb_zone VNET(tcpcb_zone)
  709. MALLOC_DEFINE(M_TCPLOG, "tcplog", "TCP address and flags print buffers");
  710. MALLOC_DEFINE(M_TCPFUNCTIONS, "tcpfunc", "TCP function set memory");
  711. static struct mtx isn_mtx;
  712. #define ISN_LOCK_INIT() mtx_init(&isn_mtx, "isn_mtx", NULL, MTX_DEF)
  713. #define ISN_LOCK() mtx_lock(&isn_mtx)
  714. #define ISN_UNLOCK() mtx_unlock(&isn_mtx)
  715. /*
  716. * TCP initialization.
  717. */
  718. static void
  719. tcp_zone_change(void *tag)
  720. {
  721. uma_zone_set_max(V_tcbinfo.ipi_zone, maxsockets);
  722. uma_zone_set_max(V_tcpcb_zone, maxsockets);
  723. tcp_tw_zone_change();
  724. }
  725. static int
  726. tcp_inpcb_init(void *mem, int size, int flags)
  727. {
  728. struct inpcb *inp = mem;
  729. INP_LOCK_INIT(inp, "inp", "tcpinp");
  730. return (0);
  731. }
  732. /*
  733. * Take a value and get the next power of 2 that doesn't overflow.
  734. * Used to size the tcp_inpcb hash buckets.
  735. */
  736. static int
  737. maketcp_hashsize(int size)
  738. {
  739. int hashsize;
  740. /*
  741. * auto tune.
  742. * get the next power of 2 higher than maxsockets.
  743. */
  744. hashsize = 1 << fls(size);
  745. /* catch overflow, and just go one power of 2 smaller */
  746. if (hashsize < size) {
  747. hashsize = 1 << (fls(size) - 1);
  748. }
  749. return (hashsize);
  750. }
  751. static volatile int next_tcp_stack_id = 1;
  752. /*
  753. * Register a TCP function block with the name provided in the names
  754. * array. (Note that this function does NOT automatically register
  755. * blk->tfb_tcp_block_name as a stack name. Therefore, you should
  756. * explicitly include blk->tfb_tcp_block_name in the list of names if
  757. * you wish to register the stack with that name.)
  758. *
  759. * Either all name registrations will succeed or all will fail. If
  760. * a name registration fails, the function will update the num_names
  761. * argument to point to the array index of the name that encountered
  762. * the failure.
  763. *
  764. * Returns 0 on success, or an error code on failure.
  765. */
  766. int
  767. register_tcp_functions_as_names(struct tcp_function_block *blk, int wait,
  768. const char *names[], int *num_names)
  769. {
  770. struct tcp_function *n;
  771. struct tcp_function_set fs;
  772. int error, i;
  773. KASSERT(names != NULL && *num_names > 0,
  774. ("%s: Called with 0-length name list", __func__));
  775. KASSERT(names != NULL, ("%s: Called with NULL name list", __func__));
  776. KASSERT(rw_initialized(&tcp_function_lock),
  777. ("%s: called too early", __func__));
  778. if ((blk->tfb_tcp_output == NULL) ||
  779. (blk->tfb_tcp_do_segment == NULL) ||
  780. (blk->tfb_tcp_ctloutput == NULL) ||
  781. (strlen(blk->tfb_tcp_block_name) == 0)) {
  782. /*
  783. * These functions are required and you
  784. * need a name.
  785. */
  786. *num_names = 0;
  787. return (EINVAL);
  788. }
  789. if (blk->tfb_tcp_timer_stop_all ||
  790. blk->tfb_tcp_timer_activate ||
  791. blk->tfb_tcp_timer_active ||
  792. blk->tfb_tcp_timer_stop) {
  793. /*
  794. * If you define one timer function you
  795. * must have them all.
  796. */
  797. if ((blk->tfb_tcp_timer_stop_all == NULL) ||
  798. (blk->tfb_tcp_timer_activate == NULL) ||
  799. (blk->tfb_tcp_timer_active == NULL) ||
  800. (blk->tfb_tcp_timer_stop == NULL)) {
  801. *num_names = 0;
  802. return (EINVAL);
  803. }
  804. }
  805. if (blk->tfb_flags & TCP_FUNC_BEING_REMOVED) {
  806. *num_names = 0;
  807. return (EINVAL);
  808. }
  809. refcount_init(&blk->tfb_refcnt, 0);
  810. blk->tfb_id = atomic_fetchadd_int(&next_tcp_stack_id, 1);
  811. for (i = 0; i < *num_names; i++) {
  812. n = malloc(sizeof(struct tcp_function), M_TCPFUNCTIONS, wait);
  813. if (n == NULL) {
  814. error = ENOMEM;
  815. goto cleanup;
  816. }
  817. n->tf_fb = blk;
  818. (void)strlcpy(fs.function_set_name, names[i],
  819. sizeof(fs.function_set_name));
  820. rw_wlock(&tcp_function_lock);
  821. if (find_tcp_functions_locked(&fs) != NULL) {
  822. /* Duplicate name space not allowed */
  823. rw_wunlock(&tcp_function_lock);
  824. free(n, M_TCPFUNCTIONS);
  825. error = EALREADY;
  826. goto cleanup;
  827. }
  828. (void)strlcpy(n->tf_name, names[i], sizeof(n->tf_name));
  829. TAILQ_INSERT_TAIL(&t_functions, n, tf_next);
  830. tcp_fb_cnt++;
  831. rw_wunlock(&tcp_function_lock);
  832. }
  833. return(0);
  834. cleanup:
  835. /*
  836. * Deregister the names we just added. Because registration failed
  837. * for names[i], we don't need to deregister that name.
  838. */
  839. *num_names = i;
  840. rw_wlock(&tcp_function_lock);
  841. while (--i >= 0) {
  842. TAILQ_FOREACH(n, &t_functions, tf_next) {
  843. if (!strncmp(n->tf_name, names[i],
  844. TCP_FUNCTION_NAME_LEN_MAX)) {
  845. TAILQ_REMOVE(&t_functions, n, tf_next);
  846. tcp_fb_cnt--;
  847. n->tf_fb = NULL;
  848. free(n, M_TCPFUNCTIONS);
  849. break;
  850. }
  851. }
  852. }
  853. rw_wunlock(&tcp_function_lock);
  854. return (error);
  855. }
  856. /*
  857. * Register a TCP function block using the name provided in the name
  858. * argument.
  859. *
  860. * Returns 0 on success, or an error code on failure.
  861. */
  862. int
  863. register_tcp_functions_as_name(struct tcp_function_block *blk, const char *name,
  864. int wait)
  865. {
  866. const char *name_list[1];
  867. int num_names, rv;
  868. num_names = 1;
  869. if (name != NULL)
  870. name_list[0] = name;
  871. else
  872. name_list[0] = blk->tfb_tcp_block_name;
  873. rv = register_tcp_functions_as_names(blk, wait, name_list, &num_names);
  874. return (rv);
  875. }
  876. /*
  877. * Register a TCP function block using the name defined in
  878. * blk->tfb_tcp_block_name.
  879. *
  880. * Returns 0 on success, or an error code on failure.
  881. */
  882. int
  883. register_tcp_functions(struct tcp_function_block *blk, int wait)
  884. {
  885. return (register_tcp_functions_as_name(blk, NULL, wait));
  886. }
  887. /*
  888. * Deregister all names associated with a function block. This
  889. * functionally removes the function block from use within the system.
  890. *
  891. * When called with a true quiesce argument, mark the function block
  892. * as being removed so no more stacks will use it and determine
  893. * whether the removal would succeed.
  894. *
  895. * When called with a false quiesce argument, actually attempt the
  896. * removal.
  897. *
  898. * When called with a force argument, attempt to switch all TCBs to
  899. * use the default stack instead of returning EBUSY.
  900. *
  901. * Returns 0 on success (or if the removal would succeed, or an error
  902. * code on failure.
  903. */
  904. int
  905. deregister_tcp_functions(struct tcp_function_block *blk, bool quiesce,
  906. bool force)
  907. {
  908. struct tcp_function *f;
  909. if (blk == &tcp_def_funcblk) {
  910. /* You can't un-register the default */
  911. return (EPERM);
  912. }
  913. rw_wlock(&tcp_function_lock);
  914. if (blk == tcp_func_set_ptr) {
  915. /* You can't free the current default */
  916. rw_wunlock(&tcp_function_lock);
  917. return (EBUSY);
  918. }
  919. /* Mark the block so no more stacks can use it. */
  920. blk->tfb_flags |= TCP_FUNC_BEING_REMOVED;
  921. /*
  922. * If TCBs are still attached to the stack, attempt to switch them
  923. * to the default stack.
  924. */
  925. if (force && blk->tfb_refcnt) {
  926. struct inpcb *inp;
  927. struct tcpcb *tp;
  928. VNET_ITERATOR_DECL(vnet_iter);
  929. rw_wunlock(&tcp_function_lock);
  930. VNET_LIST_RLOCK();
  931. VNET_FOREACH(vnet_iter) {
  932. CURVNET_SET(vnet_iter);
  933. INP_INFO_WLOCK(&V_tcbinfo);
  934. CK_LIST_FOREACH(inp, V_tcbinfo.ipi_listhead, inp_list) {
  935. INP_WLOCK(inp);
  936. if (inp->inp_flags & INP_TIMEWAIT) {
  937. INP_WUNLOCK(inp);
  938. continue;
  939. }
  940. tp = intotcpcb(inp);
  941. if (tp == NULL || tp->t_fb != blk) {
  942. INP_WUNLOCK(inp);
  943. continue;
  944. }
  945. tcp_switch_back_to_default(tp);
  946. INP_WUNLOCK(inp);
  947. }
  948. INP_INFO_WUNLOCK(&V_tcbinfo);
  949. CURVNET_RESTORE();
  950. }
  951. VNET_LIST_RUNLOCK();
  952. rw_wlock(&tcp_function_lock);
  953. }
  954. if (blk->tfb_refcnt) {
  955. /* TCBs still attached. */
  956. rw_wunlock(&tcp_function_lock);
  957. return (EBUSY);
  958. }
  959. if (quiesce) {
  960. /* Skip removal. */
  961. rw_wunlock(&tcp_function_lock);
  962. return (0);
  963. }
  964. /* Remove any function names that map to this function block. */
  965. while (find_tcp_fb_locked(blk, &f) != NULL) {
  966. TAILQ_REMOVE(&t_functions, f, tf_next);
  967. tcp_fb_cnt--;
  968. f->tf_fb = NULL;
  969. free(f, M_TCPFUNCTIONS);
  970. }
  971. rw_wunlock(&tcp_function_lock);
  972. return (0);
  973. }
  974. void
  975. tcp_init(void)
  976. {
  977. const char *tcbhash_tuneable;
  978. int hashsize;
  979. tcbhash_tuneable = "net.inet.tcp.tcbhashsize";
  980. #ifdef TCP_HHOOK
  981. if (hhook_head_register(HHOOK_TYPE_TCP, HHOOK_TCP_EST_IN,
  982. &V_tcp_hhh[HHOOK_TCP_EST_IN], HHOOK_NOWAIT|HHOOK_HEADISINVNET) != 0)
  983. printf("%s: WARNING: unable to register helper hook\n", __func__);
  984. if (hhook_head_register(HHOOK_TYPE_TCP, HHOOK_TCP_EST_OUT,
  985. &V_tcp_hhh[HHOOK_TCP_EST_OUT], HHOOK_NOWAIT|HHOOK_HEADISINVNET) != 0)
  986. printf("%s: WARNING: unable to register helper hook\n", __func__);
  987. #endif
  988. #ifdef STATS
  989. if (tcp_stats_init())
  990. printf("%s: WARNING: unable to initialise TCP stats\n",
  991. __func__);
  992. #endif
  993. hashsize = TCBHASHSIZE;
  994. TUNABLE_INT_FETCH(tcbhash_tuneable, &hashsize);
  995. if (hashsize == 0) {
  996. /*
  997. * Auto tune the hash size based on maxsockets.
  998. * A perfect hash would have a 1:1 mapping
  999. * (hashsize = maxsockets) however it's been
  1000. * suggested that O(2) average is better.
  1001. */
  1002. hashsize = maketcp_hashsize(maxsockets / 4);
  1003. /*
  1004. * Our historical default is 512,
  1005. * do not autotune lower than this.
  1006. */
  1007. if (hashsize < 512)
  1008. hashsize = 512;
  1009. if (bootverbose && IS_DEFAULT_VNET(curvnet))
  1010. printf("%s: %s auto tuned to %d\n", __func__,
  1011. tcbhash_tuneable, hashsize);
  1012. }
  1013. /*
  1014. * We require a hashsize to be a power of two.
  1015. * Previously if it was not a power of two we would just reset it
  1016. * back to 512, which could be a nasty surprise if you did not notice
  1017. * the error message.
  1018. * Instead what we do is clip it to the closest power of two lower
  1019. * than the specified hash value.
  1020. */
  1021. if (!powerof2(hashsize)) {
  1022. int oldhashsize = hashsize;
  1023. hashsize = maketcp_hashsize(hashsize);
  1024. /* prevent absurdly low value */
  1025. if (hashsize < 16)
  1026. hashsize = 16;
  1027. printf("%s: WARNING: TCB hash size not a power of 2, "
  1028. "clipped from %d to %d.\n", __func__, oldhashsize,
  1029. hashsize);
  1030. }
  1031. in_pcbinfo_init(&V_tcbinfo, "tcp", &V_tcb, hashsize, hashsize,
  1032. "tcp_inpcb", tcp_inpcb_init, IPI_HASHFIELDS_4TUPLE);
  1033. /*
  1034. * These have to be type stable for the benefit of the timers.
  1035. */
  1036. V_tcpcb_zone = uma_zcreate("tcpcb", sizeof(struct tcpcb_mem),
  1037. NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
  1038. uma_zone_set_max(V_tcpcb_zone, maxsockets);
  1039. uma_zone_set_warning(V_tcpcb_zone, "kern.ipc.maxsockets limit reached");
  1040. tcp_tw_init();
  1041. syncache_init();
  1042. tcp_hc_init();
  1043. TUNABLE_INT_FETCH("net.inet.tcp.sack.enable", &V_tcp_do_sack);
  1044. V_sack_hole_zone = uma_zcreate("sackhole", sizeof(struct sackhole),
  1045. NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
  1046. tcp_fastopen_init();
  1047. /* Skip initialization of globals for non-default instances. */
  1048. if (!IS_DEFAULT_VNET(curvnet))
  1049. return;
  1050. tcp_reass_global_init();
  1051. /* XXX virtualize those bellow? */
  1052. tcp_delacktime = TCPTV_DELACK;
  1053. tcp_keepinit = TCPTV_KEEP_INIT;
  1054. tcp_keepidle = TCPTV_KEEP_IDLE;
  1055. tcp_keepintvl = TCPTV_KEEPINTVL;
  1056. tcp_maxpersistidle = TCPTV_KEEP_IDLE;
  1057. tcp_msl = TCPTV_MSL;
  1058. tcp_rexmit_initial = TCPTV_RTOBASE;
  1059. if (tcp_rexmit_initial < 1)
  1060. tcp_rexmit_initial = 1;
  1061. tcp_rexmit_min = TCPTV_MIN;
  1062. if (tcp_rexmit_min < 1)
  1063. tcp_rexmit_min = 1;
  1064. tcp_persmin = TCPTV_PERSMIN;
  1065. tcp_persmax = TCPTV_PERSMAX;
  1066. tcp_rexmit_slop = TCPTV_CPU_VAR;
  1067. tcp_finwait2_timeout = TCPTV_FINWAIT2_TIMEOUT;
  1068. tcp_tcbhashsize = hashsize;
  1069. /* Setup the tcp function block list */
  1070. TAILQ_INIT(&t_functions);
  1071. rw_init(&tcp_function_lock, "tcp_func_lock");
  1072. register_tcp_functions(&tcp_def_funcblk, M_WAITOK);
  1073. #ifdef TCP_BLACKBOX
  1074. /* Initialize the TCP logging data. */
  1075. tcp_log_init();
  1076. #endif
  1077. arc4rand(&V_ts_offset_secret, sizeof(V_ts_offset_secret), 0);
  1078. if (tcp_soreceive_stream) {
  1079. #ifdef INET
  1080. tcp_usrreqs.pru_soreceive = soreceive_stream;
  1081. #endif
  1082. #ifdef INET6
  1083. tcp6_usrreqs.pru_soreceive = soreceive_stream;
  1084. #endif /* INET6 */
  1085. }
  1086. #ifdef INET6
  1087. #define TCP_MINPROTOHDR (sizeof(struct ip6_hdr) + sizeof(struct tcphdr))
  1088. #else /* INET6 */
  1089. #define TCP_MINPROTOHDR (sizeof(struct tcpiphdr))
  1090. #endif /* INET6 */
  1091. if (max_protohdr < TCP_MINPROTOHDR)
  1092. max_protohdr = TCP_MINPROTOHDR;
  1093. if (max_linkhdr + TCP_MINPROTOHDR > MHLEN)
  1094. panic("tcp_init");
  1095. #undef TCP_MINPROTOHDR
  1096. ISN_LOCK_INIT();
  1097. EVENTHANDLER_REGISTER(shutdown_pre_sync, tcp_fini, NULL,
  1098. SHUTDOWN_PRI_DEFAULT);
  1099. EVENTHANDLER_REGISTER(maxsockets_change, tcp_zone_change, NULL,
  1100. EVENTHANDLER_PRI_ANY);
  1101. tcp_inp_lro_direct_queue = counter_u64_alloc(M_WAITOK);
  1102. tcp_inp_lro_wokeup_queue = counter_u64_alloc(M_WAITOK);
  1103. tcp_inp_lro_compressed = counter_u64_alloc(M_WAITOK);
  1104. tcp_inp_lro_single_push = counter_u64_alloc(M_WAITOK);
  1105. tcp_inp_lro_locks_taken = counter_u64_alloc(M_WAITOK);
  1106. tcp_inp_lro_sack_wake = counter_u64_alloc(M_WAITOK);
  1107. #ifdef TCPPCAP
  1108. tcp_pcap_init();
  1109. #endif
  1110. }
  1111. #ifdef VIMAGE
  1112. static void
  1113. tcp_destroy(void *unused __unused)
  1114. {
  1115. int n;
  1116. #ifdef TCP_HHOOK
  1117. int error;
  1118. #endif
  1119. /*
  1120. * All our processes are gone, all our sockets should be cleaned
  1121. * up, which means, we should be past the tcp_discardcb() calls.
  1122. * Sleep to let all tcpcb timers really disappear and cleanup.
  1123. */
  1124. for (;;) {
  1125. INP_LIST_RLOCK(&V_tcbinfo);
  1126. n = V_tcbinfo.ipi_count;
  1127. INP_LIST_RUNLOCK(&V_tcbinfo);
  1128. if (n == 0)
  1129. break;
  1130. pause("tcpdes", hz / 10);
  1131. }
  1132. tcp_hc_destroy();
  1133. syncache_destroy();
  1134. tcp_tw_destroy();
  1135. in_pcbinfo_destroy(&V_tcbinfo);
  1136. /* tcp_discardcb() clears the sack_holes up. */
  1137. uma_zdestroy(V_sack_hole_zone);
  1138. uma_zdestroy(V_tcpcb_zone);
  1139. /*
  1140. * Cannot free the zone until all tcpcbs are released as we attach
  1141. * the allocations to them.
  1142. */
  1143. tcp_fastopen_destroy();
  1144. #ifdef TCP_HHOOK
  1145. error = hhook_head_deregister(V_tcp_hhh[HHOOK_TCP_EST_IN]);
  1146. if (error != 0) {
  1147. printf("%s: WARNING: unable to deregister helper hook "
  1148. "type=%d, id=%d: error %d returned\n", __func__,
  1149. HHOOK_TYPE_TCP, HHOOK_TCP_EST_IN, error);
  1150. }
  1151. error = hhook_head_deregister(V_tcp_hhh[HHOOK_TCP_EST_OUT]);
  1152. if (error != 0) {
  1153. printf("%s: WARNING: unable to deregister helper hook "
  1154. "type=%d, id=%d: error %d returned\n", __func__,
  1155. HHOOK_TYPE_TCP, HHOOK_TCP_EST_OUT, error);
  1156. }
  1157. #endif
  1158. }
  1159. VNET_SYSUNINIT(tcp, SI_SUB_PROTO_DOMAIN, SI_ORDER_FOURTH, tcp_destroy, NULL);
  1160. #endif
  1161. void
  1162. tcp_fini(void *xtp)
  1163. {
  1164. }
  1165. /*
  1166. * Fill in the IP and TCP headers for an outgoing packet, given the tcpcb.
  1167. * tcp_template used to store this data in mbufs, but we now recopy it out
  1168. * of the tcpcb each time to conserve mbufs.
  1169. */
  1170. void
  1171. tcpip_fillheaders(struct inpcb *inp, void *ip_ptr, void *tcp_ptr)
  1172. {
  1173. struct tcphdr *th = (struct tcphdr *)tcp_ptr;
  1174. INP_WLOCK_ASSERT(inp);
  1175. #ifdef INET6
  1176. if ((inp->inp_vflag & INP_IPV6) != 0) {
  1177. struct ip6_hdr *ip6;
  1178. ip6 = (struct ip6_hdr *)ip_ptr;
  1179. ip6->ip6_flow = (ip6->ip6_flow & ~IPV6_FLOWINFO_MASK) |
  1180. (inp->inp_flow & IPV6_FLOWINFO_MASK);
  1181. ip6->ip6_vfc = (ip6->ip6_vfc & ~IPV6_VERSION_MASK) |
  1182. (IPV6_VERSION & IPV6_VERSION_MASK);
  1183. ip6->ip6_nxt = IPPROTO_TCP;
  1184. ip6->ip6_plen = htons(sizeof(struct tcphdr));
  1185. ip6->ip6_src = inp->in6p_laddr;
  1186. ip6->ip6_dst = inp->in6p_faddr;
  1187. }
  1188. #endif /* INET6 */
  1189. #if defined(INET6) && defined(INET)
  1190. else
  1191. #endif
  1192. #ifdef INET
  1193. {
  1194. struct ip *ip;
  1195. ip = (struct ip *)ip_ptr;
  1196. ip->ip_v = IPVERSION;
  1197. ip->ip_hl = 5;
  1198. ip->ip_tos = inp->inp_ip_tos;
  1199. ip->ip_len = 0;
  1200. ip->ip_id = 0;
  1201. ip->ip_off = 0;
  1202. ip->ip_ttl = inp->inp_ip_ttl;
  1203. ip->ip_sum = 0;
  1204. ip->ip_p = IPPROTO_TCP;
  1205. ip->ip_src = inp->inp_laddr;
  1206. ip->ip_dst = inp->inp_faddr;
  1207. }
  1208. #endif /* INET */
  1209. th->th_sport = inp->inp_lport;
  1210. th->th_dport = inp->inp_fport;
  1211. th->th_seq = 0;
  1212. th->th_ack = 0;
  1213. th->th_x2 = 0;
  1214. th->th_off = 5;
  1215. th->th_flags = 0;
  1216. th->th_win = 0;
  1217. th->th_urp = 0;
  1218. th->th_sum = 0; /* in_pseudo() is called later for ipv4 */
  1219. }
  1220. /*
  1221. * Create template to be used to send tcp packets on a connection.
  1222. * Allocates an mbuf and fills in a skeletal tcp/ip header. The only
  1223. * use for this function is in keepalives, which use tcp_respond.
  1224. */
  1225. struct tcptemp *
  1226. tcpip_maketemplate(struct inpcb *inp)
  1227. {
  1228. struct tcptemp *t;
  1229. t = malloc(sizeof(*t), M_TEMP, M_NOWAIT);
  1230. if (t == NULL)
  1231. return (NULL);
  1232. tcpip_fillheaders(inp, (void *)&t->tt_ipgen, (void *)&t->tt_t);
  1233. return (t);
  1234. }
  1235. /*
  1236. * Send a single message to the TCP at address specified by
  1237. * the given TCP/IP header. If m == NULL, then we make a copy
  1238. * of the tcpiphdr at th and send directly to the addressed host.
  1239. * This is used to force keep alive messages out using the TCP
  1240. * template for a connection. If flags are given then we send
  1241. * a message back to the TCP which originated the segment th,
  1242. * and discard the mbuf containing it and any other attached mbufs.
  1243. *
  1244. * In any case the ack and sequence number of the transmitted
  1245. * segment are as specified by the parameters.
  1246. *
  1247. * NOTE: If m != NULL, then th must point to *inside* the mbuf.
  1248. */
  1249. void
  1250. tcp_respond(struct tcpcb *tp, void *ipgen, struct tcphdr *th, struct mbuf *m,
  1251. tcp_seq ack, tcp_seq seq, int flags)
  1252. {
  1253. struct tcpopt to;
  1254. struct inpcb *inp;
  1255. struct ip *ip;
  1256. struct mbuf *optm;
  1257. struct tcphdr *nth;
  1258. u_char *optp;
  1259. #ifdef INET6
  1260. struct ip6_hdr *ip6;
  1261. int isipv6;
  1262. #endif /* INET6 */
  1263. int optlen, tlen, win;
  1264. bool incl_opts;
  1265. KASSERT(tp != NULL || m != NULL, ("tcp_respond: tp and m both NULL"));
  1266. NET_EPOCH_ASSERT();
  1267. #ifdef INET6
  1268. isipv6 = ((struct ip *)ipgen)->ip_v == (IPV6_VERSION >> 4);
  1269. ip6 = ipgen;
  1270. #endif /* INET6 */
  1271. ip = ipgen;
  1272. if (tp != NULL) {
  1273. inp = tp->t_inpcb;
  1274. KASSERT(inp != NULL, ("tcp control block w/o inpcb"));
  1275. INP_WLOCK_ASSERT(inp);
  1276. } else
  1277. inp = NULL;
  1278. incl_opts = false;
  1279. win = 0;
  1280. if (tp != NULL) {
  1281. if (!(flags & TH_RST)) {
  1282. win = sbspace(&inp->inp_socket->so_rcv);
  1283. if (win > TCP_MAXWIN << tp->rcv_scale)
  1284. win = TCP_MAXWIN << tp->rcv_scale;
  1285. }
  1286. if ((tp->t_flags & TF_NOOPT) == 0)
  1287. incl_opts = true;
  1288. }
  1289. if (m == NULL) {
  1290. m = m_gethdr(M_NOWAIT, MT_DATA);
  1291. if (m == NULL)
  1292. return;
  1293. m->m_data += max_linkhdr;
  1294. #ifdef INET6
  1295. if (isipv6) {
  1296. bcopy((caddr_t)ip6, mtod(m, caddr_t),
  1297. sizeof(struct ip6_hdr));
  1298. ip6 = mtod(m, struct ip6_hdr *);
  1299. nth = (struct tcphdr *)(ip6 + 1);
  1300. } else
  1301. #endif /* INET6 */
  1302. {
  1303. bcopy((caddr_t)ip, mtod(m, caddr_t), sizeof(struct ip));
  1304. ip = mtod(m, struct ip *);
  1305. nth = (struct tcphdr *)(ip + 1);
  1306. }
  1307. bcopy((caddr_t)th, (caddr_t)nth, sizeof(struct tcphdr));
  1308. flags = TH_ACK;
  1309. } else if (!M_WRITABLE(m)) {
  1310. struct mbuf *n;
  1311. /* Can't reuse 'm', allocate a new mbuf. */
  1312. n = m_gethdr(M_NOWAIT, MT_DATA);
  1313. if (n == NULL) {
  1314. m_freem(m);
  1315. return;
  1316. }
  1317. if (!m_dup_pkthdr(n, m, M_NOWAIT)) {
  1318. m_freem(m);
  1319. m_freem(n);
  1320. return;
  1321. }
  1322. n->m_data += max_linkhdr;
  1323. /* m_len is set later */
  1324. #define xchg(a,b,type) { type t; t=a; a=b; b=t; }
  1325. #ifdef INET6
  1326. if (isipv6) {
  1327. bcopy((caddr_t)ip6, mtod(n, caddr_t),
  1328. sizeof(struct ip6_hdr));
  1329. ip6 = mtod(n, struct ip6_hdr *);
  1330. xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
  1331. nth = (struct tcphdr *)(ip6 + 1);
  1332. } else
  1333. #endif /* INET6 */
  1334. {
  1335. bcopy((caddr_t)ip, mtod(n, caddr_t), sizeof(struct ip));
  1336. ip = mtod(n, struct ip *);
  1337. xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, uint32_t);
  1338. nth = (struct tcphdr *)(ip + 1);
  1339. }
  1340. bcopy((caddr_t)th, (caddr_t)nth, sizeof(struct tcphdr));
  1341. xchg(nth->th_dport, nth->th_sport, uint16_t);
  1342. th = nth;
  1343. m_freem(m);
  1344. m = n;
  1345. } else {
  1346. /*
  1347. * reuse the mbuf.
  1348. * XXX MRT We inherit the FIB, which is lucky.
  1349. */
  1350. m_freem(m->m_next);
  1351. m->m_next = NULL;
  1352. m->m_data = (caddr_t)ipgen;
  1353. /* m_len is set later */
  1354. #ifdef INET6
  1355. if (isipv6) {
  1356. xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
  1357. nth = (struct tcphdr *)(ip6 + 1);
  1358. } else
  1359. #endif /* INET6 */
  1360. {
  1361. xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, uint32_t);
  1362. nth = (struct tcphdr *)(ip + 1);
  1363. }
  1364. if (th != nth) {
  1365. /*
  1366. * this is usually a case when an extension header
  1367. * exists between the IPv6 header and the
  1368. * TCP header.
  1369. */
  1370. nth->th_sport = th->th_sport;
  1371. nth->th_dport = th->th_dport;
  1372. }
  1373. xchg(nth->th_dport, nth->th_sport, uint16_t);
  1374. #undef xchg
  1375. }
  1376. tlen = 0;
  1377. #ifdef INET6
  1378. if (isipv6)
  1379. tlen = sizeof (struct ip6_hdr) + sizeof (struct tcphdr);
  1380. #endif
  1381. #if defined(INET) && defined(INET6)
  1382. else
  1383. #endif
  1384. #ifdef INET
  1385. tlen = sizeof (struct tcpiphdr);
  1386. #endif
  1387. #ifdef INVARIANTS
  1388. m->m_len = 0;
  1389. KASSERT(M_TRAILINGSPACE(m) >= tlen,
  1390. ("Not enough trailing space for message (m=%p, need=%d, have=%ld)",
  1391. m, tlen, (long)M_TRAILINGSPACE(m)));
  1392. #endif
  1393. m->m_len = tlen;
  1394. to.to_flags = 0;
  1395. if (incl_opts) {
  1396. /* Make sure we have room. */
  1397. if (M_TRAILINGSPACE(m) < TCP_MAXOLEN) {
  1398. m->m_next = m_get(M_NOWAIT, MT_DATA);
  1399. if (m->m_next) {
  1400. optp = mtod(m->m_next, u_char *);
  1401. optm = m->m_next;
  1402. } else
  1403. incl_opts = false;
  1404. } else {
  1405. optp = (u_char *) (nth + 1);
  1406. optm = m;
  1407. }
  1408. }
  1409. if (incl_opts) {
  1410. /* Timestamps. */
  1411. if (tp->t_flags & TF_RCVD_TSTMP) {
  1412. to.to_tsval = tcp_ts_getticks() + tp->ts_offset;
  1413. to.to_tsecr = tp->ts_recent;
  1414. to.to_flags |= TOF_TS;
  1415. }
  1416. #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
  1417. /* TCP-MD5 (RFC2385). */
  1418. if (tp->t_flags & TF_SIGNATURE)
  1419. to.to_flags |= TOF_SIGNATURE;
  1420. #endif
  1421. /* Add the options. */
  1422. tlen += optlen = tcp_addoptions(&to, optp);
  1423. /* Update m_len in the correct mbuf. */
  1424. optm->m_len += optlen;
  1425. } else
  1426. optlen = 0;
  1427. #ifdef INET6
  1428. if (isipv6) {
  1429. ip6->ip6_flow = 0;
  1430. ip6->ip6_vfc = IPV6_VERSION;
  1431. ip6->ip6_nxt = IPPROTO_TCP;
  1432. ip6->ip6_plen = htons(tlen - sizeof(*ip6));
  1433. }
  1434. #endif
  1435. #if defined(INET) && defined(INET6)
  1436. else
  1437. #endif
  1438. #ifdef INET
  1439. {
  1440. ip->ip_len = htons(tlen);
  1441. ip->ip_ttl = V_ip_defttl;
  1442. if (V_path_mtu_discovery)
  1443. ip->ip_off |= htons(IP_DF);
  1444. }
  1445. #endif
  1446. m->m_pkthdr.len = tlen;
  1447. m->m_pkthdr.rcvif = NULL;
  1448. #ifdef MAC
  1449. if (inp != NULL) {
  1450. /*
  1451. * Packet is associated with a socket, so allow the
  1452. * label of the response to reflect the socket label.
  1453. */
  1454. INP_WLOCK_ASSERT(inp);
  1455. mac_inpcb_create_mbuf(inp, m);
  1456. } else {
  1457. /*
  1458. * Packet is not associated with a socket, so possibly
  1459. * update the label in place.
  1460. */
  1461. mac_netinet_tcp_reply(m);
  1462. }
  1463. #endif
  1464. nth->th_seq = htonl(seq);
  1465. nth->th_ack = htonl(ack);
  1466. nth->th_x2 = 0;
  1467. nth->th_off = (sizeof (struct tcphdr) + optlen) >> 2;
  1468. nth->th_flags = flags;
  1469. if (tp != NULL)
  1470. nth->th_win = htons((u_short) (win >> tp->rcv_scale));
  1471. else
  1472. nth->th_win = htons((u_short)win);
  1473. nth->th_urp = 0;
  1474. #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
  1475. if (to.to_flags & TOF_SIGNATURE) {
  1476. if (!TCPMD5_ENABLED() ||
  1477. TCPMD5_OUTPUT(m, nth, to.to_signature) != 0) {
  1478. m_freem(m);
  1479. return;
  1480. }
  1481. }
  1482. #endif
  1483. m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
  1484. #ifdef INET6
  1485. if (isipv6) {
  1486. m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
  1487. nth->th_sum = in6_cksum_pseudo(ip6,
  1488. tlen - sizeof(struct ip6_hdr), IPPROTO_TCP, 0);
  1489. ip6->ip6_hlim = in6_selecthlim(tp != NULL ? tp->t_inpcb :
  1490. NULL, NULL);
  1491. }
  1492. #endif /* INET6 */
  1493. #if defined(INET6) && defined(INET)
  1494. else
  1495. #endif
  1496. #ifdef INET
  1497. {
  1498. m->m_pkthdr.csum_flags = CSUM_TCP;
  1499. nth->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
  1500. htons((u_short)(tlen - sizeof(struct ip) + ip->ip_p)));
  1501. }
  1502. #endif /* INET */
  1503. #ifdef TCPDEBUG
  1504. if (tp == NULL || (inp->inp_socket->so_options & SO_DEBUG))
  1505. tcp_trace(TA_OUTPUT, 0, tp, mtod(m, void *), th, 0);
  1506. #endif
  1507. TCP_PROBE3(debug__output, tp, th, m);
  1508. if (flags & TH_RST)
  1509. TCP_PROBE5(accept__refused, NULL, NULL, m, tp, nth);
  1510. #ifdef INET6
  1511. if (isipv6) {
  1512. TCP_PROBE5(send, NULL, tp, ip6, tp, nth);
  1513. (void)ip6_output(m, NULL, NULL, 0, NULL, NULL, inp);
  1514. }
  1515. #endif /* INET6 */
  1516. #if defined(INET) && defined(INET6)
  1517. else
  1518. #endif
  1519. #ifdef INET
  1520. {
  1521. TCP_PROBE5(send, NULL, tp, ip, tp, nth);
  1522. (void)ip_output(m, NULL, NULL, 0, NULL, inp);
  1523. }
  1524. #endif
  1525. }
  1526. /*
  1527. * Create a new TCP control block, making an
  1528. * empty reassembly queue and hooking it to the argument
  1529. * protocol control block. The `inp' parameter must have
  1530. * come from the zone allocator set up in tcp_init().
  1531. */
  1532. struct tcpcb *
  1533. tcp_newtcpcb(struct inpcb *inp)
  1534. {
  1535. struct tcpcb_mem *tm;
  1536. struct tcpcb *tp;
  1537. #ifdef INET6
  1538. int isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
  1539. #endif /* INET6 */
  1540. tm = uma_zalloc(V_tcpcb_zone, M_NOWAIT | M_ZERO);
  1541. if (tm == NULL)
  1542. return (NULL);
  1543. tp = &tm->tcb;
  1544. /* Initialise cc_var struct for this tcpcb. */
  1545. tp->ccv = &tm->ccv;
  1546. tp->ccv->type = IPPROTO_TCP;
  1547. tp->ccv->ccvc.tcp = tp;
  1548. rw_rlock(&tcp_function_lock);
  1549. tp->t_fb = tcp_func_set_ptr;
  1550. refcount_acquire(&tp->t_fb->tfb_refcnt);
  1551. rw_runlock(&tcp_function_lock);
  1552. /*
  1553. * Use the current system default CC algorithm.
  1554. */
  1555. CC_LIST_RLOCK();
  1556. KASSERT(!STAILQ_EMPTY(&cc_list), ("cc_list is empty!"));
  1557. CC_ALGO(tp) = CC_DEFAULT();
  1558. CC_LIST_RUNLOCK();
  1559. /*
  1560. * The tcpcb will hold a reference on its inpcb until tcp_discardcb()
  1561. * is called.
  1562. */
  1563. in_pcbref(inp); /* Reference for tcpcb */
  1564. tp->t_inpcb = inp;
  1565. if (CC_ALGO(tp)->cb_init != NULL)
  1566. if (CC_ALGO(tp)->cb_init(tp->ccv) > 0) {
  1567. if (tp->t_fb->tfb_tcp_fb_fini)
  1568. (*tp->t_fb->tfb_tcp_fb_fini)(tp, 1);
  1569. in_pcbrele_wlocked(inp);
  1570. refcount_release(&tp->t_fb->tfb_refcnt);
  1571. uma_zfree(V_tcpcb_zone, tm);
  1572. return (NULL);
  1573. }
  1574. #ifdef TCP_HHOOK
  1575. tp->osd = &tm->osd;
  1576. if (khelp_init_osd(HELPER_CLASS_TCP, tp->osd)) {
  1577. if (tp->t_fb->tfb_tcp_fb_fini)
  1578. (*tp->t_fb->tfb_tcp_fb_fini)(tp, 1);
  1579. in_pcbrele_wlocked(inp);
  1580. refcount_release(&tp->t_fb->tfb_refcnt);
  1581. uma_zfree(V_tcpcb_zone, tm);
  1582. return (NULL);
  1583. }
  1584. #endif
  1585. #ifdef VIMAGE
  1586. tp->t_vnet = inp->inp_vnet;
  1587. #endif
  1588. tp->t_timers = &tm->tt;
  1589. TAILQ_INIT(&tp->t_segq);
  1590. tp->t_maxseg =
  1591. #ifdef INET6
  1592. isipv6 ? V_tcp_v6mssdflt :
  1593. #endif /* INET6 */
  1594. V_tcp_mssdflt;
  1595. /* Set up our timeouts. */
  1596. callout_init(&tp->t_timers->tt_rexmt, 1);
  1597. callout_init(&tp->t_timers->tt_persist, 1);
  1598. callout_init(&tp->t_timers->tt_keep, 1);
  1599. callout_init(&tp->t_timers->tt_2msl, 1);
  1600. callout_init(&tp->t_timers->tt_delack, 1);
  1601. if (V_tcp_do_rfc1323)
  1602. tp->t_flags = (TF_REQ_SCALE|TF_REQ_TSTMP);
  1603. if (V_tcp_do_sack)
  1604. tp->t_flags |= TF_SACK_PERMIT;
  1605. TAILQ_INIT(&tp->snd_holes);
  1606. /*
  1607. * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no
  1608. * rtt estimate. Set rttvar so that srtt + 4 * rttvar gives
  1609. * reasonable initial retransmit time.
  1610. */
  1611. tp->t_srtt = TCPTV_SRTTBASE;
  1612. tp->t_rttvar = ((tcp_rexmit_initial - TCPTV_SRTTBASE) << TCP_RTTVAR_SHIFT) / 4;
  1613. tp->t_rttmin = tcp_rexmit_min;
  1614. tp->t_rxtcur = tcp_rexmit_initial;
  1615. tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
  1616. tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
  1617. tp->t_rcvtime = ticks;
  1618. /*
  1619. * IPv4 TTL initialization is necessary for an IPv6 socket as well,
  1620. * because the socket may be bound to an IPv6 wildcard address,
  1621. * which may match an IPv4-mapped IPv6 address.
  1622. */
  1623. inp->inp_ip_ttl = V_ip_defttl;
  1624. inp->inp_ppcb = tp;
  1625. #ifdef TCPPCAP
  1626. /*
  1627. * Init the TCP PCAP queues.
  1628. */
  1629. tcp_pcap_tcpcb_init(tp);
  1630. #endif
  1631. #ifdef TCP_BLACKBOX
  1632. /* Initialize the per-TCPCB log data. */
  1633. tcp_log_tcpcbinit(tp);
  1634. #endif
  1635. tp->t_pacing_rate = -1;
  1636. if (tp->t_fb->tfb_tcp_fb_init) {
  1637. if ((*tp->t_fb->tfb_tcp_fb_init)(tp)) {
  1638. refcount_release(&tp->t_fb->tfb_refcnt);
  1639. in_pcbrele_wlocked(inp);
  1640. uma_zfree(V_tcpcb_zone, tm);
  1641. return (NULL);
  1642. }
  1643. }
  1644. #ifdef STATS
  1645. if (V_tcp_perconn_stats_enable == 1)
  1646. tp->t_stats = stats_blob_alloc(V_tcp_perconn_stats_dflt_tpl, 0);
  1647. #endif
  1648. return (tp); /* XXX */
  1649. }
  1650. /*
  1651. * Switch the congestion control algorithm back to NewReno for any active
  1652. * control blocks using an algorithm which is about to go away.
  1653. * This ensures the CC framework can allow the unload to proceed without leaving
  1654. * any dangling pointers which would trigger a panic.
  1655. * Returning non-zero would inform the CC framework that something went wrong
  1656. * and it would be unsafe to allow the unload to proceed. However, there is no
  1657. * way for this to occur with this implementation so we always return zero.
  1658. */
  1659. int
  1660. tcp_ccalgounload(struct cc_algo *unload_algo)
  1661. {
  1662. struct cc_algo *tmpalgo;
  1663. struct inpcb *inp;
  1664. struct tcpcb *tp;
  1665. VNET_ITERATOR_DECL(vnet_iter);
  1666. /*
  1667. * Check all active control blocks across all network stacks and change
  1668. * any that are using "unload_algo" back to NewReno. If "unload_algo"
  1669. * requires cleanup code to be run, call it.
  1670. */
  1671. VNET_LIST_RLOCK();
  1672. VNET_FOREACH(vnet_iter) {
  1673. CURVNET_SET(vnet_iter);
  1674. INP_INFO_WLOCK(&V_tcbinfo);
  1675. /*
  1676. * New connections already part way through being initialised
  1677. * with the CC algo we're removing will not race with this code
  1678. * because the INP_INFO_WLOCK is held during initialisation. We
  1679. * therefore don't enter the loop below until the connection
  1680. * list has stabilised.
  1681. */
  1682. CK_LIST_FOREACH(inp, &V_tcb, inp_list) {
  1683. INP_WLOCK(inp);
  1684. /* Important to skip tcptw structs. */
  1685. if (!(inp->inp_flags & INP_TIMEWAIT) &&
  1686. (tp = intotcpcb(inp)) != NULL) {
  1687. /*
  1688. * By holding INP_WLOCK here, we are assured
  1689. * that the connection is not currently
  1690. * executing inside the CC module's functions
  1691. * i.e. it is safe to make the switch back to
  1692. * NewReno.
  1693. */
  1694. if (CC_ALGO(tp) == unload_algo) {
  1695. tmpalgo = CC_ALGO(tp);
  1696. if (tmpalgo->cb_destroy != NULL)
  1697. tmpalgo->cb_destroy(tp->ccv);
  1698. CC_DATA(tp) = NULL;
  1699. /*
  1700. * NewReno may allocate memory on
  1701. * demand for certain stateful
  1702. * configuration as needed, but is
  1703. * coded to never fail on memory
  1704. * allocation failure so it is a safe
  1705. * fallback.
  1706. */
  1707. CC_ALGO(tp) = &newreno_cc_algo;
  1708. }
  1709. }
  1710. INP_WUNLOCK(inp);
  1711. }
  1712. INP_INFO_WUNLOCK(&V_tcbinfo);
  1713. CURVNET_RESTORE();
  1714. }
  1715. VNET_LIST_RUNLOCK();
  1716. return (0);
  1717. }
  1718. /*
  1719. * Drop a TCP connection, reporting
  1720. * the specified error. If connection is synchronized,
  1721. * then send a RST to peer.
  1722. */
  1723. struct tcpcb *
  1724. tcp_drop(struct tcpcb *tp, int errno)
  1725. {
  1726. struct socket *so = tp->t_inpcb->inp_socket;
  1727. NET_EPOCH_ASSERT();
  1728. INP_INFO_LOCK_ASSERT(&V_tcbinfo);
  1729. INP_WLOCK_ASSERT(tp->t_inpcb);
  1730. if (TCPS_HAVERCVDSYN(tp->t_state)) {
  1731. tcp_state_change(tp, TCPS_CLOSED);
  1732. (void) tp->t_fb->tfb_tcp_output(tp);
  1733. TCPSTAT_INC(tcps_drops);
  1734. } else
  1735. TCPSTAT_INC(tcps_conndrops);
  1736. if (errno == ETIMEDOUT && tp->t_softerror)
  1737. errno = tp->t_softerror;
  1738. so->so_error = errno;
  1739. return (tcp_close(tp));
  1740. }
  1741. void
  1742. tcp_discardcb(struct tcpcb *tp)
  1743. {
  1744. struct inpcb *inp = tp->t_inpcb;
  1745. struct socket *so = inp->inp_socket;
  1746. #ifdef INET6
  1747. int isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
  1748. #endif /* INET6 */
  1749. int released __unused;
  1750. INP_WLOCK_ASSERT(inp);
  1751. /*
  1752. * Make sure that all of our timers are stopped before we delete the
  1753. * PCB.
  1754. *
  1755. * If stopping a timer fails, we schedule a discard function in same
  1756. * callout, and the last discard function called will take care of
  1757. * deleting the tcpcb.
  1758. */
  1759. tp->t_timers->tt_draincnt = 0;
  1760. tcp_timer_stop(tp, TT_REXMT);
  1761. tcp_timer_stop(tp, TT_PERSIST);
  1762. tcp_timer_stop(tp, TT_KEEP);
  1763. tcp_timer_stop(tp, TT_2MSL);
  1764. tcp_timer_stop(tp, TT_DELACK);
  1765. if (tp->t_fb->tfb_tcp_timer_stop_all) {
  1766. /*
  1767. * Call the stop-all function of the methods,
  1768. * this function should call the tcp_timer_stop()
  1769. * method with each of the function specific timeouts.
  1770. * That stop will be called via the tfb_tcp_timer_stop()
  1771. * which should use the async drain function of the
  1772. * callout system (see tcp_var.h).
  1773. */
  1774. tp->t_fb->tfb_tcp_timer_stop_all(tp);
  1775. }
  1776. /*
  1777. * If we got enough samples through the srtt filter,
  1778. * save the rtt and rttvar in the routing entry.
  1779. * 'Enough' is arbitrarily defined as 4 rtt samples.
  1780. * 4 samples is enough for the srtt filter to converge
  1781. * to within enough % of the correct value; fewer samples
  1782. * and we could save a bogus rtt. The danger is not high
  1783. * as tcp quickly recovers from everything.
  1784. * XXX: Works very well but needs some more statistics!
  1785. */
  1786. if (tp->t_rttupdated >= 4) {
  1787. struct hc_metrics_lite metrics;
  1788. uint32_t ssthresh;
  1789. bzero(&metrics, sizeof(metrics));
  1790. /*
  1791. * Update the ssthresh always when the conditions below
  1792. * are satisfied. This gives us better new start value
  1793. * for the congestion avoidance for new connections.
  1794. * ssthresh is only set if packet loss occurred on a session.
  1795. *
  1796. * XXXRW: 'so' may be NULL here, and/or socket buffer may be
  1797. * being torn down. Ideally this code would not use 'so'.
  1798. */
  1799. ssthresh = tp->snd_ssthresh;
  1800. if (ssthresh != 0 && ssthresh < so->so_snd.sb_hiwat / 2) {
  1801. /*
  1802. * convert the limit from user data bytes to
  1803. * packets then to packet data bytes.
  1804. */
  1805. ssthresh = (ssthresh + tp->t_maxseg / 2) / tp->t_maxseg;
  1806. if (ssthresh < 2)
  1807. ssthresh = 2;
  1808. ssthresh *= (tp->t_maxseg +
  1809. #ifdef INET6
  1810. (isipv6 ? sizeof (struct ip6_hdr) +
  1811. sizeof (struct tcphdr) :
  1812. #endif
  1813. sizeof (struct tcpiphdr)
  1814. #ifdef INET6
  1815. )
  1816. #endif
  1817. );
  1818. } else
  1819. ssthresh = 0;
  1820. metrics.rmx_ssthresh = ssthresh;
  1821. metrics.rmx_rtt = tp->t_srtt;
  1822. metrics.rmx_rttvar = tp->t_rttvar;
  1823. metrics.rmx_cwnd = tp->snd_cwnd;
  1824. metrics.rmx_sendpipe = 0;
  1825. metrics.rmx_recvpipe = 0;
  1826. tcp_hc_update(&inp->inp_inc, &metrics);
  1827. }
  1828. /* free the reassembly queue, if any */
  1829. tcp_reass_flush(tp);
  1830. #ifdef TCP_OFFLOAD
  1831. /* Disconnect offload device, if any. */
  1832. if (tp->t_flags & TF_TOE)
  1833. tcp_offload_detach(tp);
  1834. #endif
  1835. tcp_free_sackholes(tp);
  1836. #ifdef TCPPCAP
  1837. /* Free the TCP PCAP queues. */
  1838. tcp_pcap_drain(&(tp->t_inpkts));
  1839. tcp_pcap_drain(&(tp->t_outpkts));
  1840. #endif
  1841. /* Allow the CC algorithm to clean up after itself. */
  1842. if (CC_ALGO(tp)->cb_destroy != NULL)
  1843. CC_ALGO(tp)->cb_destroy(tp->ccv);
  1844. CC_DATA(tp) = NULL;
  1845. #ifdef TCP_HHOOK
  1846. khelp_destroy_osd(tp->osd);
  1847. #endif
  1848. #ifdef STATS
  1849. stats_blob_destroy(tp->t_stats);
  1850. #endif
  1851. CC_ALGO(tp) = NULL;
  1852. inp->inp_ppcb = NULL;
  1853. if (tp->t_timers->tt_draincnt == 0) {
  1854. /* We own the last reference on tcpcb, let's free it. */
  1855. #ifdef TCP_BLACKBOX
  1856. tcp_log_tcpcbfini(tp);
  1857. #endif
  1858. TCPSTATES_DEC(tp->t_state);
  1859. if (tp->t_fb->tfb_tcp_fb_fini)
  1860. (*tp->t_fb->tfb_tcp_fb_fini)(tp, 1);
  1861. refcount_release(&tp->t_fb->tfb_refcnt);
  1862. tp->t_inpcb = NULL;
  1863. uma_zfree(V_tcpcb_zone, tp);
  1864. released = in_pcbrele_wlocked(inp);
  1865. KASSERT(!released, ("%s: inp %p should not have been released "
  1866. "here", __func__, inp));
  1867. }
  1868. }
  1869. void
  1870. tcp_timer_discard(void *ptp)
  1871. {
  1872. struct inpcb *inp;
  1873. struct tcpcb *tp;
  1874. struct epoch_tracker et;
  1875. tp = (struct tcpcb *)ptp;
  1876. CURVNET_SET(tp->t_vnet);
  1877. NET_EPOCH_ENTER(et);
  1878. inp = tp->t_inpcb;
  1879. KASSERT(inp != NULL, ("%s: tp %p tp->t_inpcb == NULL",
  1880. __func__, tp));
  1881. INP_WLOCK(inp);
  1882. KASSERT((tp->t_timers->tt_flags & TT_STOPPED) != 0,
  1883. ("%s: tcpcb has to be stopped here", __func__));
  1884. tp->t_timers->tt_draincnt--;
  1885. if (tp->t_timers->tt_draincnt == 0) {
  1886. /* We own the last reference on this tcpcb, let's free it. */
  1887. #ifdef TCP_BLACKBOX
  1888. tcp_log_tcpcbfini(tp);
  1889. #endif
  1890. TCPSTATES_DEC(tp->t_state);
  1891. if (tp->t_fb->tfb_tcp_fb_fini)
  1892. (*tp->t_fb->tfb_tcp_fb_fini)(tp, 1);
  1893. refcount_release(&tp->t_fb->tfb_refcnt);
  1894. tp->t_inpcb = NULL;
  1895. uma_zfree(V_tcpcb_zone, tp);
  1896. if (in_pcbrele_wlocked(inp)) {
  1897. NET_EPOCH_EXIT(et);
  1898. CURVNET_RESTORE();
  1899. return;
  1900. }
  1901. }
  1902. INP_WUNLOCK(inp);
  1903. NET_EPOCH_EXIT(et);
  1904. CURVNET_RESTORE();
  1905. }
  1906. /*
  1907. * Attempt to close a TCP control block, marking it as dropped, and freeing
  1908. * the socket if we hold the only reference.
  1909. */
  1910. struct tcpcb *
  1911. tcp_close(struct tcpcb *tp)
  1912. {
  1913. struct inpcb *inp = tp->t_inpcb;
  1914. struct socket *so;
  1915. INP_INFO_LOCK_ASSERT(&V_tcbinfo);
  1916. INP_WLOCK_ASSERT(inp);
  1917. #ifdef TCP_OFFLOAD
  1918. if (tp->t_state == TCPS_LISTEN)
  1919. tcp_offload_listen_stop(tp);
  1920. #endif
  1921. /*
  1922. * This releases the TFO pending counter resource for TFO listen
  1923. * sockets as well as passively-created TFO sockets that transition
  1924. * from SYN_RECEIVED to CLOSED.
  1925. */
  1926. if (tp->t_tfo_pending) {
  1927. tcp_fastopen_decrement_counter(tp->t_tfo_pending);
  1928. tp->t_tfo_pending = NULL;
  1929. }
  1930. in_pcbdrop(inp);
  1931. TCPSTAT_INC(tcps_closed);
  1932. if (tp->t_state != TCPS_CLOSED)
  1933. tcp_state_change(tp, TCPS_CLOSED);
  1934. KASSERT(inp->inp_socket != NULL, ("tcp_close: inp_socket NULL"));
  1935. so = inp->inp_socket;
  1936. soisdisconnected(so);
  1937. if (inp->inp_flags & INP_SOCKREF) {
  1938. KASSERT(so->so_state & SS_PROTOREF,
  1939. ("tcp_close: !SS_PROTOREF"));
  1940. inp->inp_flags &= ~INP_SOCKREF;
  1941. INP_WUNLOCK(inp);
  1942. SOCK_LOCK(so);
  1943. so->so_state &= ~SS_PROTOREF;
  1944. sofree(so);
  1945. return (NULL);
  1946. }
  1947. return (tp);
  1948. }
  1949. void
  1950. tcp_drain(void)
  1951. {
  1952. VNET_ITERATOR_DECL(vnet_iter);
  1953. if (!do_tcpdrain)
  1954. return;
  1955. VNET_LIST_RLOCK_NOSLEEP();
  1956. VNET_FOREACH(vnet_iter) {
  1957. CURVNET_SET(vnet_iter);
  1958. struct inpcb *inpb;
  1959. struct tcpcb *tcpb;
  1960. /*
  1961. * Walk the tcpbs, if existing, and flush the reassembly queue,
  1962. * if there is one...
  1963. * XXX: The "Net/3" implementation doesn't imply that the TCP
  1964. * reassembly queue should be flushed, but in a situation
  1965. * where we're really low on mbufs, this is potentially
  1966. * useful.
  1967. */
  1968. INP_INFO_WLOCK(&V_tcbinfo);
  1969. CK_LIST_FOREACH(inpb, V_tcbinfo.ipi_listhead, inp_list) {
  1970. INP_WLOCK(inpb);
  1971. if (inpb->inp_flags & INP_TIMEWAIT) {
  1972. INP_WUNLOCK(inpb);
  1973. continue;
  1974. }
  1975. if ((tcpb = intotcpcb(inpb)) != NULL) {
  1976. tcp_reass_flush(tcpb);
  1977. tcp_clean_sackreport(tcpb);
  1978. #ifdef TCP_BLACKBOX
  1979. tcp_log_drain(tcpb);
  1980. #endif
  1981. #ifdef TCPPCAP
  1982. if (tcp_pcap_aggressive_free) {
  1983. /* Free the TCP PCAP queues. */
  1984. tcp_pcap_drain(&(tcpb->t_inpkts));
  1985. tcp_pcap_drain(&(tcpb->t_outpkts));
  1986. }
  1987. #endif
  1988. }
  1989. INP_WUNLOCK(inpb);
  1990. }
  1991. INP_INFO_WUNLOCK(&V_tcbinfo);
  1992. CURVNET_RESTORE();
  1993. }
  1994. VNET_LIST_RUNLOCK_NOSLEEP();
  1995. }
  1996. /*
  1997. * Notify a tcp user of an asynchronous error;
  1998. * store error as soft error, but wake up user
  1999. * (for now, won't do anything until can select for soft error).
  2000. *
  2001. * Do not wake up user since there currently is no mechanism for
  2002. * reporting soft errors (yet - a kqueue filter may be added).
  2003. */
  2004. static struct inpcb *
  2005. tcp_notify(struct inpcb *inp, int error)
  2006. {
  2007. struct tcpcb *tp;
  2008. INP_INFO_LOCK_ASSERT(&V_tcbinfo);
  2009. INP_WLOCK_ASSERT(inp);
  2010. if ((inp->inp_flags & INP_TIMEWAIT) ||
  2011. (inp->inp_flags & INP_DROPPED))
  2012. return (inp);
  2013. tp = intotcpcb(inp);
  2014. KASSERT(tp != NULL, ("tcp_notify: tp == NULL"));
  2015. /*
  2016. * Ignore some errors if we are hooked up.
  2017. * If connection hasn't completed, has retransmitted several times,
  2018. * and receives a second error, give up now. This is better
  2019. * than waiting a long time to establish a connection that
  2020. * can never complete.
  2021. */
  2022. if (tp->t_state == TCPS_ESTABLISHED &&
  2023. (error == EHOSTUNREACH || error == ENETUNREACH ||
  2024. error == EHOSTDOWN)) {
  2025. if (inp->inp_route.ro_nh) {
  2026. NH_FREE(inp->inp_route.ro_nh);
  2027. inp->inp_route.ro_nh = (struct nhop_object *)NULL;
  2028. }
  2029. return (inp);
  2030. } else if (tp->t_state < TCPS_ESTABLISHED && tp->t_rxtshift > 3 &&
  2031. tp->t_softerror) {
  2032. tp = tcp_drop(tp, error);
  2033. if (tp != NULL)
  2034. return (inp);
  2035. else
  2036. return (NULL);
  2037. } else {
  2038. tp->t_softerror = error;
  2039. return (inp);
  2040. }
  2041. #if 0
  2042. wakeup( &so->so_timeo);
  2043. sorwakeup(so);
  2044. sowwakeup(so);
  2045. #endif
  2046. }
  2047. static int
  2048. tcp_pcblist(SYSCTL_HANDLER_ARGS)
  2049. {
  2050. struct epoch_tracker et;
  2051. struct inpcb *inp;
  2052. struct xinpgen xig;
  2053. int error;
  2054. if (req->newptr != NULL)
  2055. return (EPERM);
  2056. if (req->oldptr == NULL) {
  2057. int n;
  2058. n = V_tcbinfo.ipi_count +
  2059. counter_u64_fetch(V_tcps_states[TCPS_SYN_RECEIVED]);
  2060. n += imax(n / 8, 10);
  2061. req->oldidx = 2 * (sizeof xig) + n * sizeof(struct xtcpcb);
  2062. return (0);
  2063. }
  2064. if ((error = sysctl_wire_old_buffer(req, 0)) != 0)
  2065. return (error);
  2066. bzero(&xig, sizeof(xig));
  2067. xig.xig_len = sizeof xig;
  2068. xig.xig_count = V_tcbinfo.ipi_count +
  2069. counter_u64_fetch(V_tcps_states[TCPS_SYN_RECEIVED]);
  2070. xig.xig_gen = V_tcbinfo.ipi_gencnt;
  2071. xig.xig_sogen = so_gencnt;
  2072. error = SYSCTL_OUT(req, &xig, sizeof xig);
  2073. if (error)
  2074. return (error);
  2075. error = syncache_pcblist(req);
  2076. if (error)
  2077. return (error);
  2078. NET_EPOCH_ENTER(et);
  2079. for (inp = CK_LIST_FIRST(V_tcbinfo.ipi_listhead);
  2080. inp != NULL;
  2081. inp = CK_LIST_NEXT(inp, inp_list)) {
  2082. INP_RLOCK(inp);
  2083. if (inp->inp_gencnt <= xig.xig_gen) {
  2084. int crerr;
  2085. /*
  2086. * XXX: This use of cr_cansee(), introduced with
  2087. * TCP state changes, is not quite right, but for
  2088. * now, better than nothing.
  2089. */
  2090. if (inp->inp_flags & INP_TIMEWAIT) {
  2091. if (intotw(inp) != NULL)
  2092. crerr = cr_cansee(req->td->td_ucred,
  2093. intotw(inp)->tw_cred);
  2094. else
  2095. crerr = EINVAL; /* Skip this inp. */
  2096. } else
  2097. crerr = cr_canseeinpcb(req->td->td_ucred, inp);
  2098. if (crerr == 0) {
  2099. struct xtcpcb xt;
  2100. tcp_inptoxtp(inp, &xt);
  2101. INP_RUNLOCK(inp);
  2102. error = SYSCTL_OUT(req, &xt, sizeof xt);
  2103. if (error)
  2104. break;
  2105. else
  2106. continue;
  2107. }
  2108. }
  2109. INP_RUNLOCK(inp);
  2110. }
  2111. NET_EPOCH_EXIT(et);
  2112. if (!error) {
  2113. /*
  2114. * Give the user an updated idea of our state.
  2115. * If the generation differs from what we told
  2116. * her before, she knows that something happened
  2117. * while we were processing this request, and it
  2118. * might be necessary to retry.
  2119. */
  2120. xig.xig_gen = V_tcbinfo.ipi_gencnt;
  2121. xig.xig_sogen = so_gencnt;
  2122. xig.xig_count = V_tcbinfo.ipi_count +
  2123. counter_u64_fetch(V_tcps_states[TCPS_SYN_RECEIVED]);
  2124. error = SYSCTL_OUT(req, &xig, sizeof xig);
  2125. }
  2126. return (error);
  2127. }
  2128. SYSCTL_PROC(_net_inet_tcp, TCPCTL_PCBLIST, pcblist,
  2129. CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_NEEDGIANT,
  2130. NULL, 0, tcp_pcblist, "S,xtcpcb",
  2131. "List of active TCP connections");
  2132. #ifdef INET
  2133. static int
  2134. tcp_getcred(SYSCTL_HANDLER_ARGS)
  2135. {
  2136. struct xucred xuc;
  2137. struct sockaddr_in addrs[2];
  2138. struct epoch_tracker et;
  2139. struct inpcb *inp;
  2140. int error;
  2141. error = priv_check(req->td, PRIV_NETINET_GETCRED);
  2142. if (error)
  2143. return (error);
  2144. error = SYSCTL_IN(req, addrs, sizeof(addrs));
  2145. if (error)
  2146. return (error);
  2147. NET_EPOCH_ENTER(et);
  2148. inp = in_pcblookup(&V_tcbinfo, addrs[1].sin_addr, addrs[1].sin_port,
  2149. addrs[0].sin_addr, addrs[0].sin_port, INPLOOKUP_RLOCKPCB, NULL);
  2150. NET_EPOCH_EXIT(et);
  2151. if (inp != NULL) {
  2152. if (inp->inp_socket == NULL)
  2153. error = ENOENT;
  2154. if (error == 0)
  2155. error = cr_canseeinpcb(req->td->td_ucred, inp);
  2156. if (error == 0)
  2157. cru2x(inp->inp_cred, &xuc);
  2158. INP_RUNLOCK(inp);
  2159. } else
  2160. error = ENOENT;
  2161. if (error == 0)
  2162. error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
  2163. return (error);
  2164. }
  2165. SYSCTL_PROC(_net_inet_tcp, OID_AUTO, getcred,
  2166. CTLTYPE_OPAQUE | CTLFLAG_RW | CTLFLAG_PRISON | CTLFLAG_NEEDGIANT,
  2167. 0, 0, tcp_getcred, "S,xucred",
  2168. "Get the xucred of a TCP connection");
  2169. #endif /* INET */
  2170. #ifdef INET6
  2171. static int
  2172. tcp6_getcred(SYSCTL_HANDLER_ARGS)
  2173. {
  2174. struct epoch_tracker et;
  2175. struct xucred xuc;
  2176. struct sockaddr_in6 addrs[2];
  2177. struct inpcb *inp;
  2178. int error;
  2179. #ifdef INET
  2180. int mapped = 0;
  2181. #endif
  2182. error = priv_check(req->td, PRIV_NETINET_GETCRED);
  2183. if (error)
  2184. return (error);
  2185. error = SYSCTL_IN(req, addrs, sizeof(addrs));
  2186. if (error)
  2187. return (error);
  2188. if ((error = sa6_embedscope(&addrs[0], V_ip6_use_defzone)) != 0 ||
  2189. (error = sa6_embedscope(&addrs[1], V_ip6_use_defzone)) != 0) {
  2190. return (error);
  2191. }
  2192. if (IN6_IS_ADDR_V4MAPPED(&addrs[0].sin6_addr)) {
  2193. #ifdef INET
  2194. if (IN6_IS_ADDR_V4MAPPED(&addrs[1].sin6_addr))
  2195. mapped = 1;
  2196. else
  2197. #endif
  2198. return (EINVAL);
  2199. }
  2200. NET_EPOCH_ENTER(et);
  2201. #ifdef INET
  2202. if (mapped == 1)
  2203. inp = in_pcblookup(&V_tcbinfo,
  2204. *(struct in_addr *)&addrs[1].sin6_addr.s6_addr[12],
  2205. addrs[1].sin6_port,
  2206. *(struct in_addr *)&addrs[0].sin6_addr.s6_addr[12],
  2207. addrs[0].sin6_port, INPLOOKUP_RLOCKPCB, NULL);
  2208. else
  2209. #endif
  2210. inp = in6_pcblookup(&V_tcbinfo,
  2211. &addrs[1].sin6_addr, addrs[1].sin6_port,
  2212. &addrs[0].sin6_addr, addrs[0].sin6_port,
  2213. INPLOOKUP_RLOCKPCB, NULL);
  2214. NET_EPOCH_EXIT(et);
  2215. if (inp != NULL) {
  2216. if (inp->inp_socket == NULL)
  2217. error = ENOENT;
  2218. if (error == 0)
  2219. error = cr_canseeinpcb(req->td->td_ucred, inp);
  2220. if (error == 0)
  2221. cru2x(inp->inp_cred, &xuc);
  2222. INP_RUNLOCK(inp);
  2223. } else
  2224. error = ENOENT;
  2225. if (error == 0)
  2226. error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
  2227. return (error);
  2228. }
  2229. SYSCTL_PROC(_net_inet6_tcp6, OID_AUTO, getcred,
  2230. CTLTYPE_OPAQUE | CTLFLAG_RW | CTLFLAG_PRISON | CTLFLAG_NEEDGIANT,
  2231. 0, 0, tcp6_getcred, "S,xucred",
  2232. "Get the xucred of a TCP6 connection");
  2233. #endif /* INET6 */
  2234. #ifdef INET
  2235. void
  2236. tcp_ctlinput(int cmd, struct sockaddr *sa, void *vip)
  2237. {
  2238. struct ip *ip = vip;
  2239. struct tcphdr *th;
  2240. struct in_addr faddr;
  2241. struct inpcb *inp;
  2242. struct tcpcb *tp;
  2243. struct inpcb *(*notify)(struct inpcb *, int) = tcp_notify;
  2244. struct icmp *icp;
  2245. struct in_conninfo inc;
  2246. tcp_seq icmp_tcp_seq;
  2247. int mtu;
  2248. faddr = ((struct sockaddr_in *)sa)->sin_addr;
  2249. if (sa->sa_family != AF_INET || faddr.s_addr == INADDR_ANY)
  2250. return;
  2251. if (cmd == PRC_MSGSIZE)
  2252. notify = tcp_mtudisc_notify;
  2253. else if (V_icmp_may_rst && (cmd == PRC_UNREACH_ADMIN_PROHIB ||
  2254. cmd == PRC_UNREACH_PORT || cmd == PRC_UNREACH_PROTOCOL ||
  2255. cmd == PRC_TIMXCEED_INTRANS) && ip)
  2256. notify = tcp_drop_syn_sent;
  2257. /*
  2258. * Hostdead is ugly because it goes linearly through all PCBs.
  2259. * XXX: We never get this from ICMP, otherwise it makes an
  2260. * excellent DoS attack on machines with many connections.
  2261. */
  2262. else if (cmd == PRC_HOSTDEAD)
  2263. ip = NULL;
  2264. else if ((unsigned)cmd >= PRC_NCMDS || inetctlerrmap[cmd] == 0)
  2265. return;
  2266. if (ip == NULL) {
  2267. in_pcbnotifyall(&V_tcbinfo, faddr, inetctlerrmap[cmd], notify);
  2268. return;
  2269. }
  2270. icp = (struct icmp *)((caddr_t)ip - offsetof(struct icmp, icmp_ip));
  2271. th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
  2272. inp = in_pcblookup(&V_tcbinfo, faddr, th->th_dport, ip->ip_src,
  2273. th->th_sport, INPLOOKUP_WLOCKPCB, NULL);
  2274. if (inp != NULL && PRC_IS_REDIRECT(cmd)) {
  2275. /* signal EHOSTDOWN, as it flushes the cached route */
  2276. inp = (*notify)(inp, EHOSTDOWN);
  2277. goto out;
  2278. }
  2279. icmp_tcp_seq = th->th_seq;
  2280. if (inp != NULL) {
  2281. if (!(inp->inp_flags & INP_TIMEWAIT) &&
  2282. !(inp->inp_flags & INP_DROPPED) &&
  2283. !(inp->inp_socket == NULL)) {
  2284. tp = intotcpcb(inp);
  2285. if (SEQ_GEQ(ntohl(icmp_tcp_seq), tp->snd_una) &&
  2286. SEQ_LT(ntohl(icmp_tcp_seq), tp->snd_max)) {
  2287. if (cmd == PRC_MSGSIZE) {
  2288. /*
  2289. * MTU discovery:
  2290. * If we got a needfrag set the MTU
  2291. * in the route to the suggested new
  2292. * value (if given) and then notify.
  2293. */
  2294. mtu = ntohs(icp->icmp_nextmtu);
  2295. /*
  2296. * If no alternative MTU was
  2297. * proposed, try the next smaller
  2298. * one.
  2299. */
  2300. if (!mtu)
  2301. mtu = ip_next_mtu(
  2302. ntohs(ip->ip_len), 1);
  2303. if (mtu < V_tcp_minmss +
  2304. sizeof(struct tcpiphdr))
  2305. mtu = V_tcp_minmss +
  2306. sizeof(struct tcpiphdr);
  2307. /*
  2308. * Only process the offered MTU if it
  2309. * is smaller than the current one.
  2310. */
  2311. if (mtu < tp->t_maxseg +
  2312. sizeof(struct tcpiphdr)) {
  2313. bzero(&inc, sizeof(inc));
  2314. inc.inc_faddr = faddr;
  2315. inc.inc_fibnum =
  2316. inp->inp_inc.inc_fibnum;
  2317. tcp_hc_updatemtu(&inc, mtu);
  2318. tcp_mtudisc(inp, mtu);
  2319. }
  2320. } else
  2321. inp = (*notify)(inp,
  2322. inetctlerrmap[cmd]);
  2323. }
  2324. }
  2325. } else {
  2326. bzero(&inc, sizeof(inc));
  2327. inc.inc_fport = th->th_dport;
  2328. inc.inc_lport = th->th_sport;
  2329. inc.inc_faddr = faddr;
  2330. inc.inc_laddr = ip->ip_src;
  2331. syncache_unreach(&inc, icmp_tcp_seq);
  2332. }
  2333. out:
  2334. if (inp != NULL)
  2335. INP_WUNLOCK(inp);
  2336. }
  2337. #endif /* INET */
  2338. #ifdef INET6
  2339. void
  2340. tcp6_ctlinput(int cmd, struct sockaddr *sa, void *d)
  2341. {
  2342. struct in6_addr *dst;
  2343. struct inpcb *(*notify)(struct inpcb *, int) = tcp_notify;
  2344. struct ip6_hdr *ip6;
  2345. struct mbuf *m;
  2346. struct inpcb *inp;
  2347. struct tcpcb *tp;
  2348. struct icmp6_hdr *icmp6;
  2349. struct ip6ctlparam *ip6cp = NULL;
  2350. const struct sockaddr_in6 *sa6_src = NULL;
  2351. struct in_conninfo inc;
  2352. struct tcp_ports {
  2353. uint16_t th_sport;
  2354. uint16_t th_dport;
  2355. } t_ports;
  2356. tcp_seq icmp_tcp_seq;
  2357. unsigned int mtu;
  2358. unsigned int off;
  2359. if (sa->sa_family != AF_INET6 ||
  2360. sa->sa_len != sizeof(struct sockaddr_in6))
  2361. return;
  2362. /* if the parameter is from icmp6, decode it. */
  2363. if (d != NULL) {
  2364. ip6cp = (struct ip6ctlparam *)d;
  2365. icmp6 = ip6cp->ip6c_icmp6;
  2366. m = ip6cp->ip6c_m;
  2367. ip6 = ip6cp->ip6c_ip6;
  2368. off = ip6cp->ip6c_off;
  2369. sa6_src = ip6cp->ip6c_src;
  2370. dst = ip6cp->ip6c_finaldst;
  2371. } else {
  2372. m = NULL;
  2373. ip6 = NULL;
  2374. off = 0; /* fool gcc */
  2375. sa6_src = &sa6_any;
  2376. dst = NULL;
  2377. }
  2378. if (cmd == PRC_MSGSIZE)
  2379. notify = tcp_mtudisc_notify;
  2380. else if (V_icmp_may_rst && (cmd == PRC_UNREACH_ADMIN_PROHIB ||
  2381. cmd == PRC_UNREACH_PORT || cmd == PRC_UNREACH_PROTOCOL ||
  2382. cmd == PRC_TIMXCEED_INTRANS) && ip6 != NULL)
  2383. notify = tcp_drop_syn_sent;
  2384. /*
  2385. * Hostdead is ugly because it goes linearly through all PCBs.
  2386. * XXX: We never get this from ICMP, otherwise it makes an
  2387. * excellent DoS attack on machines with many connections.
  2388. */
  2389. else if (cmd == PRC_HOSTDEAD)
  2390. ip6 = NULL;
  2391. else if ((unsigned)cmd >= PRC_NCMDS || inet6ctlerrmap[cmd] == 0)
  2392. return;
  2393. if (ip6 == NULL) {
  2394. in6_pcbnotify(&V_tcbinfo, sa, 0,
  2395. (const struct sockaddr *)sa6_src,
  2396. 0, cmd, NULL, notify);
  2397. return;
  2398. }
  2399. /* Check if we can safely get the ports from the tcp hdr */
  2400. if (m == NULL ||
  2401. (m->m_pkthdr.len <
  2402. (int32_t) (off + sizeof(struct tcp_ports)))) {
  2403. return;
  2404. }
  2405. bzero(&t_ports, sizeof(struct tcp_ports));
  2406. m_copydata(m, off, sizeof(struct tcp_ports), (caddr_t)&t_ports);
  2407. inp = in6_pcblookup(&V_tcbinfo, &ip6->ip6_dst, t_ports.th_dport,
  2408. &ip6->ip6_src, t_ports.th_sport, INPLOOKUP_WLOCKPCB, NULL);
  2409. if (inp != NULL && PRC_IS_REDIRECT(cmd)) {
  2410. /* signal EHOSTDOWN, as it flushes the cached route */
  2411. inp = (*notify)(inp, EHOSTDOWN);
  2412. goto out;
  2413. }
  2414. off += sizeof(struct tcp_ports);
  2415. if (m->m_pkthdr.len < (int32_t) (off + sizeof(tcp_seq))) {
  2416. goto out;
  2417. }
  2418. m_copydata(m, off, sizeof(tcp_seq), (caddr_t)&icmp_tcp_seq);
  2419. if (inp != NULL) {
  2420. if (!(inp->inp_flags & INP_TIMEWAIT) &&
  2421. !(inp->inp_flags & INP_DROPPED) &&
  2422. !(inp->inp_socket == NULL)) {
  2423. tp = intotcpcb(inp);
  2424. if (SEQ_GEQ(ntohl(icmp_tcp_seq), tp->snd_una) &&
  2425. SEQ_LT(ntohl(icmp_tcp_seq), tp->snd_max)) {
  2426. if (cmd == PRC_MSGSIZE) {
  2427. /*
  2428. * MTU discovery:
  2429. * If we got a needfrag set the MTU
  2430. * in the route to the suggested new
  2431. * value (if given) and then notify.
  2432. */
  2433. mtu = ntohl(icmp6->icmp6_mtu);
  2434. /*
  2435. * If no alternative MTU was
  2436. * proposed, or the proposed
  2437. * MTU was too small, set to
  2438. * the min.
  2439. */
  2440. if (mtu < IPV6_MMTU)
  2441. mtu = IPV6_MMTU - 8;
  2442. bzero(&inc, sizeof(inc));
  2443. inc.inc_fibnum = M_GETFIB(m);
  2444. inc.inc_flags |= INC_ISIPV6;
  2445. inc.inc6_faddr = *dst;
  2446. if (in6_setscope(&inc.inc6_faddr,
  2447. m->m_pkthdr.rcvif, NULL))
  2448. goto out;
  2449. /*
  2450. * Only process the offered MTU if it
  2451. * is smaller than the current one.
  2452. */
  2453. if (mtu < tp->t_maxseg +
  2454. sizeof (struct tcphdr) +
  2455. sizeof (struct ip6_hdr)) {
  2456. tcp_hc_updatemtu(&inc, mtu);
  2457. tcp_mtudisc(inp, mtu);
  2458. ICMP6STAT_INC(icp6s_pmtuchg);
  2459. }
  2460. } else
  2461. inp = (*notify)(inp,
  2462. inet6ctlerrmap[cmd]);
  2463. }
  2464. }
  2465. } else {
  2466. bzero(&inc, sizeof(inc));
  2467. inc.inc_fibnum = M_GETFIB(m);
  2468. inc.inc_flags |= INC_ISIPV6;
  2469. inc.inc_fport = t_ports.th_dport;
  2470. inc.inc_lport = t_ports.th_sport;
  2471. inc.inc6_faddr = *dst;
  2472. inc.inc6_laddr = ip6->ip6_src;
  2473. syncache_unreach(&inc, icmp_tcp_seq);
  2474. }
  2475. out:
  2476. if (inp != NULL)
  2477. INP_WUNLOCK(inp);
  2478. }
  2479. #endif /* INET6 */
  2480. static uint32_t
  2481. tcp_keyed_hash(struct in_conninfo *inc, u_char *key, u_int len)
  2482. {
  2483. SIPHASH_CTX ctx;
  2484. uint32_t hash[2];
  2485. KASSERT(len >= SIPHASH_KEY_LENGTH,
  2486. ("%s: keylen %u too short ", __func__, len));
  2487. SipHash24_Init(&ctx);
  2488. SipHash_SetKey(&ctx, (uint8_t *)key);
  2489. SipHash_Update(&ctx, &inc->inc_fport, sizeof(uint16_t));
  2490. SipHash_Update(&ctx, &inc->inc_lport, sizeof(uint16_t));
  2491. switch (inc->inc_flags & INC_ISIPV6) {
  2492. #ifdef INET
  2493. case 0:
  2494. SipHash_Update(&ctx, &inc->inc_faddr, sizeof(struct in_addr));
  2495. SipHash_Update(&ctx, &inc->inc_laddr, sizeof(struct in_addr));
  2496. break;
  2497. #endif
  2498. #ifdef INET6
  2499. case INC_ISIPV6:
  2500. SipHash_Update(&ctx, &inc->inc6_faddr, sizeof(struct in6_addr));
  2501. SipHash_Update(&ctx, &inc->inc6_laddr, sizeof(struct in6_addr));
  2502. break;
  2503. #endif
  2504. }
  2505. SipHash_Final((uint8_t *)hash, &ctx);
  2506. return (hash[0] ^ hash[1]);
  2507. }
  2508. uint32_t
  2509. tcp_new_ts_offset(struct in_conninfo *inc)
  2510. {
  2511. struct in_conninfo inc_store, *local_inc;
  2512. if (!V_tcp_ts_offset_per_conn) {
  2513. memcpy(&inc_store, inc, sizeof(struct in_conninfo));
  2514. inc_store.inc_lport = 0;
  2515. inc_store.inc_fport = 0;
  2516. local_inc = &inc_store;
  2517. } else {
  2518. local_inc = inc;
  2519. }
  2520. return (tcp_keyed_hash(local_inc, V_ts_offset_secret,
  2521. sizeof(V_ts_offset_secret)));
  2522. }
  2523. /*
  2524. * Following is where TCP initial sequence number generation occurs.
  2525. *
  2526. * There are two places where we must use initial sequence numbers:
  2527. * 1. In SYN-ACK packets.
  2528. * 2. In SYN packets.
  2529. *
  2530. * All ISNs for SYN-ACK packets are generated by the syncache. See
  2531. * tcp_syncache.c for details.
  2532. *
  2533. * The ISNs in SYN packets must be monotonic; TIME_WAIT recycling
  2534. * depends on this property. In addition, these ISNs should be
  2535. * unguessable so as to prevent connection hijacking. To satisfy
  2536. * the requirements of this situation, the algorithm outlined in
  2537. * RFC 1948 is used, with only small modifications.
  2538. *
  2539. * Implementation details:
  2540. *
  2541. * Time is based off the system timer, and is corrected so that it
  2542. * increases by one megabyte per second. This allows for proper
  2543. * recycling on high speed LANs while still leaving over an hour
  2544. * before rollover.
  2545. *
  2546. * As reading the *exact* system time is too expensive to be done
  2547. * whenever setting up a TCP connection, we increment the time
  2548. * offset in two ways. First, a small random positive increment
  2549. * is added to isn_offset for each connection that is set up.
  2550. * Second, the function tcp_isn_tick fires once per clock tick
  2551. * and increments isn_offset as necessary so that sequence numbers
  2552. * are incremented at approximately ISN_BYTES_PER_SECOND. The
  2553. * random positive increments serve only to ensure that the same
  2554. * exact sequence number is never sent out twice (as could otherwise
  2555. * happen when a port is recycled in less than the system tick
  2556. * interval.)
  2557. *
  2558. * net.inet.tcp.isn_reseed_interval controls the number of seconds
  2559. * between seeding of isn_secret. This is normally set to zero,
  2560. * as reseeding should not be necessary.
  2561. *
  2562. * Locking of the global variables isn_secret, isn_last_reseed, isn_offset,
  2563. * isn_offset_old, and isn_ctx is performed using the ISN lock. In
  2564. * general, this means holding an exclusive (write) lock.
  2565. */
  2566. #define ISN_BYTES_PER_SECOND 1048576
  2567. #define ISN_STATIC_INCREMENT 4096
  2568. #define ISN_RANDOM_INCREMENT (4096 - 1)
  2569. #define ISN_SECRET_LENGTH SIPHASH_KEY_LENGTH
  2570. VNET_DEFINE_STATIC(u_char, isn_secret[ISN_SECRET_LENGTH]);
  2571. VNET_DEFINE_STATIC(int, isn_last);
  2572. VNET_DEFINE_STATIC(int, isn_last_reseed);
  2573. VNET_DEFINE_STATIC(u_int32_t, isn_offset);
  2574. VNET_DEFINE_STATIC(u_int32_t, isn_offset_old);
  2575. #define V_isn_secret VNET(isn_secret)
  2576. #define V_isn_last VNET(isn_last)
  2577. #define V_isn_last_reseed VNET(isn_last_reseed)
  2578. #define V_isn_offset VNET(isn_offset)
  2579. #define V_isn_offset_old VNET(isn_offset_old)
  2580. tcp_seq
  2581. tcp_new_isn(struct in_conninfo *inc)
  2582. {
  2583. tcp_seq new_isn;
  2584. u_int32_t projected_offset;
  2585. ISN_LOCK();
  2586. /* Seed if this is the first use, reseed if requested. */
  2587. if ((V_isn_last_reseed == 0) || ((V_tcp_isn_reseed_interval > 0) &&
  2588. (((u_int)V_isn_last_reseed + (u_int)V_tcp_isn_reseed_interval*hz)
  2589. < (u_int)ticks))) {
  2590. arc4rand(&V_isn_secret, sizeof(V_isn_secret), 0);
  2591. V_isn_last_reseed = ticks;
  2592. }
  2593. /* Compute the hash and return the ISN. */
  2594. new_isn = (tcp_seq)tcp_keyed_hash(inc, V_isn_secret,
  2595. sizeof(V_isn_secret));
  2596. V_isn_offset += ISN_STATIC_INCREMENT +
  2597. (arc4random() & ISN_RANDOM_INCREMENT);
  2598. if (ticks != V_isn_last) {
  2599. projected_offset = V_isn_offset_old +
  2600. ISN_BYTES_PER_SECOND / hz * (ticks - V_isn_last);
  2601. if (SEQ_GT(projected_offset, V_isn_offset))
  2602. V_isn_offset = projected_offset;
  2603. V_isn_offset_old = V_isn_offset;
  2604. V_isn_last = ticks;
  2605. }
  2606. new_isn += V_isn_offset;
  2607. ISN_UNLOCK();
  2608. return (new_isn);
  2609. }
  2610. /*
  2611. * When a specific ICMP unreachable message is received and the
  2612. * connection state is SYN-SENT, drop the connection. This behavior
  2613. * is controlled by the icmp_may_rst sysctl.
  2614. */
  2615. struct inpcb *
  2616. tcp_drop_syn_sent(struct inpcb *inp, int errno)
  2617. {
  2618. struct tcpcb *tp;
  2619. NET_EPOCH_ASSERT();
  2620. INP_WLOCK_ASSERT(inp);
  2621. if ((inp->inp_flags & INP_TIMEWAIT) ||
  2622. (inp->inp_flags & INP_DROPPED))
  2623. return (inp);
  2624. tp = intotcpcb(inp);
  2625. if (tp->t_state != TCPS_SYN_SENT)
  2626. return (inp);
  2627. if (IS_FASTOPEN(tp->t_flags))
  2628. tcp_fastopen_disable_path(tp);
  2629. tp = tcp_drop(tp, errno);
  2630. if (tp != NULL)
  2631. return (inp);
  2632. else
  2633. return (NULL);
  2634. }
  2635. /*
  2636. * When `need fragmentation' ICMP is received, update our idea of the MSS
  2637. * based on the new value. Also nudge TCP to send something, since we
  2638. * know the packet we just sent was dropped.
  2639. * This duplicates some code in the tcp_mss() function in tcp_input.c.
  2640. */
  2641. static struct inpcb *
  2642. tcp_mtudisc_notify(struct inpcb *inp, int error)
  2643. {
  2644. tcp_mtudisc(inp, -1);
  2645. return (inp);
  2646. }
  2647. static void
  2648. tcp_mtudisc(struct inpcb *inp, int mtuoffer)
  2649. {
  2650. struct tcpcb *tp;
  2651. struct socket *so;
  2652. INP_WLOCK_ASSERT(inp);
  2653. if ((inp->inp_flags & INP_TIMEWAIT) ||
  2654. (inp->inp_flags & INP_DROPPED))
  2655. return;
  2656. tp = intotcpcb(inp);
  2657. KASSERT(tp != NULL, ("tcp_mtudisc: tp == NULL"));
  2658. tcp_mss_update(tp, -1, mtuoffer, NULL, NULL);
  2659. so = inp->inp_socket;
  2660. SOCKBUF_LOCK(&so->so_snd);
  2661. /* If the mss is larger than the socket buffer, decrease the mss. */
  2662. if (so->so_snd.sb_hiwat < tp->t_maxseg)
  2663. tp->t_maxseg = so->so_snd.sb_hiwat;
  2664. SOCKBUF_UNLOCK(&so->so_snd);
  2665. TCPSTAT_INC(tcps_mturesent);
  2666. tp->t_rtttime = 0;
  2667. tp->snd_nxt = tp->snd_una;
  2668. tcp_free_sackholes(tp);
  2669. tp->snd_recover = tp->snd_max;
  2670. if (tp->t_flags & TF_SACK_PERMIT)
  2671. EXIT_FASTRECOVERY(tp->t_flags);
  2672. tp->t_fb->tfb_tcp_output(tp);
  2673. }
  2674. #ifdef INET
  2675. /*
  2676. * Look-up the routing entry to the peer of this inpcb. If no route
  2677. * is found and it cannot be allocated, then return 0. This routine
  2678. * is called by TCP routines that access the rmx structure and by
  2679. * tcp_mss_update to get the peer/interface MTU.
  2680. */
  2681. uint32_t
  2682. tcp_maxmtu(struct in_conninfo *inc, struct tcp_ifcap *cap)
  2683. {
  2684. struct nhop_object *nh;
  2685. struct ifnet *ifp;
  2686. uint32_t maxmtu = 0;
  2687. KASSERT(inc != NULL, ("tcp_maxmtu with NULL in_conninfo pointer"));
  2688. if (inc->inc_faddr.s_addr != INADDR_ANY) {
  2689. nh = fib4_lookup(inc->inc_fibnum, inc->inc_faddr, 0, NHR_NONE, 0);
  2690. if (nh == NULL)
  2691. return (0);
  2692. ifp = nh->nh_ifp;
  2693. maxmtu = nh->nh_mtu;
  2694. /* Report additional interface capabilities. */
  2695. if (cap != NULL) {
  2696. if (ifp->if_capenable & IFCAP_TSO4 &&
  2697. ifp->if_hwassist & CSUM_TSO) {
  2698. cap->ifcap |= CSUM_TSO;
  2699. cap->tsomax = ifp->if_hw_tsomax;
  2700. cap->tsomaxsegcount = ifp->if_hw_tsomaxsegcount;
  2701. cap->tsomaxsegsize = ifp->if_hw_tsomaxsegsize;
  2702. }
  2703. }
  2704. }
  2705. return (maxmtu);
  2706. }
  2707. #endif /* INET */
  2708. #ifdef INET6
  2709. uint32_t
  2710. tcp_maxmtu6(struct in_conninfo *inc, struct tcp_ifcap *cap)
  2711. {
  2712. struct nhop_object *nh;
  2713. struct in6_addr dst6;
  2714. uint32_t scopeid;
  2715. struct ifnet *ifp;
  2716. uint32_t maxmtu = 0;
  2717. KASSERT(inc != NULL, ("tcp_maxmtu6 with NULL in_conninfo pointer"));
  2718. if (inc->inc_flags & INC_IPV6MINMTU)
  2719. return (IPV6_MMTU);
  2720. if (!IN6_IS_ADDR_UNSPECIFIED(&inc->inc6_faddr)) {
  2721. in6_splitscope(&inc->inc6_faddr, &dst6, &scopeid);
  2722. nh = fib6_lookup(inc->inc_fibnum, &dst6, scopeid, NHR_NONE, 0);
  2723. if (nh == NULL)
  2724. return (0);
  2725. ifp = nh->nh_ifp;
  2726. maxmtu = nh->nh_mtu;
  2727. /* Report additional interface capabilities. */
  2728. if (cap != NULL) {
  2729. if (ifp->if_capenable & IFCAP_TSO6 &&
  2730. ifp->if_hwassist & CSUM_TSO) {
  2731. cap->ifcap |= CSUM_TSO;
  2732. cap->tsomax = ifp->if_hw_tsomax;
  2733. cap->tsomaxsegcount = ifp->if_hw_tsomaxsegcount;
  2734. cap->tsomaxsegsize = ifp->if_hw_tsomaxsegsize;
  2735. }
  2736. }
  2737. }
  2738. return (maxmtu);
  2739. }
  2740. #endif /* INET6 */
  2741. /*
  2742. * Calculate effective SMSS per RFC5681 definition for a given TCP
  2743. * connection at its current state, taking into account SACK and etc.
  2744. */
  2745. u_int
  2746. tcp_maxseg(const struct tcpcb *tp)
  2747. {
  2748. u_int optlen;
  2749. if (tp->t_flags & TF_NOOPT)
  2750. return (tp->t_maxseg);
  2751. /*
  2752. * Here we have a simplified code from tcp_addoptions(),
  2753. * without a proper loop, and having most of paddings hardcoded.
  2754. * We might make mistakes with padding here in some edge cases,
  2755. * but this is harmless, since result of tcp_maxseg() is used
  2756. * only in cwnd and ssthresh estimations.
  2757. */
  2758. if (TCPS_HAVEESTABLISHED(tp->t_state)) {
  2759. if (tp->t_flags & TF_RCVD_TSTMP)
  2760. optlen = TCPOLEN_TSTAMP_APPA;
  2761. else
  2762. optlen = 0;
  2763. #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
  2764. if (tp->t_flags & TF_SIGNATURE)
  2765. optlen += PADTCPOLEN(TCPOLEN_SIGNATURE);
  2766. #endif
  2767. if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks > 0) {
  2768. optlen += TCPOLEN_SACKHDR;
  2769. optlen += tp->rcv_numsacks * TCPOLEN_SACK;
  2770. optlen = PADTCPOLEN(optlen);
  2771. }
  2772. } else {
  2773. if (tp->t_flags & TF_REQ_TSTMP)
  2774. optlen = TCPOLEN_TSTAMP_APPA;
  2775. else
  2776. optlen = PADTCPOLEN(TCPOLEN_MAXSEG);
  2777. if (tp->t_flags & TF_REQ_SCALE)
  2778. optlen += PADTCPOLEN(TCPOLEN_WINDOW);
  2779. #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
  2780. if (tp->t_flags & TF_SIGNATURE)
  2781. optlen += PADTCPOLEN(TCPOLEN_SIGNATURE);
  2782. #endif
  2783. if (tp->t_flags & TF_SACK_PERMIT)
  2784. optlen += PADTCPOLEN(TCPOLEN_SACK_PERMITTED);
  2785. }
  2786. #undef PAD
  2787. optlen = min(optlen, TCP_MAXOLEN);
  2788. return (tp->t_maxseg - optlen);
  2789. }
  2790. static int
  2791. sysctl_drop(SYSCTL_HANDLER_ARGS)
  2792. {
  2793. /* addrs[0] is a foreign socket, addrs[1] is a local one. */
  2794. struct sockaddr_storage addrs[2];
  2795. struct inpcb *inp;
  2796. struct tcpcb *tp;
  2797. struct tcptw *tw;
  2798. struct sockaddr_in *fin, *lin;
  2799. struct epoch_tracker et;
  2800. #ifdef INET6
  2801. struct sockaddr_in6 *fin6, *lin6;
  2802. #endif
  2803. int error;
  2804. inp = NULL;
  2805. fin = lin = NULL;
  2806. #ifdef INET6
  2807. fin6 = lin6 = NULL;
  2808. #endif
  2809. error = 0;
  2810. if (req->oldptr != NULL || req->oldlen != 0)
  2811. return (EINVAL);
  2812. if (req->newptr == NULL)
  2813. return (EPERM);
  2814. if (req->newlen < sizeof(addrs))
  2815. return (ENOMEM);
  2816. error = SYSCTL_IN(req, &addrs, sizeof(addrs));
  2817. if (error)
  2818. return (error);
  2819. switch (addrs[0].ss_family) {
  2820. #ifdef INET6
  2821. case AF_INET6:
  2822. fin6 = (struct sockaddr_in6 *)&addrs[0];
  2823. lin6 = (struct sockaddr_in6 *)&addrs[1];
  2824. if (fin6->sin6_len != sizeof(struct sockaddr_in6) ||
  2825. lin6->sin6_len != sizeof(struct sockaddr_in6))
  2826. return (EINVAL);
  2827. if (IN6_IS_ADDR_V4MAPPED(&fin6->sin6_addr)) {
  2828. if (!IN6_IS_ADDR_V4MAPPED(&lin6->sin6_addr))
  2829. return (EINVAL);
  2830. in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[0]);
  2831. in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[1]);
  2832. fin = (struct sockaddr_in *)&addrs[0];
  2833. lin = (struct sockaddr_in *)&addrs[1];
  2834. break;
  2835. }
  2836. error = sa6_embedscope(fin6, V_ip6_use_defzone);
  2837. if (error)
  2838. return (error);
  2839. error = sa6_embedscope(lin6, V_ip6_use_defzone);
  2840. if (error)
  2841. return (error);
  2842. break;
  2843. #endif
  2844. #ifdef INET
  2845. case AF_INET:
  2846. fin = (struct sockaddr_in *)&addrs[0];
  2847. lin = (struct sockaddr_in *)&addrs[1];
  2848. if (fin->sin_len != sizeof(struct sockaddr_in) ||
  2849. lin->sin_len != sizeof(struct sockaddr_in))
  2850. return (EINVAL);
  2851. break;
  2852. #endif
  2853. default:
  2854. return (EINVAL);
  2855. }
  2856. NET_EPOCH_ENTER(et);
  2857. switch (addrs[0].ss_family) {
  2858. #ifdef INET6
  2859. case AF_INET6:
  2860. inp = in6_pcblookup(&V_tcbinfo, &fin6->sin6_addr,
  2861. fin6->sin6_port, &lin6->sin6_addr, lin6->sin6_port,
  2862. INPLOOKUP_WLOCKPCB, NULL);
  2863. break;
  2864. #endif
  2865. #ifdef INET
  2866. case AF_INET:
  2867. inp = in_pcblookup(&V_tcbinfo, fin->sin_addr, fin->sin_port,
  2868. lin->sin_addr, lin->sin_port, INPLOOKUP_WLOCKPCB, NULL);
  2869. break;
  2870. #endif
  2871. }
  2872. if (inp != NULL) {
  2873. if (inp->inp_flags & INP_TIMEWAIT) {
  2874. /*
  2875. * XXXRW: There currently exists a state where an
  2876. * inpcb is present, but its timewait state has been
  2877. * discarded. For now, don't allow dropping of this
  2878. * type of inpcb.
  2879. */
  2880. tw = intotw(inp);
  2881. if (tw != NULL)
  2882. tcp_twclose(tw, 0);
  2883. else
  2884. INP_WUNLOCK(inp);
  2885. } else if (!(inp->inp_flags & INP_DROPPED) &&
  2886. !(inp->inp_socket->so_options & SO_ACCEPTCONN)) {
  2887. tp = intotcpcb(inp);
  2888. tp = tcp_drop(tp, ECONNABORTED);
  2889. if (tp != NULL)
  2890. INP_WUNLOCK(inp);
  2891. } else
  2892. INP_WUNLOCK(inp);
  2893. } else
  2894. error = ESRCH;
  2895. NET_EPOCH_EXIT(et);
  2896. return (error);
  2897. }
  2898. SYSCTL_PROC(_net_inet_tcp, TCPCTL_DROP, drop,
  2899. CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP |
  2900. CTLFLAG_NEEDGIANT, NULL, 0, sysctl_drop, "",
  2901. "Drop TCP connection");
  2902. #ifdef KERN_TLS
  2903. static int
  2904. sysctl_switch_tls(SYSCTL_HANDLER_ARGS)
  2905. {
  2906. /* addrs[0] is a foreign socket, addrs[1] is a local one. */
  2907. struct sockaddr_storage addrs[2];
  2908. struct inpcb *inp;
  2909. struct sockaddr_in *fin, *lin;
  2910. struct epoch_tracker et;
  2911. #ifdef INET6
  2912. struct sockaddr_in6 *fin6, *lin6;
  2913. #endif
  2914. int error;
  2915. inp = NULL;
  2916. fin = lin = NULL;
  2917. #ifdef INET6
  2918. fin6 = lin6 = NULL;
  2919. #endif
  2920. error = 0;
  2921. if (req->oldptr != NULL || req->oldlen != 0)
  2922. return (EINVAL);
  2923. if (req->newptr == NULL)
  2924. return (EPERM);
  2925. if (req->newlen < sizeof(addrs))
  2926. return (ENOMEM);
  2927. error = SYSCTL_IN(req, &addrs, sizeof(addrs));
  2928. if (error)
  2929. return (error);
  2930. switch (addrs[0].ss_family) {
  2931. #ifdef INET6
  2932. case AF_INET6:
  2933. fin6 = (struct sockaddr_in6 *)&addrs[0];
  2934. lin6 = (struct sockaddr_in6 *)&addrs[1];
  2935. if (fin6->sin6_len != sizeof(struct sockaddr_in6) ||
  2936. lin6->sin6_len != sizeof(struct sockaddr_in6))
  2937. return (EINVAL);
  2938. if (IN6_IS_ADDR_V4MAPPED(&fin6->sin6_addr)) {
  2939. if (!IN6_IS_ADDR_V4MAPPED(&lin6->sin6_addr))
  2940. return (EINVAL);
  2941. in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[0]);
  2942. in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[1]);
  2943. fin = (struct sockaddr_in *)&addrs[0];
  2944. lin = (struct sockaddr_in *)&addrs[1];
  2945. break;
  2946. }
  2947. error = sa6_embedscope(fin6, V_ip6_use_defzone);
  2948. if (error)
  2949. return (error);
  2950. error = sa6_embedscope(lin6, V_ip6_use_defzone);
  2951. if (error)
  2952. return (error);
  2953. break;
  2954. #endif
  2955. #ifdef INET
  2956. case AF_INET:
  2957. fin = (struct sockaddr_in *)&addrs[0];
  2958. lin = (struct sockaddr_in *)&addrs[1];
  2959. if (fin->sin_len != sizeof(struct sockaddr_in) ||
  2960. lin->sin_len != sizeof(struct sockaddr_in))
  2961. return (EINVAL);
  2962. break;
  2963. #endif
  2964. default:
  2965. return (EINVAL);
  2966. }
  2967. NET_EPOCH_ENTER(et);
  2968. switch (addrs[0].ss_family) {
  2969. #ifdef INET6
  2970. case AF_INET6:
  2971. inp = in6_pcblookup(&V_tcbinfo, &fin6->sin6_addr,
  2972. fin6->sin6_port, &lin6->sin6_addr, lin6->sin6_port,
  2973. INPLOOKUP_WLOCKPCB, NULL);
  2974. break;
  2975. #endif
  2976. #ifdef INET
  2977. case AF_INET:
  2978. inp = in_pcblookup(&V_tcbinfo, fin->sin_addr, fin->sin_port,
  2979. lin->sin_addr, lin->sin_port, INPLOOKUP_WLOCKPCB, NULL);
  2980. break;
  2981. #endif
  2982. }
  2983. NET_EPOCH_EXIT(et);
  2984. if (inp != NULL) {
  2985. if ((inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) != 0 ||
  2986. inp->inp_socket == NULL) {
  2987. error = ECONNRESET;
  2988. INP_WUNLOCK(inp);
  2989. } else {
  2990. struct socket *so;
  2991. so = inp->inp_socket;
  2992. soref(so);
  2993. error = ktls_set_tx_mode(so,
  2994. arg2 == 0 ? TCP_TLS_MODE_SW : TCP_TLS_MODE_IFNET);
  2995. INP_WUNLOCK(inp);
  2996. SOCK_LOCK(so);
  2997. sorele(so);
  2998. }
  2999. } else
  3000. error = ESRCH;
  3001. return (error);
  3002. }
  3003. SYSCTL_PROC(_net_inet_tcp, OID_AUTO, switch_to_sw_tls,
  3004. CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP |
  3005. CTLFLAG_NEEDGIANT, NULL, 0, sysctl_switch_tls, "",
  3006. "Switch TCP connection to SW TLS");
  3007. SYSCTL_PROC(_net_inet_tcp, OID_AUTO, switch_to_ifnet_tls,
  3008. CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP |
  3009. CTLFLAG_NEEDGIANT, NULL, 1, sysctl_switch_tls, "",
  3010. "Switch TCP connection to ifnet TLS");
  3011. #endif
  3012. /*
  3013. * Generate a standardized TCP log line for use throughout the
  3014. * tcp subsystem. Memory allocation is done with M_NOWAIT to
  3015. * allow use in the interrupt context.
  3016. *
  3017. * NB: The caller MUST free(s, M_TCPLOG) the returned string.
  3018. * NB: The function may return NULL if memory allocation failed.
  3019. *
  3020. * Due to header inclusion and ordering limitations the struct ip
  3021. * and ip6_hdr pointers have to be passed as void pointers.
  3022. */
  3023. char *
  3024. tcp_log_vain(struct in_conninfo *inc, struct tcphdr *th, void *ip4hdr,
  3025. const void *ip6hdr)
  3026. {
  3027. /* Is logging enabled? */
  3028. if (V_tcp_log_in_vain == 0)
  3029. return (NULL);
  3030. return (tcp_log_addr(inc, th, ip4hdr, ip6hdr));
  3031. }
  3032. char *
  3033. tcp_log_addrs(struct in_conninfo *inc, struct tcphdr *th, void *ip4hdr,
  3034. const void *ip6hdr)
  3035. {
  3036. /* Is logging enabled? */
  3037. if (tcp_log_debug == 0)
  3038. return (NULL);
  3039. return (tcp_log_addr(inc, th, ip4hdr, ip6hdr));
  3040. }
  3041. static char *
  3042. tcp_log_addr(struct in_conninfo *inc, struct tcphdr *th, void *ip4hdr,
  3043. const void *ip6hdr)
  3044. {
  3045. char *s, *sp;
  3046. size_t size;
  3047. struct ip *ip;
  3048. #ifdef INET6
  3049. const struct ip6_hdr *ip6;
  3050. ip6 = (const struct ip6_hdr *)ip6hdr;
  3051. #endif /* INET6 */
  3052. ip = (struct ip *)ip4hdr;
  3053. /*
  3054. * The log line looks like this:
  3055. * "TCP: [1.2.3.4]:50332 to [1.2.3.4]:80 tcpflags 0x2<SYN>"
  3056. */
  3057. size = sizeof("TCP: []:12345 to []:12345 tcpflags 0x2<>") +
  3058. sizeof(PRINT_TH_FLAGS) + 1 +
  3059. #ifdef INET6
  3060. 2 * INET6_ADDRSTRLEN;
  3061. #else
  3062. 2 * INET_ADDRSTRLEN;
  3063. #endif /* INET6 */
  3064. s = malloc(size, M_TCPLOG, M_ZERO|M_NOWAIT);
  3065. if (s == NULL)
  3066. return (NULL);
  3067. strcat(s, "TCP: [");
  3068. sp = s + strlen(s);
  3069. if (inc && ((inc->inc_flags & INC_ISIPV6) == 0)) {
  3070. inet_ntoa_r(inc->inc_faddr, sp);
  3071. sp = s + strlen(s);
  3072. sprintf(sp, "]:%i to [", ntohs(inc->inc_fport));
  3073. sp = s + strlen(s);
  3074. inet_ntoa_r(inc->inc_laddr, sp);
  3075. sp = s + strlen(s);
  3076. sprintf(sp, "]:%i", ntohs(inc->inc_lport));
  3077. #ifdef INET6
  3078. } else if (inc) {
  3079. ip6_sprintf(sp, &inc->inc6_faddr);
  3080. sp = s + strlen(s);
  3081. sprintf(sp, "]:%i to [", ntohs(inc->inc_fport));
  3082. sp = s + strlen(s);
  3083. ip6_sprintf(sp, &inc->inc6_laddr);
  3084. sp = s + strlen(s);
  3085. sprintf(sp, "]:%i", ntohs(inc->inc_lport));
  3086. } else if (ip6 && th) {
  3087. ip6_sprintf(sp, &ip6->ip6_src);
  3088. sp = s + strlen(s);
  3089. sprintf(sp, "]:%i to [", ntohs(th->th_sport));
  3090. sp = s + strlen(s);
  3091. ip6_sprintf(sp, &ip6->ip6_dst);
  3092. sp = s + strlen(s);
  3093. sprintf(sp, "]:%i", ntohs(th->th_dport));
  3094. #endif /* INET6 */
  3095. #ifdef INET
  3096. } else if (ip && th) {
  3097. inet_ntoa_r(ip->ip_src, sp);
  3098. sp = s + strlen(s);
  3099. sprintf(sp, "]:%i to [", ntohs(th->th_sport));
  3100. sp = s + strlen(s);
  3101. inet_ntoa_r(ip->ip_dst, sp);
  3102. sp = s + strlen(s);
  3103. sprintf(sp, "]:%i", ntohs(th->th_dport));
  3104. #endif /* INET */
  3105. } else {
  3106. free(s, M_TCPLOG);
  3107. return (NULL);
  3108. }
  3109. sp = s + strlen(s);
  3110. if (th)
  3111. sprintf(sp, " tcpflags 0x%b", th->th_flags, PRINT_TH_FLAGS);
  3112. if (*(s + size - 1) != '\0')
  3113. panic("%s: string too long", __func__);
  3114. return (s);
  3115. }
  3116. /*
  3117. * A subroutine which makes it easy to track TCP state changes with DTrace.
  3118. * This function shouldn't be called for t_state initializations that don't
  3119. * correspond to actual TCP state transitions.
  3120. */
  3121. void
  3122. tcp_state_change(struct tcpcb *tp, int newstate)
  3123. {
  3124. #if defined(KDTRACE_HOOKS)
  3125. int pstate = tp->t_state;
  3126. #endif
  3127. TCPSTATES_DEC(tp->t_state);
  3128. TCPSTATES_INC(newstate);
  3129. tp->t_state = newstate;
  3130. TCP_PROBE6(state__change, NULL, tp, NULL, tp, NULL, pstate);
  3131. }
  3132. /*
  3133. * Create an external-format (``xtcpcb'') structure using the information in
  3134. * the kernel-format tcpcb structure pointed to by tp. This is done to
  3135. * reduce the spew of irrelevant information over this interface, to isolate
  3136. * user code from changes in the kernel structure, and potentially to provide
  3137. * information-hiding if we decide that some of this information should be
  3138. * hidden from users.
  3139. */
  3140. void
  3141. tcp_inptoxtp(const struct inpcb *inp, struct xtcpcb *xt)
  3142. {
  3143. struct tcpcb *tp = intotcpcb(inp);
  3144. sbintime_t now;
  3145. bzero(xt, sizeof(*xt));
  3146. if (inp->inp_flags & INP_TIMEWAIT) {
  3147. xt->t_state = TCPS_TIME_WAIT;
  3148. } else {
  3149. xt->t_state = tp->t_state;
  3150. xt->t_logstate = tp->t_logstate;
  3151. xt->t_flags = tp->t_flags;
  3152. xt->t_sndzerowin = tp->t_sndzerowin;
  3153. xt->t_sndrexmitpack = tp->t_sndrexmitpack;
  3154. xt->t_rcvoopack = tp->t_rcvoopack;
  3155. xt->t_rcv_wnd = tp->rcv_wnd;
  3156. xt->t_snd_wnd = tp->snd_wnd;
  3157. xt->t_snd_cwnd = tp->snd_cwnd;
  3158. xt->t_snd_ssthresh = tp->snd_ssthresh;
  3159. xt->t_maxseg = tp->t_maxseg;
  3160. xt->xt_ecn = (tp->t_flags2 & TF2_ECN_PERMIT) ? 1 : 0 +
  3161. (tp->t_flags2 & TF2_ACE_PERMIT) ? 2 : 0;
  3162. now = getsbinuptime();
  3163. #define COPYTIMER(ttt) do { \
  3164. if (callout_active(&tp->t_timers->ttt)) \
  3165. xt->ttt = (tp->t_timers->ttt.c_time - now) / \
  3166. SBT_1MS; \
  3167. else \
  3168. xt->ttt = 0; \
  3169. } while (0)
  3170. COPYTIMER(tt_delack);
  3171. COPYTIMER(tt_rexmt);
  3172. COPYTIMER(tt_persist);
  3173. COPYTIMER(tt_keep);
  3174. COPYTIMER(tt_2msl);
  3175. #undef COPYTIMER
  3176. xt->t_rcvtime = 1000 * (ticks - tp->t_rcvtime) / hz;
  3177. bcopy(tp->t_fb->tfb_tcp_block_name, xt->xt_stack,
  3178. TCP_FUNCTION_NAME_LEN_MAX);
  3179. bcopy(CC_ALGO(tp)->name, xt->xt_cc,
  3180. TCP_CA_NAME_MAX);
  3181. #ifdef TCP_BLACKBOX
  3182. (void)tcp_log_get_id(tp, xt->xt_logid);
  3183. #endif
  3184. }
  3185. xt->xt_len = sizeof(struct xtcpcb);
  3186. in_pcbtoxinpcb(inp, &xt->xt_inp);
  3187. if (inp->inp_socket == NULL)
  3188. xt->xt_inp.xi_socket.xso_protocol = IPPROTO_TCP;
  3189. }
  3190. void
  3191. tcp_log_end_status(struct tcpcb *tp, uint8_t status)
  3192. {
  3193. uint32_t bit, i;
  3194. if ((tp == NULL) ||
  3195. (status > TCP_EI_STATUS_MAX_VALUE) ||
  3196. (status == 0)) {
  3197. /* Invalid */
  3198. return;
  3199. }
  3200. if (status > (sizeof(uint32_t) * 8)) {
  3201. /* Should this be a KASSERT? */
  3202. return;
  3203. }
  3204. bit = 1U << (status - 1);
  3205. if (bit & tp->t_end_info_status) {
  3206. /* already logged */
  3207. return;
  3208. }
  3209. for (i = 0; i < TCP_END_BYTE_INFO; i++) {
  3210. if (tp->t_end_info_bytes[i] == TCP_EI_EMPTY_SLOT) {
  3211. tp->t_end_info_bytes[i] = status;
  3212. tp->t_end_info_status |= bit;
  3213. break;
  3214. }
  3215. }
  3216. }