tcp_ipv4.c 97 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /*
  3. * INET An implementation of the TCP/IP protocol suite for the LINUX
  4. * operating system. INET is implemented using the BSD Socket
  5. * interface as the means of communication with the user level.
  6. *
  7. * Implementation of the Transmission Control Protocol(TCP).
  8. *
  9. * IPv4 specific functions
  10. *
  11. * code split from:
  12. * linux/ipv4/tcp.c
  13. * linux/ipv4/tcp_input.c
  14. * linux/ipv4/tcp_output.c
  15. *
  16. * See tcp.c for author information
  17. */
  18. /*
  19. * Changes:
  20. * David S. Miller : New socket lookup architecture.
  21. * This code is dedicated to John Dyson.
  22. * David S. Miller : Change semantics of established hash,
  23. * half is devoted to TIME_WAIT sockets
  24. * and the rest go in the other half.
  25. * Andi Kleen : Add support for syncookies and fixed
  26. * some bugs: ip options weren't passed to
  27. * the TCP layer, missed a check for an
  28. * ACK bit.
  29. * Andi Kleen : Implemented fast path mtu discovery.
  30. * Fixed many serious bugs in the
  31. * request_sock handling and moved
  32. * most of it into the af independent code.
  33. * Added tail drop and some other bugfixes.
  34. * Added new listen semantics.
  35. * Mike McLagan : Routing by source
  36. * Juan Jose Ciarlante: ip_dynaddr bits
  37. * Andi Kleen: various fixes.
  38. * Vitaly E. Lavrov : Transparent proxy revived after year
  39. * coma.
  40. * Andi Kleen : Fix new listen.
  41. * Andi Kleen : Fix accept error reporting.
  42. * YOSHIFUJI Hideaki @USAGI and: Support IPV6_V6ONLY socket option, which
  43. * Alexey Kuznetsov allow both IPv4 and IPv6 sockets to bind
  44. * a single port at the same time.
  45. */
  46. #define pr_fmt(fmt) "TCP: " fmt
  47. #include <linux/bottom_half.h>
  48. #include <linux/types.h>
  49. #include <linux/fcntl.h>
  50. #include <linux/module.h>
  51. #include <linux/random.h>
  52. #include <linux/cache.h>
  53. #include <linux/jhash.h>
  54. #include <linux/init.h>
  55. #include <linux/times.h>
  56. #include <linux/slab.h>
  57. #include <linux/sched.h>
  58. #include <net/net_namespace.h>
  59. #include <net/icmp.h>
  60. #include <net/inet_hashtables.h>
  61. #include <net/tcp.h>
  62. #include <net/transp_v6.h>
  63. #include <net/ipv6.h>
  64. #include <net/inet_common.h>
  65. #include <net/timewait_sock.h>
  66. #include <net/xfrm.h>
  67. #include <net/secure_seq.h>
  68. #include <net/busy_poll.h>
  69. #include <net/rstreason.h>
  70. #include <linux/inet.h>
  71. #include <linux/ipv6.h>
  72. #include <linux/stddef.h>
  73. #include <linux/proc_fs.h>
  74. #include <linux/seq_file.h>
  75. #include <linux/inetdevice.h>
  76. #include <linux/btf_ids.h>
  77. #include <linux/skbuff_ref.h>
  78. #include <crypto/hash.h>
  79. #include <linux/scatterlist.h>
  80. #include <trace/events/tcp.h>
  81. #ifdef CONFIG_TCP_MD5SIG
  82. static int tcp_v4_md5_hash_hdr(char *md5_hash, const struct tcp_md5sig_key *key,
  83. __be32 daddr, __be32 saddr, const struct tcphdr *th);
  84. #endif
  85. struct inet_hashinfo tcp_hashinfo;
  86. EXPORT_SYMBOL(tcp_hashinfo);
  87. static DEFINE_PER_CPU(struct sock_bh_locked, ipv4_tcp_sk) = {
  88. .bh_lock = INIT_LOCAL_LOCK(bh_lock),
  89. };
  90. static DEFINE_MUTEX(tcp_exit_batch_mutex);
  91. static u32 tcp_v4_init_seq(const struct sk_buff *skb)
  92. {
  93. return secure_tcp_seq(ip_hdr(skb)->daddr,
  94. ip_hdr(skb)->saddr,
  95. tcp_hdr(skb)->dest,
  96. tcp_hdr(skb)->source);
  97. }
  98. static u32 tcp_v4_init_ts_off(const struct net *net, const struct sk_buff *skb)
  99. {
  100. return secure_tcp_ts_off(net, ip_hdr(skb)->daddr, ip_hdr(skb)->saddr);
  101. }
  102. int tcp_twsk_unique(struct sock *sk, struct sock *sktw, void *twp)
  103. {
  104. int reuse = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_tw_reuse);
  105. const struct inet_timewait_sock *tw = inet_twsk(sktw);
  106. const struct tcp_timewait_sock *tcptw = tcp_twsk(sktw);
  107. struct tcp_sock *tp = tcp_sk(sk);
  108. int ts_recent_stamp;
  109. if (READ_ONCE(tw->tw_substate) == TCP_FIN_WAIT2)
  110. reuse = 0;
  111. if (reuse == 2) {
  112. /* Still does not detect *everything* that goes through
  113. * lo, since we require a loopback src or dst address
  114. * or direct binding to 'lo' interface.
  115. */
  116. bool loopback = false;
  117. if (tw->tw_bound_dev_if == LOOPBACK_IFINDEX)
  118. loopback = true;
  119. #if IS_ENABLED(CONFIG_IPV6)
  120. if (tw->tw_family == AF_INET6) {
  121. if (ipv6_addr_loopback(&tw->tw_v6_daddr) ||
  122. ipv6_addr_v4mapped_loopback(&tw->tw_v6_daddr) ||
  123. ipv6_addr_loopback(&tw->tw_v6_rcv_saddr) ||
  124. ipv6_addr_v4mapped_loopback(&tw->tw_v6_rcv_saddr))
  125. loopback = true;
  126. } else
  127. #endif
  128. {
  129. if (ipv4_is_loopback(tw->tw_daddr) ||
  130. ipv4_is_loopback(tw->tw_rcv_saddr))
  131. loopback = true;
  132. }
  133. if (!loopback)
  134. reuse = 0;
  135. }
  136. /* With PAWS, it is safe from the viewpoint
  137. of data integrity. Even without PAWS it is safe provided sequence
  138. spaces do not overlap i.e. at data rates <= 80Mbit/sec.
  139. Actually, the idea is close to VJ's one, only timestamp cache is
  140. held not per host, but per port pair and TW bucket is used as state
  141. holder.
  142. If TW bucket has been already destroyed we fall back to VJ's scheme
  143. and use initial timestamp retrieved from peer table.
  144. */
  145. ts_recent_stamp = READ_ONCE(tcptw->tw_ts_recent_stamp);
  146. if (ts_recent_stamp &&
  147. (!twp || (reuse && time_after32(ktime_get_seconds(),
  148. ts_recent_stamp)))) {
  149. /* inet_twsk_hashdance_schedule() sets sk_refcnt after putting twsk
  150. * and releasing the bucket lock.
  151. */
  152. if (unlikely(!refcount_inc_not_zero(&sktw->sk_refcnt)))
  153. return 0;
  154. /* In case of repair and re-using TIME-WAIT sockets we still
  155. * want to be sure that it is safe as above but honor the
  156. * sequence numbers and time stamps set as part of the repair
  157. * process.
  158. *
  159. * Without this check re-using a TIME-WAIT socket with TCP
  160. * repair would accumulate a -1 on the repair assigned
  161. * sequence number. The first time it is reused the sequence
  162. * is -1, the second time -2, etc. This fixes that issue
  163. * without appearing to create any others.
  164. */
  165. if (likely(!tp->repair)) {
  166. u32 seq = tcptw->tw_snd_nxt + 65535 + 2;
  167. if (!seq)
  168. seq = 1;
  169. WRITE_ONCE(tp->write_seq, seq);
  170. tp->rx_opt.ts_recent = READ_ONCE(tcptw->tw_ts_recent);
  171. tp->rx_opt.ts_recent_stamp = ts_recent_stamp;
  172. }
  173. return 1;
  174. }
  175. return 0;
  176. }
  177. EXPORT_SYMBOL_GPL(tcp_twsk_unique);
  178. static int tcp_v4_pre_connect(struct sock *sk, struct sockaddr *uaddr,
  179. int addr_len)
  180. {
  181. /* This check is replicated from tcp_v4_connect() and intended to
  182. * prevent BPF program called below from accessing bytes that are out
  183. * of the bound specified by user in addr_len.
  184. */
  185. if (addr_len < sizeof(struct sockaddr_in))
  186. return -EINVAL;
  187. sock_owned_by_me(sk);
  188. return BPF_CGROUP_RUN_PROG_INET4_CONNECT(sk, uaddr, &addr_len);
  189. }
  190. /* This will initiate an outgoing connection. */
  191. int tcp_v4_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
  192. {
  193. struct sockaddr_in *usin = (struct sockaddr_in *)uaddr;
  194. struct inet_timewait_death_row *tcp_death_row;
  195. struct inet_sock *inet = inet_sk(sk);
  196. struct tcp_sock *tp = tcp_sk(sk);
  197. struct ip_options_rcu *inet_opt;
  198. struct net *net = sock_net(sk);
  199. __be16 orig_sport, orig_dport;
  200. __be32 daddr, nexthop;
  201. struct flowi4 *fl4;
  202. struct rtable *rt;
  203. int err;
  204. if (addr_len < sizeof(struct sockaddr_in))
  205. return -EINVAL;
  206. if (usin->sin_family != AF_INET)
  207. return -EAFNOSUPPORT;
  208. nexthop = daddr = usin->sin_addr.s_addr;
  209. inet_opt = rcu_dereference_protected(inet->inet_opt,
  210. lockdep_sock_is_held(sk));
  211. if (inet_opt && inet_opt->opt.srr) {
  212. if (!daddr)
  213. return -EINVAL;
  214. nexthop = inet_opt->opt.faddr;
  215. }
  216. orig_sport = inet->inet_sport;
  217. orig_dport = usin->sin_port;
  218. fl4 = &inet->cork.fl.u.ip4;
  219. rt = ip_route_connect(fl4, nexthop, inet->inet_saddr,
  220. sk->sk_bound_dev_if, IPPROTO_TCP, orig_sport,
  221. orig_dport, sk);
  222. if (IS_ERR(rt)) {
  223. err = PTR_ERR(rt);
  224. if (err == -ENETUNREACH)
  225. IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
  226. return err;
  227. }
  228. if (rt->rt_flags & (RTCF_MULTICAST | RTCF_BROADCAST)) {
  229. ip_rt_put(rt);
  230. return -ENETUNREACH;
  231. }
  232. if (!inet_opt || !inet_opt->opt.srr)
  233. daddr = fl4->daddr;
  234. tcp_death_row = &sock_net(sk)->ipv4.tcp_death_row;
  235. if (!inet->inet_saddr) {
  236. err = inet_bhash2_update_saddr(sk, &fl4->saddr, AF_INET);
  237. if (err) {
  238. ip_rt_put(rt);
  239. return err;
  240. }
  241. } else {
  242. sk_rcv_saddr_set(sk, inet->inet_saddr);
  243. }
  244. if (tp->rx_opt.ts_recent_stamp && inet->inet_daddr != daddr) {
  245. /* Reset inherited state */
  246. tp->rx_opt.ts_recent = 0;
  247. tp->rx_opt.ts_recent_stamp = 0;
  248. if (likely(!tp->repair))
  249. WRITE_ONCE(tp->write_seq, 0);
  250. }
  251. inet->inet_dport = usin->sin_port;
  252. sk_daddr_set(sk, daddr);
  253. inet_csk(sk)->icsk_ext_hdr_len = 0;
  254. if (inet_opt)
  255. inet_csk(sk)->icsk_ext_hdr_len = inet_opt->opt.optlen;
  256. tp->rx_opt.mss_clamp = TCP_MSS_DEFAULT;
  257. /* Socket identity is still unknown (sport may be zero).
  258. * However we set state to SYN-SENT and not releasing socket
  259. * lock select source port, enter ourselves into the hash tables and
  260. * complete initialization after this.
  261. */
  262. tcp_set_state(sk, TCP_SYN_SENT);
  263. err = inet_hash_connect(tcp_death_row, sk);
  264. if (err)
  265. goto failure;
  266. sk_set_txhash(sk);
  267. rt = ip_route_newports(fl4, rt, orig_sport, orig_dport,
  268. inet->inet_sport, inet->inet_dport, sk);
  269. if (IS_ERR(rt)) {
  270. err = PTR_ERR(rt);
  271. rt = NULL;
  272. goto failure;
  273. }
  274. tp->tcp_usec_ts = dst_tcp_usec_ts(&rt->dst);
  275. /* OK, now commit destination to socket. */
  276. sk->sk_gso_type = SKB_GSO_TCPV4;
  277. sk_setup_caps(sk, &rt->dst);
  278. rt = NULL;
  279. if (likely(!tp->repair)) {
  280. if (!tp->write_seq)
  281. WRITE_ONCE(tp->write_seq,
  282. secure_tcp_seq(inet->inet_saddr,
  283. inet->inet_daddr,
  284. inet->inet_sport,
  285. usin->sin_port));
  286. WRITE_ONCE(tp->tsoffset,
  287. secure_tcp_ts_off(net, inet->inet_saddr,
  288. inet->inet_daddr));
  289. }
  290. atomic_set(&inet->inet_id, get_random_u16());
  291. if (tcp_fastopen_defer_connect(sk, &err))
  292. return err;
  293. if (err)
  294. goto failure;
  295. err = tcp_connect(sk);
  296. if (err)
  297. goto failure;
  298. return 0;
  299. failure:
  300. /*
  301. * This unhashes the socket and releases the local port,
  302. * if necessary.
  303. */
  304. tcp_set_state(sk, TCP_CLOSE);
  305. inet_bhash2_reset_saddr(sk);
  306. ip_rt_put(rt);
  307. sk->sk_route_caps = 0;
  308. inet->inet_dport = 0;
  309. return err;
  310. }
  311. EXPORT_SYMBOL(tcp_v4_connect);
  312. /*
  313. * This routine reacts to ICMP_FRAG_NEEDED mtu indications as defined in RFC1191.
  314. * It can be called through tcp_release_cb() if socket was owned by user
  315. * at the time tcp_v4_err() was called to handle ICMP message.
  316. */
  317. void tcp_v4_mtu_reduced(struct sock *sk)
  318. {
  319. struct inet_sock *inet = inet_sk(sk);
  320. struct dst_entry *dst;
  321. u32 mtu;
  322. if ((1 << sk->sk_state) & (TCPF_LISTEN | TCPF_CLOSE))
  323. return;
  324. mtu = READ_ONCE(tcp_sk(sk)->mtu_info);
  325. dst = inet_csk_update_pmtu(sk, mtu);
  326. if (!dst)
  327. return;
  328. /* Something is about to be wrong... Remember soft error
  329. * for the case, if this connection will not able to recover.
  330. */
  331. if (mtu < dst_mtu(dst) && ip_dont_fragment(sk, dst))
  332. WRITE_ONCE(sk->sk_err_soft, EMSGSIZE);
  333. mtu = dst_mtu(dst);
  334. if (inet->pmtudisc != IP_PMTUDISC_DONT &&
  335. ip_sk_accept_pmtu(sk) &&
  336. inet_csk(sk)->icsk_pmtu_cookie > mtu) {
  337. tcp_sync_mss(sk, mtu);
  338. /* Resend the TCP packet because it's
  339. * clear that the old packet has been
  340. * dropped. This is the new "fast" path mtu
  341. * discovery.
  342. */
  343. tcp_simple_retransmit(sk);
  344. } /* else let the usual retransmit timer handle it */
  345. }
  346. EXPORT_SYMBOL(tcp_v4_mtu_reduced);
  347. static void do_redirect(struct sk_buff *skb, struct sock *sk)
  348. {
  349. struct dst_entry *dst = __sk_dst_check(sk, 0);
  350. if (dst)
  351. dst->ops->redirect(dst, sk, skb);
  352. }
  353. /* handle ICMP messages on TCP_NEW_SYN_RECV request sockets */
  354. void tcp_req_err(struct sock *sk, u32 seq, bool abort)
  355. {
  356. struct request_sock *req = inet_reqsk(sk);
  357. struct net *net = sock_net(sk);
  358. /* ICMPs are not backlogged, hence we cannot get
  359. * an established socket here.
  360. */
  361. if (seq != tcp_rsk(req)->snt_isn) {
  362. __NET_INC_STATS(net, LINUX_MIB_OUTOFWINDOWICMPS);
  363. } else if (abort) {
  364. /*
  365. * Still in SYN_RECV, just remove it silently.
  366. * There is no good way to pass the error to the newly
  367. * created socket, and POSIX does not want network
  368. * errors returned from accept().
  369. */
  370. inet_csk_reqsk_queue_drop(req->rsk_listener, req);
  371. tcp_listendrop(req->rsk_listener);
  372. }
  373. reqsk_put(req);
  374. }
  375. EXPORT_SYMBOL(tcp_req_err);
  376. /* TCP-LD (RFC 6069) logic */
  377. void tcp_ld_RTO_revert(struct sock *sk, u32 seq)
  378. {
  379. struct inet_connection_sock *icsk = inet_csk(sk);
  380. struct tcp_sock *tp = tcp_sk(sk);
  381. struct sk_buff *skb;
  382. s32 remaining;
  383. u32 delta_us;
  384. if (sock_owned_by_user(sk))
  385. return;
  386. if (seq != tp->snd_una || !icsk->icsk_retransmits ||
  387. !icsk->icsk_backoff)
  388. return;
  389. skb = tcp_rtx_queue_head(sk);
  390. if (WARN_ON_ONCE(!skb))
  391. return;
  392. icsk->icsk_backoff--;
  393. icsk->icsk_rto = tp->srtt_us ? __tcp_set_rto(tp) : TCP_TIMEOUT_INIT;
  394. icsk->icsk_rto = inet_csk_rto_backoff(icsk, TCP_RTO_MAX);
  395. tcp_mstamp_refresh(tp);
  396. delta_us = (u32)(tp->tcp_mstamp - tcp_skb_timestamp_us(skb));
  397. remaining = icsk->icsk_rto - usecs_to_jiffies(delta_us);
  398. if (remaining > 0) {
  399. inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS,
  400. remaining, TCP_RTO_MAX);
  401. } else {
  402. /* RTO revert clocked out retransmission.
  403. * Will retransmit now.
  404. */
  405. tcp_retransmit_timer(sk);
  406. }
  407. }
  408. EXPORT_SYMBOL(tcp_ld_RTO_revert);
  409. /*
  410. * This routine is called by the ICMP module when it gets some
  411. * sort of error condition. If err < 0 then the socket should
  412. * be closed and the error returned to the user. If err > 0
  413. * it's just the icmp type << 8 | icmp code. After adjustment
  414. * header points to the first 8 bytes of the tcp header. We need
  415. * to find the appropriate port.
  416. *
  417. * The locking strategy used here is very "optimistic". When
  418. * someone else accesses the socket the ICMP is just dropped
  419. * and for some paths there is no check at all.
  420. * A more general error queue to queue errors for later handling
  421. * is probably better.
  422. *
  423. */
  424. int tcp_v4_err(struct sk_buff *skb, u32 info)
  425. {
  426. const struct iphdr *iph = (const struct iphdr *)skb->data;
  427. struct tcphdr *th = (struct tcphdr *)(skb->data + (iph->ihl << 2));
  428. struct net *net = dev_net_rcu(skb->dev);
  429. const int type = icmp_hdr(skb)->type;
  430. const int code = icmp_hdr(skb)->code;
  431. struct request_sock *fastopen;
  432. struct tcp_sock *tp;
  433. u32 seq, snd_una;
  434. struct sock *sk;
  435. int err;
  436. sk = __inet_lookup_established(net, net->ipv4.tcp_death_row.hashinfo,
  437. iph->daddr, th->dest, iph->saddr,
  438. ntohs(th->source), inet_iif(skb), 0);
  439. if (!sk) {
  440. __ICMP_INC_STATS(net, ICMP_MIB_INERRORS);
  441. return -ENOENT;
  442. }
  443. if (sk->sk_state == TCP_TIME_WAIT) {
  444. /* To increase the counter of ignored icmps for TCP-AO */
  445. tcp_ao_ignore_icmp(sk, AF_INET, type, code);
  446. inet_twsk_put(inet_twsk(sk));
  447. return 0;
  448. }
  449. seq = ntohl(th->seq);
  450. if (sk->sk_state == TCP_NEW_SYN_RECV) {
  451. tcp_req_err(sk, seq, type == ICMP_PARAMETERPROB ||
  452. type == ICMP_TIME_EXCEEDED ||
  453. (type == ICMP_DEST_UNREACH &&
  454. (code == ICMP_NET_UNREACH ||
  455. code == ICMP_HOST_UNREACH)));
  456. return 0;
  457. }
  458. if (tcp_ao_ignore_icmp(sk, AF_INET, type, code)) {
  459. sock_put(sk);
  460. return 0;
  461. }
  462. bh_lock_sock(sk);
  463. /* If too many ICMPs get dropped on busy
  464. * servers this needs to be solved differently.
  465. * We do take care of PMTU discovery (RFC1191) special case :
  466. * we can receive locally generated ICMP messages while socket is held.
  467. */
  468. if (sock_owned_by_user(sk)) {
  469. if (!(type == ICMP_DEST_UNREACH && code == ICMP_FRAG_NEEDED))
  470. __NET_INC_STATS(net, LINUX_MIB_LOCKDROPPEDICMPS);
  471. }
  472. if (sk->sk_state == TCP_CLOSE)
  473. goto out;
  474. if (static_branch_unlikely(&ip4_min_ttl)) {
  475. /* min_ttl can be changed concurrently from do_ip_setsockopt() */
  476. if (unlikely(iph->ttl < READ_ONCE(inet_sk(sk)->min_ttl))) {
  477. __NET_INC_STATS(net, LINUX_MIB_TCPMINTTLDROP);
  478. goto out;
  479. }
  480. }
  481. tp = tcp_sk(sk);
  482. /* XXX (TFO) - tp->snd_una should be ISN (tcp_create_openreq_child() */
  483. fastopen = rcu_dereference(tp->fastopen_rsk);
  484. snd_una = fastopen ? tcp_rsk(fastopen)->snt_isn : tp->snd_una;
  485. if (sk->sk_state != TCP_LISTEN &&
  486. !between(seq, snd_una, tp->snd_nxt)) {
  487. __NET_INC_STATS(net, LINUX_MIB_OUTOFWINDOWICMPS);
  488. goto out;
  489. }
  490. switch (type) {
  491. case ICMP_REDIRECT:
  492. if (!sock_owned_by_user(sk))
  493. do_redirect(skb, sk);
  494. goto out;
  495. case ICMP_SOURCE_QUENCH:
  496. /* Just silently ignore these. */
  497. goto out;
  498. case ICMP_PARAMETERPROB:
  499. err = EPROTO;
  500. break;
  501. case ICMP_DEST_UNREACH:
  502. if (code > NR_ICMP_UNREACH)
  503. goto out;
  504. if (code == ICMP_FRAG_NEEDED) { /* PMTU discovery (RFC1191) */
  505. /* We are not interested in TCP_LISTEN and open_requests
  506. * (SYN-ACKs send out by Linux are always <576bytes so
  507. * they should go through unfragmented).
  508. */
  509. if (sk->sk_state == TCP_LISTEN)
  510. goto out;
  511. WRITE_ONCE(tp->mtu_info, info);
  512. if (!sock_owned_by_user(sk)) {
  513. tcp_v4_mtu_reduced(sk);
  514. } else {
  515. if (!test_and_set_bit(TCP_MTU_REDUCED_DEFERRED, &sk->sk_tsq_flags))
  516. sock_hold(sk);
  517. }
  518. goto out;
  519. }
  520. err = icmp_err_convert[code].errno;
  521. /* check if this ICMP message allows revert of backoff.
  522. * (see RFC 6069)
  523. */
  524. if (!fastopen &&
  525. (code == ICMP_NET_UNREACH || code == ICMP_HOST_UNREACH))
  526. tcp_ld_RTO_revert(sk, seq);
  527. break;
  528. case ICMP_TIME_EXCEEDED:
  529. err = EHOSTUNREACH;
  530. break;
  531. default:
  532. goto out;
  533. }
  534. switch (sk->sk_state) {
  535. case TCP_SYN_SENT:
  536. case TCP_SYN_RECV:
  537. /* Only in fast or simultaneous open. If a fast open socket is
  538. * already accepted it is treated as a connected one below.
  539. */
  540. if (fastopen && !fastopen->sk)
  541. break;
  542. ip_icmp_error(sk, skb, err, th->dest, info, (u8 *)th);
  543. if (!sock_owned_by_user(sk))
  544. tcp_done_with_error(sk, err);
  545. else
  546. WRITE_ONCE(sk->sk_err_soft, err);
  547. goto out;
  548. }
  549. /* If we've already connected we will keep trying
  550. * until we time out, or the user gives up.
  551. *
  552. * rfc1122 4.2.3.9 allows to consider as hard errors
  553. * only PROTO_UNREACH and PORT_UNREACH (well, FRAG_FAILED too,
  554. * but it is obsoleted by pmtu discovery).
  555. *
  556. * Note, that in modern internet, where routing is unreliable
  557. * and in each dark corner broken firewalls sit, sending random
  558. * errors ordered by their masters even this two messages finally lose
  559. * their original sense (even Linux sends invalid PORT_UNREACHs)
  560. *
  561. * Now we are in compliance with RFCs.
  562. * --ANK (980905)
  563. */
  564. if (!sock_owned_by_user(sk) &&
  565. inet_test_bit(RECVERR, sk)) {
  566. WRITE_ONCE(sk->sk_err, err);
  567. sk_error_report(sk);
  568. } else { /* Only an error on timeout */
  569. WRITE_ONCE(sk->sk_err_soft, err);
  570. }
  571. out:
  572. bh_unlock_sock(sk);
  573. sock_put(sk);
  574. return 0;
  575. }
  576. void __tcp_v4_send_check(struct sk_buff *skb, __be32 saddr, __be32 daddr)
  577. {
  578. struct tcphdr *th = tcp_hdr(skb);
  579. th->check = ~tcp_v4_check(skb->len, saddr, daddr, 0);
  580. skb->csum_start = skb_transport_header(skb) - skb->head;
  581. skb->csum_offset = offsetof(struct tcphdr, check);
  582. }
  583. /* This routine computes an IPv4 TCP checksum. */
  584. void tcp_v4_send_check(struct sock *sk, struct sk_buff *skb)
  585. {
  586. const struct inet_sock *inet = inet_sk(sk);
  587. __tcp_v4_send_check(skb, inet->inet_saddr, inet->inet_daddr);
  588. }
  589. EXPORT_SYMBOL(tcp_v4_send_check);
  590. #define REPLY_OPTIONS_LEN (MAX_TCP_OPTION_SPACE / sizeof(__be32))
  591. static bool tcp_v4_ao_sign_reset(const struct sock *sk, struct sk_buff *skb,
  592. const struct tcp_ao_hdr *aoh,
  593. struct ip_reply_arg *arg, struct tcphdr *reply,
  594. __be32 reply_options[REPLY_OPTIONS_LEN])
  595. {
  596. #ifdef CONFIG_TCP_AO
  597. int sdif = tcp_v4_sdif(skb);
  598. int dif = inet_iif(skb);
  599. int l3index = sdif ? dif : 0;
  600. bool allocated_traffic_key;
  601. struct tcp_ao_key *key;
  602. char *traffic_key;
  603. bool drop = true;
  604. u32 ao_sne = 0;
  605. u8 keyid;
  606. rcu_read_lock();
  607. if (tcp_ao_prepare_reset(sk, skb, aoh, l3index, ntohl(reply->seq),
  608. &key, &traffic_key, &allocated_traffic_key,
  609. &keyid, &ao_sne))
  610. goto out;
  611. reply_options[0] = htonl((TCPOPT_AO << 24) | (tcp_ao_len(key) << 16) |
  612. (aoh->rnext_keyid << 8) | keyid);
  613. arg->iov[0].iov_len += tcp_ao_len_aligned(key);
  614. reply->doff = arg->iov[0].iov_len / 4;
  615. if (tcp_ao_hash_hdr(AF_INET, (char *)&reply_options[1],
  616. key, traffic_key,
  617. (union tcp_ao_addr *)&ip_hdr(skb)->saddr,
  618. (union tcp_ao_addr *)&ip_hdr(skb)->daddr,
  619. reply, ao_sne))
  620. goto out;
  621. drop = false;
  622. out:
  623. rcu_read_unlock();
  624. if (allocated_traffic_key)
  625. kfree(traffic_key);
  626. return drop;
  627. #else
  628. return true;
  629. #endif
  630. }
  631. /*
  632. * This routine will send an RST to the other tcp.
  633. *
  634. * Someone asks: why I NEVER use socket parameters (TOS, TTL etc.)
  635. * for reset.
  636. * Answer: if a packet caused RST, it is not for a socket
  637. * existing in our system, if it is matched to a socket,
  638. * it is just duplicate segment or bug in other side's TCP.
  639. * So that we build reply only basing on parameters
  640. * arrived with segment.
  641. * Exception: precedence violation. We do not implement it in any case.
  642. */
  643. static void tcp_v4_send_reset(const struct sock *sk, struct sk_buff *skb,
  644. enum sk_rst_reason reason)
  645. {
  646. const struct tcphdr *th = tcp_hdr(skb);
  647. struct {
  648. struct tcphdr th;
  649. __be32 opt[REPLY_OPTIONS_LEN];
  650. } rep;
  651. const __u8 *md5_hash_location = NULL;
  652. const struct tcp_ao_hdr *aoh;
  653. struct ip_reply_arg arg;
  654. #ifdef CONFIG_TCP_MD5SIG
  655. struct tcp_md5sig_key *key = NULL;
  656. unsigned char newhash[16];
  657. struct sock *sk1 = NULL;
  658. int genhash;
  659. #endif
  660. u64 transmit_time = 0;
  661. struct sock *ctl_sk;
  662. struct net *net;
  663. u32 txhash = 0;
  664. /* Never send a reset in response to a reset. */
  665. if (th->rst)
  666. return;
  667. /* If sk not NULL, it means we did a successful lookup and incoming
  668. * route had to be correct. prequeue might have dropped our dst.
  669. */
  670. if (!sk && skb_rtable(skb)->rt_type != RTN_LOCAL)
  671. return;
  672. /* Swap the send and the receive. */
  673. memset(&rep, 0, sizeof(rep));
  674. rep.th.dest = th->source;
  675. rep.th.source = th->dest;
  676. rep.th.doff = sizeof(struct tcphdr) / 4;
  677. rep.th.rst = 1;
  678. if (th->ack) {
  679. rep.th.seq = th->ack_seq;
  680. } else {
  681. rep.th.ack = 1;
  682. rep.th.ack_seq = htonl(ntohl(th->seq) + th->syn + th->fin +
  683. skb->len - (th->doff << 2));
  684. }
  685. memset(&arg, 0, sizeof(arg));
  686. arg.iov[0].iov_base = (unsigned char *)&rep;
  687. arg.iov[0].iov_len = sizeof(rep.th);
  688. net = sk ? sock_net(sk) : skb_dst_dev_net_rcu(skb);
  689. /* Invalid TCP option size or twice included auth */
  690. if (tcp_parse_auth_options(tcp_hdr(skb), &md5_hash_location, &aoh))
  691. return;
  692. if (aoh && tcp_v4_ao_sign_reset(sk, skb, aoh, &arg, &rep.th, rep.opt))
  693. return;
  694. #ifdef CONFIG_TCP_MD5SIG
  695. rcu_read_lock();
  696. if (sk && sk_fullsock(sk)) {
  697. const union tcp_md5_addr *addr;
  698. int l3index;
  699. /* sdif set, means packet ingressed via a device
  700. * in an L3 domain and inet_iif is set to it.
  701. */
  702. l3index = tcp_v4_sdif(skb) ? inet_iif(skb) : 0;
  703. addr = (union tcp_md5_addr *)&ip_hdr(skb)->saddr;
  704. key = tcp_md5_do_lookup(sk, l3index, addr, AF_INET);
  705. } else if (md5_hash_location) {
  706. const union tcp_md5_addr *addr;
  707. int sdif = tcp_v4_sdif(skb);
  708. int dif = inet_iif(skb);
  709. int l3index;
  710. /*
  711. * active side is lost. Try to find listening socket through
  712. * source port, and then find md5 key through listening socket.
  713. * we are not loose security here:
  714. * Incoming packet is checked with md5 hash with finding key,
  715. * no RST generated if md5 hash doesn't match.
  716. */
  717. sk1 = __inet_lookup_listener(net, net->ipv4.tcp_death_row.hashinfo,
  718. NULL, 0, ip_hdr(skb)->saddr,
  719. th->source, ip_hdr(skb)->daddr,
  720. ntohs(th->source), dif, sdif);
  721. /* don't send rst if it can't find key */
  722. if (!sk1)
  723. goto out;
  724. /* sdif set, means packet ingressed via a device
  725. * in an L3 domain and dif is set to it.
  726. */
  727. l3index = sdif ? dif : 0;
  728. addr = (union tcp_md5_addr *)&ip_hdr(skb)->saddr;
  729. key = tcp_md5_do_lookup(sk1, l3index, addr, AF_INET);
  730. if (!key)
  731. goto out;
  732. genhash = tcp_v4_md5_hash_skb(newhash, key, NULL, skb);
  733. if (genhash || memcmp(md5_hash_location, newhash, 16) != 0)
  734. goto out;
  735. }
  736. if (key) {
  737. rep.opt[0] = htonl((TCPOPT_NOP << 24) |
  738. (TCPOPT_NOP << 16) |
  739. (TCPOPT_MD5SIG << 8) |
  740. TCPOLEN_MD5SIG);
  741. /* Update length and the length the header thinks exists */
  742. arg.iov[0].iov_len += TCPOLEN_MD5SIG_ALIGNED;
  743. rep.th.doff = arg.iov[0].iov_len / 4;
  744. tcp_v4_md5_hash_hdr((__u8 *) &rep.opt[1],
  745. key, ip_hdr(skb)->saddr,
  746. ip_hdr(skb)->daddr, &rep.th);
  747. }
  748. #endif
  749. /* Can't co-exist with TCPMD5, hence check rep.opt[0] */
  750. if (rep.opt[0] == 0) {
  751. __be32 mrst = mptcp_reset_option(skb);
  752. if (mrst) {
  753. rep.opt[0] = mrst;
  754. arg.iov[0].iov_len += sizeof(mrst);
  755. rep.th.doff = arg.iov[0].iov_len / 4;
  756. }
  757. }
  758. arg.csum = csum_tcpudp_nofold(ip_hdr(skb)->daddr,
  759. ip_hdr(skb)->saddr, /* XXX */
  760. arg.iov[0].iov_len, IPPROTO_TCP, 0);
  761. arg.csumoffset = offsetof(struct tcphdr, check) / 2;
  762. arg.flags = (sk && inet_sk_transparent(sk)) ? IP_REPLY_ARG_NOSRCCHECK : 0;
  763. /* When socket is gone, all binding information is lost.
  764. * routing might fail in this case. No choice here, if we choose to force
  765. * input interface, we will misroute in case of asymmetric route.
  766. */
  767. if (sk)
  768. arg.bound_dev_if = sk->sk_bound_dev_if;
  769. trace_tcp_send_reset(sk, skb, reason);
  770. BUILD_BUG_ON(offsetof(struct sock, sk_bound_dev_if) !=
  771. offsetof(struct inet_timewait_sock, tw_bound_dev_if));
  772. arg.tos = ip_hdr(skb)->tos;
  773. arg.uid = sock_net_uid(net, sk && sk_fullsock(sk) ? sk : NULL);
  774. local_bh_disable();
  775. local_lock_nested_bh(&ipv4_tcp_sk.bh_lock);
  776. ctl_sk = this_cpu_read(ipv4_tcp_sk.sock);
  777. sock_net_set(ctl_sk, net);
  778. if (sk) {
  779. ctl_sk->sk_mark = (sk->sk_state == TCP_TIME_WAIT) ?
  780. inet_twsk(sk)->tw_mark : READ_ONCE(sk->sk_mark);
  781. ctl_sk->sk_priority = (sk->sk_state == TCP_TIME_WAIT) ?
  782. inet_twsk(sk)->tw_priority : READ_ONCE(sk->sk_priority);
  783. transmit_time = tcp_transmit_time(sk);
  784. xfrm_sk_clone_policy(ctl_sk, sk);
  785. txhash = (sk->sk_state == TCP_TIME_WAIT) ?
  786. inet_twsk(sk)->tw_txhash : sk->sk_txhash;
  787. } else {
  788. ctl_sk->sk_mark = 0;
  789. ctl_sk->sk_priority = 0;
  790. }
  791. ip_send_unicast_reply(ctl_sk,
  792. skb, &TCP_SKB_CB(skb)->header.h4.opt,
  793. ip_hdr(skb)->saddr, ip_hdr(skb)->daddr,
  794. &arg, arg.iov[0].iov_len,
  795. transmit_time, txhash);
  796. xfrm_sk_free_policy(ctl_sk);
  797. sock_net_set(ctl_sk, &init_net);
  798. __TCP_INC_STATS(net, TCP_MIB_OUTSEGS);
  799. __TCP_INC_STATS(net, TCP_MIB_OUTRSTS);
  800. local_unlock_nested_bh(&ipv4_tcp_sk.bh_lock);
  801. local_bh_enable();
  802. #ifdef CONFIG_TCP_MD5SIG
  803. out:
  804. rcu_read_unlock();
  805. #endif
  806. }
  807. /* The code following below sending ACKs in SYN-RECV and TIME-WAIT states
  808. outside socket context is ugly, certainly. What can I do?
  809. */
  810. static void tcp_v4_send_ack(const struct sock *sk,
  811. struct sk_buff *skb, u32 seq, u32 ack,
  812. u32 win, u32 tsval, u32 tsecr, int oif,
  813. struct tcp_key *key,
  814. int reply_flags, u8 tos, u32 txhash)
  815. {
  816. const struct tcphdr *th = tcp_hdr(skb);
  817. struct {
  818. struct tcphdr th;
  819. __be32 opt[(MAX_TCP_OPTION_SPACE >> 2)];
  820. } rep;
  821. struct net *net = sock_net(sk);
  822. struct ip_reply_arg arg;
  823. struct sock *ctl_sk;
  824. u64 transmit_time;
  825. memset(&rep.th, 0, sizeof(struct tcphdr));
  826. memset(&arg, 0, sizeof(arg));
  827. arg.iov[0].iov_base = (unsigned char *)&rep;
  828. arg.iov[0].iov_len = sizeof(rep.th);
  829. if (tsecr) {
  830. rep.opt[0] = htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) |
  831. (TCPOPT_TIMESTAMP << 8) |
  832. TCPOLEN_TIMESTAMP);
  833. rep.opt[1] = htonl(tsval);
  834. rep.opt[2] = htonl(tsecr);
  835. arg.iov[0].iov_len += TCPOLEN_TSTAMP_ALIGNED;
  836. }
  837. /* Swap the send and the receive. */
  838. rep.th.dest = th->source;
  839. rep.th.source = th->dest;
  840. rep.th.doff = arg.iov[0].iov_len / 4;
  841. rep.th.seq = htonl(seq);
  842. rep.th.ack_seq = htonl(ack);
  843. rep.th.ack = 1;
  844. rep.th.window = htons(win);
  845. #ifdef CONFIG_TCP_MD5SIG
  846. if (tcp_key_is_md5(key)) {
  847. int offset = (tsecr) ? 3 : 0;
  848. rep.opt[offset++] = htonl((TCPOPT_NOP << 24) |
  849. (TCPOPT_NOP << 16) |
  850. (TCPOPT_MD5SIG << 8) |
  851. TCPOLEN_MD5SIG);
  852. arg.iov[0].iov_len += TCPOLEN_MD5SIG_ALIGNED;
  853. rep.th.doff = arg.iov[0].iov_len/4;
  854. tcp_v4_md5_hash_hdr((__u8 *) &rep.opt[offset],
  855. key->md5_key, ip_hdr(skb)->saddr,
  856. ip_hdr(skb)->daddr, &rep.th);
  857. }
  858. #endif
  859. #ifdef CONFIG_TCP_AO
  860. if (tcp_key_is_ao(key)) {
  861. int offset = (tsecr) ? 3 : 0;
  862. rep.opt[offset++] = htonl((TCPOPT_AO << 24) |
  863. (tcp_ao_len(key->ao_key) << 16) |
  864. (key->ao_key->sndid << 8) |
  865. key->rcv_next);
  866. arg.iov[0].iov_len += tcp_ao_len_aligned(key->ao_key);
  867. rep.th.doff = arg.iov[0].iov_len / 4;
  868. tcp_ao_hash_hdr(AF_INET, (char *)&rep.opt[offset],
  869. key->ao_key, key->traffic_key,
  870. (union tcp_ao_addr *)&ip_hdr(skb)->saddr,
  871. (union tcp_ao_addr *)&ip_hdr(skb)->daddr,
  872. &rep.th, key->sne);
  873. }
  874. #endif
  875. arg.flags = reply_flags;
  876. arg.csum = csum_tcpudp_nofold(ip_hdr(skb)->daddr,
  877. ip_hdr(skb)->saddr, /* XXX */
  878. arg.iov[0].iov_len, IPPROTO_TCP, 0);
  879. arg.csumoffset = offsetof(struct tcphdr, check) / 2;
  880. if (oif)
  881. arg.bound_dev_if = oif;
  882. arg.tos = tos;
  883. arg.uid = sock_net_uid(net, sk_fullsock(sk) ? sk : NULL);
  884. local_bh_disable();
  885. local_lock_nested_bh(&ipv4_tcp_sk.bh_lock);
  886. ctl_sk = this_cpu_read(ipv4_tcp_sk.sock);
  887. sock_net_set(ctl_sk, net);
  888. ctl_sk->sk_mark = (sk->sk_state == TCP_TIME_WAIT) ?
  889. inet_twsk(sk)->tw_mark : READ_ONCE(sk->sk_mark);
  890. ctl_sk->sk_priority = (sk->sk_state == TCP_TIME_WAIT) ?
  891. inet_twsk(sk)->tw_priority : READ_ONCE(sk->sk_priority);
  892. transmit_time = tcp_transmit_time(sk);
  893. ip_send_unicast_reply(ctl_sk,
  894. skb, &TCP_SKB_CB(skb)->header.h4.opt,
  895. ip_hdr(skb)->saddr, ip_hdr(skb)->daddr,
  896. &arg, arg.iov[0].iov_len,
  897. transmit_time, txhash);
  898. sock_net_set(ctl_sk, &init_net);
  899. __TCP_INC_STATS(net, TCP_MIB_OUTSEGS);
  900. local_unlock_nested_bh(&ipv4_tcp_sk.bh_lock);
  901. local_bh_enable();
  902. }
  903. static void tcp_v4_timewait_ack(struct sock *sk, struct sk_buff *skb)
  904. {
  905. struct inet_timewait_sock *tw = inet_twsk(sk);
  906. struct tcp_timewait_sock *tcptw = tcp_twsk(sk);
  907. struct tcp_key key = {};
  908. #ifdef CONFIG_TCP_AO
  909. struct tcp_ao_info *ao_info;
  910. if (static_branch_unlikely(&tcp_ao_needed.key)) {
  911. /* FIXME: the segment to-be-acked is not verified yet */
  912. ao_info = rcu_dereference(tcptw->ao_info);
  913. if (ao_info) {
  914. const struct tcp_ao_hdr *aoh;
  915. if (tcp_parse_auth_options(tcp_hdr(skb), NULL, &aoh)) {
  916. inet_twsk_put(tw);
  917. return;
  918. }
  919. if (aoh)
  920. key.ao_key = tcp_ao_established_key(sk, ao_info,
  921. aoh->rnext_keyid, -1);
  922. }
  923. }
  924. if (key.ao_key) {
  925. struct tcp_ao_key *rnext_key;
  926. key.traffic_key = snd_other_key(key.ao_key);
  927. key.sne = READ_ONCE(ao_info->snd_sne);
  928. rnext_key = READ_ONCE(ao_info->rnext_key);
  929. key.rcv_next = rnext_key->rcvid;
  930. key.type = TCP_KEY_AO;
  931. #else
  932. if (0) {
  933. #endif
  934. } else if (static_branch_tcp_md5()) {
  935. key.md5_key = tcp_twsk_md5_key(tcptw);
  936. if (key.md5_key)
  937. key.type = TCP_KEY_MD5;
  938. }
  939. tcp_v4_send_ack(sk, skb,
  940. tcptw->tw_snd_nxt, READ_ONCE(tcptw->tw_rcv_nxt),
  941. tcptw->tw_rcv_wnd >> tw->tw_rcv_wscale,
  942. tcp_tw_tsval(tcptw),
  943. READ_ONCE(tcptw->tw_ts_recent),
  944. tw->tw_bound_dev_if, &key,
  945. tw->tw_transparent ? IP_REPLY_ARG_NOSRCCHECK : 0,
  946. tw->tw_tos,
  947. tw->tw_txhash);
  948. inet_twsk_put(tw);
  949. }
  950. static void tcp_v4_reqsk_send_ack(const struct sock *sk, struct sk_buff *skb,
  951. struct request_sock *req)
  952. {
  953. struct tcp_key key = {};
  954. /* sk->sk_state == TCP_LISTEN -> for regular TCP_SYN_RECV
  955. * sk->sk_state == TCP_SYN_RECV -> for Fast Open.
  956. */
  957. u32 seq = (sk->sk_state == TCP_LISTEN) ? tcp_rsk(req)->snt_isn + 1 :
  958. tcp_sk(sk)->snd_nxt;
  959. #ifdef CONFIG_TCP_AO
  960. if (static_branch_unlikely(&tcp_ao_needed.key) &&
  961. tcp_rsk_used_ao(req)) {
  962. const union tcp_md5_addr *addr;
  963. const struct tcp_ao_hdr *aoh;
  964. int l3index;
  965. /* Invalid TCP option size or twice included auth */
  966. if (tcp_parse_auth_options(tcp_hdr(skb), NULL, &aoh))
  967. return;
  968. if (!aoh)
  969. return;
  970. addr = (union tcp_md5_addr *)&ip_hdr(skb)->saddr;
  971. l3index = tcp_v4_sdif(skb) ? inet_iif(skb) : 0;
  972. key.ao_key = tcp_ao_do_lookup(sk, l3index, addr, AF_INET,
  973. aoh->rnext_keyid, -1);
  974. if (unlikely(!key.ao_key)) {
  975. /* Send ACK with any matching MKT for the peer */
  976. key.ao_key = tcp_ao_do_lookup(sk, l3index, addr, AF_INET, -1, -1);
  977. /* Matching key disappeared (user removed the key?)
  978. * let the handshake timeout.
  979. */
  980. if (!key.ao_key) {
  981. net_info_ratelimited("TCP-AO key for (%pI4, %d)->(%pI4, %d) suddenly disappeared, won't ACK new connection\n",
  982. addr,
  983. ntohs(tcp_hdr(skb)->source),
  984. &ip_hdr(skb)->daddr,
  985. ntohs(tcp_hdr(skb)->dest));
  986. return;
  987. }
  988. }
  989. key.traffic_key = kmalloc(tcp_ao_digest_size(key.ao_key), GFP_ATOMIC);
  990. if (!key.traffic_key)
  991. return;
  992. key.type = TCP_KEY_AO;
  993. key.rcv_next = aoh->keyid;
  994. tcp_v4_ao_calc_key_rsk(key.ao_key, key.traffic_key, req);
  995. #else
  996. if (0) {
  997. #endif
  998. } else if (static_branch_tcp_md5()) {
  999. const union tcp_md5_addr *addr;
  1000. int l3index;
  1001. addr = (union tcp_md5_addr *)&ip_hdr(skb)->saddr;
  1002. l3index = tcp_v4_sdif(skb) ? inet_iif(skb) : 0;
  1003. key.md5_key = tcp_md5_do_lookup(sk, l3index, addr, AF_INET);
  1004. if (key.md5_key)
  1005. key.type = TCP_KEY_MD5;
  1006. }
  1007. tcp_v4_send_ack(sk, skb, seq,
  1008. tcp_rsk(req)->rcv_nxt,
  1009. tcp_synack_window(req) >> inet_rsk(req)->rcv_wscale,
  1010. tcp_rsk_tsval(tcp_rsk(req)),
  1011. READ_ONCE(req->ts_recent),
  1012. 0, &key,
  1013. inet_rsk(req)->no_srccheck ? IP_REPLY_ARG_NOSRCCHECK : 0,
  1014. ip_hdr(skb)->tos,
  1015. READ_ONCE(tcp_rsk(req)->txhash));
  1016. if (tcp_key_is_ao(&key))
  1017. kfree(key.traffic_key);
  1018. }
  1019. /*
  1020. * Send a SYN-ACK after having received a SYN.
  1021. * This still operates on a request_sock only, not on a big
  1022. * socket.
  1023. */
  1024. static int tcp_v4_send_synack(const struct sock *sk, struct dst_entry *dst,
  1025. struct flowi *fl,
  1026. struct request_sock *req,
  1027. struct tcp_fastopen_cookie *foc,
  1028. enum tcp_synack_type synack_type,
  1029. struct sk_buff *syn_skb)
  1030. {
  1031. const struct inet_request_sock *ireq = inet_rsk(req);
  1032. struct flowi4 fl4;
  1033. int err = -1;
  1034. struct sk_buff *skb;
  1035. u8 tos;
  1036. /* First, grab a route. */
  1037. if (!dst && (dst = inet_csk_route_req(sk, &fl4, req)) == NULL)
  1038. return -1;
  1039. skb = tcp_make_synack(sk, dst, req, foc, synack_type, syn_skb);
  1040. if (skb) {
  1041. __tcp_v4_send_check(skb, ireq->ir_loc_addr, ireq->ir_rmt_addr);
  1042. tos = READ_ONCE(inet_sk(sk)->tos);
  1043. if (READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_reflect_tos))
  1044. tos = (tcp_rsk(req)->syn_tos & ~INET_ECN_MASK) |
  1045. (tos & INET_ECN_MASK);
  1046. if (!INET_ECN_is_capable(tos) &&
  1047. tcp_bpf_ca_needs_ecn((struct sock *)req))
  1048. tos |= INET_ECN_ECT_0;
  1049. rcu_read_lock();
  1050. err = ip_build_and_send_pkt(skb, sk, ireq->ir_loc_addr,
  1051. ireq->ir_rmt_addr,
  1052. rcu_dereference(ireq->ireq_opt),
  1053. tos);
  1054. rcu_read_unlock();
  1055. err = net_xmit_eval(err);
  1056. }
  1057. return err;
  1058. }
  1059. /*
  1060. * IPv4 request_sock destructor.
  1061. */
  1062. static void tcp_v4_reqsk_destructor(struct request_sock *req)
  1063. {
  1064. kfree(rcu_dereference_protected(inet_rsk(req)->ireq_opt, 1));
  1065. }
  1066. #ifdef CONFIG_TCP_MD5SIG
  1067. /*
  1068. * RFC2385 MD5 checksumming requires a mapping of
  1069. * IP address->MD5 Key.
  1070. * We need to maintain these in the sk structure.
  1071. */
  1072. DEFINE_STATIC_KEY_DEFERRED_FALSE(tcp_md5_needed, HZ);
  1073. EXPORT_SYMBOL(tcp_md5_needed);
  1074. static bool better_md5_match(struct tcp_md5sig_key *old, struct tcp_md5sig_key *new)
  1075. {
  1076. if (!old)
  1077. return true;
  1078. /* l3index always overrides non-l3index */
  1079. if (old->l3index && new->l3index == 0)
  1080. return false;
  1081. if (old->l3index == 0 && new->l3index)
  1082. return true;
  1083. return old->prefixlen < new->prefixlen;
  1084. }
  1085. /* Find the Key structure for an address. */
  1086. struct tcp_md5sig_key *__tcp_md5_do_lookup(const struct sock *sk, int l3index,
  1087. const union tcp_md5_addr *addr,
  1088. int family, bool any_l3index)
  1089. {
  1090. const struct tcp_sock *tp = tcp_sk(sk);
  1091. struct tcp_md5sig_key *key;
  1092. const struct tcp_md5sig_info *md5sig;
  1093. __be32 mask;
  1094. struct tcp_md5sig_key *best_match = NULL;
  1095. bool match;
  1096. /* caller either holds rcu_read_lock() or socket lock */
  1097. md5sig = rcu_dereference_check(tp->md5sig_info,
  1098. lockdep_sock_is_held(sk));
  1099. if (!md5sig)
  1100. return NULL;
  1101. hlist_for_each_entry_rcu(key, &md5sig->head, node,
  1102. lockdep_sock_is_held(sk)) {
  1103. if (key->family != family)
  1104. continue;
  1105. if (!any_l3index && key->flags & TCP_MD5SIG_FLAG_IFINDEX &&
  1106. key->l3index != l3index)
  1107. continue;
  1108. if (family == AF_INET) {
  1109. mask = inet_make_mask(key->prefixlen);
  1110. match = (key->addr.a4.s_addr & mask) ==
  1111. (addr->a4.s_addr & mask);
  1112. #if IS_ENABLED(CONFIG_IPV6)
  1113. } else if (family == AF_INET6) {
  1114. match = ipv6_prefix_equal(&key->addr.a6, &addr->a6,
  1115. key->prefixlen);
  1116. #endif
  1117. } else {
  1118. match = false;
  1119. }
  1120. if (match && better_md5_match(best_match, key))
  1121. best_match = key;
  1122. }
  1123. return best_match;
  1124. }
  1125. EXPORT_SYMBOL(__tcp_md5_do_lookup);
  1126. static struct tcp_md5sig_key *tcp_md5_do_lookup_exact(const struct sock *sk,
  1127. const union tcp_md5_addr *addr,
  1128. int family, u8 prefixlen,
  1129. int l3index, u8 flags)
  1130. {
  1131. const struct tcp_sock *tp = tcp_sk(sk);
  1132. struct tcp_md5sig_key *key;
  1133. unsigned int size = sizeof(struct in_addr);
  1134. const struct tcp_md5sig_info *md5sig;
  1135. /* caller either holds rcu_read_lock() or socket lock */
  1136. md5sig = rcu_dereference_check(tp->md5sig_info,
  1137. lockdep_sock_is_held(sk));
  1138. if (!md5sig)
  1139. return NULL;
  1140. #if IS_ENABLED(CONFIG_IPV6)
  1141. if (family == AF_INET6)
  1142. size = sizeof(struct in6_addr);
  1143. #endif
  1144. hlist_for_each_entry_rcu(key, &md5sig->head, node,
  1145. lockdep_sock_is_held(sk)) {
  1146. if (key->family != family)
  1147. continue;
  1148. if ((key->flags & TCP_MD5SIG_FLAG_IFINDEX) != (flags & TCP_MD5SIG_FLAG_IFINDEX))
  1149. continue;
  1150. if (key->l3index != l3index)
  1151. continue;
  1152. if (!memcmp(&key->addr, addr, size) &&
  1153. key->prefixlen == prefixlen)
  1154. return key;
  1155. }
  1156. return NULL;
  1157. }
  1158. struct tcp_md5sig_key *tcp_v4_md5_lookup(const struct sock *sk,
  1159. const struct sock *addr_sk)
  1160. {
  1161. const union tcp_md5_addr *addr;
  1162. int l3index;
  1163. l3index = l3mdev_master_ifindex_by_index(sock_net(sk),
  1164. addr_sk->sk_bound_dev_if);
  1165. addr = (const union tcp_md5_addr *)&addr_sk->sk_daddr;
  1166. return tcp_md5_do_lookup(sk, l3index, addr, AF_INET);
  1167. }
  1168. EXPORT_SYMBOL(tcp_v4_md5_lookup);
  1169. static int tcp_md5sig_info_add(struct sock *sk, gfp_t gfp)
  1170. {
  1171. struct tcp_sock *tp = tcp_sk(sk);
  1172. struct tcp_md5sig_info *md5sig;
  1173. md5sig = kmalloc(sizeof(*md5sig), gfp);
  1174. if (!md5sig)
  1175. return -ENOMEM;
  1176. sk_gso_disable(sk);
  1177. INIT_HLIST_HEAD(&md5sig->head);
  1178. rcu_assign_pointer(tp->md5sig_info, md5sig);
  1179. return 0;
  1180. }
  1181. /* This can be called on a newly created socket, from other files */
  1182. static int __tcp_md5_do_add(struct sock *sk, const union tcp_md5_addr *addr,
  1183. int family, u8 prefixlen, int l3index, u8 flags,
  1184. const u8 *newkey, u8 newkeylen, gfp_t gfp)
  1185. {
  1186. /* Add Key to the list */
  1187. struct tcp_md5sig_key *key;
  1188. struct tcp_sock *tp = tcp_sk(sk);
  1189. struct tcp_md5sig_info *md5sig;
  1190. key = tcp_md5_do_lookup_exact(sk, addr, family, prefixlen, l3index, flags);
  1191. if (key) {
  1192. /* Pre-existing entry - just update that one.
  1193. * Note that the key might be used concurrently.
  1194. * data_race() is telling kcsan that we do not care of
  1195. * key mismatches, since changing MD5 key on live flows
  1196. * can lead to packet drops.
  1197. */
  1198. data_race(memcpy(key->key, newkey, newkeylen));
  1199. /* Pairs with READ_ONCE() in tcp_md5_hash_key().
  1200. * Also note that a reader could catch new key->keylen value
  1201. * but old key->key[], this is the reason we use __GFP_ZERO
  1202. * at sock_kmalloc() time below these lines.
  1203. */
  1204. WRITE_ONCE(key->keylen, newkeylen);
  1205. return 0;
  1206. }
  1207. md5sig = rcu_dereference_protected(tp->md5sig_info,
  1208. lockdep_sock_is_held(sk));
  1209. key = sock_kmalloc(sk, sizeof(*key), gfp | __GFP_ZERO);
  1210. if (!key)
  1211. return -ENOMEM;
  1212. memcpy(key->key, newkey, newkeylen);
  1213. key->keylen = newkeylen;
  1214. key->family = family;
  1215. key->prefixlen = prefixlen;
  1216. key->l3index = l3index;
  1217. key->flags = flags;
  1218. memcpy(&key->addr, addr,
  1219. (IS_ENABLED(CONFIG_IPV6) && family == AF_INET6) ? sizeof(struct in6_addr) :
  1220. sizeof(struct in_addr));
  1221. hlist_add_head_rcu(&key->node, &md5sig->head);
  1222. return 0;
  1223. }
  1224. int tcp_md5_do_add(struct sock *sk, const union tcp_md5_addr *addr,
  1225. int family, u8 prefixlen, int l3index, u8 flags,
  1226. const u8 *newkey, u8 newkeylen)
  1227. {
  1228. struct tcp_sock *tp = tcp_sk(sk);
  1229. if (!rcu_dereference_protected(tp->md5sig_info, lockdep_sock_is_held(sk))) {
  1230. if (tcp_md5_alloc_sigpool())
  1231. return -ENOMEM;
  1232. if (tcp_md5sig_info_add(sk, GFP_KERNEL)) {
  1233. tcp_md5_release_sigpool();
  1234. return -ENOMEM;
  1235. }
  1236. if (!static_branch_inc(&tcp_md5_needed.key)) {
  1237. struct tcp_md5sig_info *md5sig;
  1238. md5sig = rcu_dereference_protected(tp->md5sig_info, lockdep_sock_is_held(sk));
  1239. rcu_assign_pointer(tp->md5sig_info, NULL);
  1240. kfree_rcu(md5sig, rcu);
  1241. tcp_md5_release_sigpool();
  1242. return -EUSERS;
  1243. }
  1244. }
  1245. return __tcp_md5_do_add(sk, addr, family, prefixlen, l3index, flags,
  1246. newkey, newkeylen, GFP_KERNEL);
  1247. }
  1248. EXPORT_SYMBOL(tcp_md5_do_add);
  1249. int tcp_md5_key_copy(struct sock *sk, const union tcp_md5_addr *addr,
  1250. int family, u8 prefixlen, int l3index,
  1251. struct tcp_md5sig_key *key)
  1252. {
  1253. struct tcp_sock *tp = tcp_sk(sk);
  1254. if (!rcu_dereference_protected(tp->md5sig_info, lockdep_sock_is_held(sk))) {
  1255. tcp_md5_add_sigpool();
  1256. if (tcp_md5sig_info_add(sk, sk_gfp_mask(sk, GFP_ATOMIC))) {
  1257. tcp_md5_release_sigpool();
  1258. return -ENOMEM;
  1259. }
  1260. if (!static_key_fast_inc_not_disabled(&tcp_md5_needed.key.key)) {
  1261. struct tcp_md5sig_info *md5sig;
  1262. md5sig = rcu_dereference_protected(tp->md5sig_info, lockdep_sock_is_held(sk));
  1263. net_warn_ratelimited("Too many TCP-MD5 keys in the system\n");
  1264. rcu_assign_pointer(tp->md5sig_info, NULL);
  1265. kfree_rcu(md5sig, rcu);
  1266. tcp_md5_release_sigpool();
  1267. return -EUSERS;
  1268. }
  1269. }
  1270. return __tcp_md5_do_add(sk, addr, family, prefixlen, l3index,
  1271. key->flags, key->key, key->keylen,
  1272. sk_gfp_mask(sk, GFP_ATOMIC));
  1273. }
  1274. EXPORT_SYMBOL(tcp_md5_key_copy);
  1275. int tcp_md5_do_del(struct sock *sk, const union tcp_md5_addr *addr, int family,
  1276. u8 prefixlen, int l3index, u8 flags)
  1277. {
  1278. struct tcp_md5sig_key *key;
  1279. key = tcp_md5_do_lookup_exact(sk, addr, family, prefixlen, l3index, flags);
  1280. if (!key)
  1281. return -ENOENT;
  1282. hlist_del_rcu(&key->node);
  1283. atomic_sub(sizeof(*key), &sk->sk_omem_alloc);
  1284. kfree_rcu(key, rcu);
  1285. return 0;
  1286. }
  1287. EXPORT_SYMBOL(tcp_md5_do_del);
  1288. void tcp_clear_md5_list(struct sock *sk)
  1289. {
  1290. struct tcp_sock *tp = tcp_sk(sk);
  1291. struct tcp_md5sig_key *key;
  1292. struct hlist_node *n;
  1293. struct tcp_md5sig_info *md5sig;
  1294. md5sig = rcu_dereference_protected(tp->md5sig_info, 1);
  1295. hlist_for_each_entry_safe(key, n, &md5sig->head, node) {
  1296. hlist_del_rcu(&key->node);
  1297. atomic_sub(sizeof(*key), &sk->sk_omem_alloc);
  1298. kfree_rcu(key, rcu);
  1299. }
  1300. }
  1301. static int tcp_v4_parse_md5_keys(struct sock *sk, int optname,
  1302. sockptr_t optval, int optlen)
  1303. {
  1304. struct tcp_md5sig cmd;
  1305. struct sockaddr_in *sin = (struct sockaddr_in *)&cmd.tcpm_addr;
  1306. const union tcp_md5_addr *addr;
  1307. u8 prefixlen = 32;
  1308. int l3index = 0;
  1309. bool l3flag;
  1310. u8 flags;
  1311. if (optlen < sizeof(cmd))
  1312. return -EINVAL;
  1313. if (copy_from_sockptr(&cmd, optval, sizeof(cmd)))
  1314. return -EFAULT;
  1315. if (sin->sin_family != AF_INET)
  1316. return -EINVAL;
  1317. flags = cmd.tcpm_flags & TCP_MD5SIG_FLAG_IFINDEX;
  1318. l3flag = cmd.tcpm_flags & TCP_MD5SIG_FLAG_IFINDEX;
  1319. if (optname == TCP_MD5SIG_EXT &&
  1320. cmd.tcpm_flags & TCP_MD5SIG_FLAG_PREFIX) {
  1321. prefixlen = cmd.tcpm_prefixlen;
  1322. if (prefixlen > 32)
  1323. return -EINVAL;
  1324. }
  1325. if (optname == TCP_MD5SIG_EXT && cmd.tcpm_ifindex &&
  1326. cmd.tcpm_flags & TCP_MD5SIG_FLAG_IFINDEX) {
  1327. struct net_device *dev;
  1328. rcu_read_lock();
  1329. dev = dev_get_by_index_rcu(sock_net(sk), cmd.tcpm_ifindex);
  1330. if (dev && netif_is_l3_master(dev))
  1331. l3index = dev->ifindex;
  1332. rcu_read_unlock();
  1333. /* ok to reference set/not set outside of rcu;
  1334. * right now device MUST be an L3 master
  1335. */
  1336. if (!dev || !l3index)
  1337. return -EINVAL;
  1338. }
  1339. addr = (union tcp_md5_addr *)&sin->sin_addr.s_addr;
  1340. if (!cmd.tcpm_keylen)
  1341. return tcp_md5_do_del(sk, addr, AF_INET, prefixlen, l3index, flags);
  1342. if (cmd.tcpm_keylen > TCP_MD5SIG_MAXKEYLEN)
  1343. return -EINVAL;
  1344. /* Don't allow keys for peers that have a matching TCP-AO key.
  1345. * See the comment in tcp_ao_add_cmd()
  1346. */
  1347. if (tcp_ao_required(sk, addr, AF_INET, l3flag ? l3index : -1, false))
  1348. return -EKEYREJECTED;
  1349. return tcp_md5_do_add(sk, addr, AF_INET, prefixlen, l3index, flags,
  1350. cmd.tcpm_key, cmd.tcpm_keylen);
  1351. }
  1352. static int tcp_v4_md5_hash_headers(struct tcp_sigpool *hp,
  1353. __be32 daddr, __be32 saddr,
  1354. const struct tcphdr *th, int nbytes)
  1355. {
  1356. struct tcp4_pseudohdr *bp;
  1357. struct scatterlist sg;
  1358. struct tcphdr *_th;
  1359. bp = hp->scratch;
  1360. bp->saddr = saddr;
  1361. bp->daddr = daddr;
  1362. bp->pad = 0;
  1363. bp->protocol = IPPROTO_TCP;
  1364. bp->len = cpu_to_be16(nbytes);
  1365. _th = (struct tcphdr *)(bp + 1);
  1366. memcpy(_th, th, sizeof(*th));
  1367. _th->check = 0;
  1368. sg_init_one(&sg, bp, sizeof(*bp) + sizeof(*th));
  1369. ahash_request_set_crypt(hp->req, &sg, NULL,
  1370. sizeof(*bp) + sizeof(*th));
  1371. return crypto_ahash_update(hp->req);
  1372. }
  1373. static int tcp_v4_md5_hash_hdr(char *md5_hash, const struct tcp_md5sig_key *key,
  1374. __be32 daddr, __be32 saddr, const struct tcphdr *th)
  1375. {
  1376. struct tcp_sigpool hp;
  1377. if (tcp_sigpool_start(tcp_md5_sigpool_id, &hp))
  1378. goto clear_hash_nostart;
  1379. if (crypto_ahash_init(hp.req))
  1380. goto clear_hash;
  1381. if (tcp_v4_md5_hash_headers(&hp, daddr, saddr, th, th->doff << 2))
  1382. goto clear_hash;
  1383. if (tcp_md5_hash_key(&hp, key))
  1384. goto clear_hash;
  1385. ahash_request_set_crypt(hp.req, NULL, md5_hash, 0);
  1386. if (crypto_ahash_final(hp.req))
  1387. goto clear_hash;
  1388. tcp_sigpool_end(&hp);
  1389. return 0;
  1390. clear_hash:
  1391. tcp_sigpool_end(&hp);
  1392. clear_hash_nostart:
  1393. memset(md5_hash, 0, 16);
  1394. return 1;
  1395. }
  1396. int tcp_v4_md5_hash_skb(char *md5_hash, const struct tcp_md5sig_key *key,
  1397. const struct sock *sk,
  1398. const struct sk_buff *skb)
  1399. {
  1400. const struct tcphdr *th = tcp_hdr(skb);
  1401. struct tcp_sigpool hp;
  1402. __be32 saddr, daddr;
  1403. if (sk) { /* valid for establish/request sockets */
  1404. saddr = sk->sk_rcv_saddr;
  1405. daddr = sk->sk_daddr;
  1406. } else {
  1407. const struct iphdr *iph = ip_hdr(skb);
  1408. saddr = iph->saddr;
  1409. daddr = iph->daddr;
  1410. }
  1411. if (tcp_sigpool_start(tcp_md5_sigpool_id, &hp))
  1412. goto clear_hash_nostart;
  1413. if (crypto_ahash_init(hp.req))
  1414. goto clear_hash;
  1415. if (tcp_v4_md5_hash_headers(&hp, daddr, saddr, th, skb->len))
  1416. goto clear_hash;
  1417. if (tcp_sigpool_hash_skb_data(&hp, skb, th->doff << 2))
  1418. goto clear_hash;
  1419. if (tcp_md5_hash_key(&hp, key))
  1420. goto clear_hash;
  1421. ahash_request_set_crypt(hp.req, NULL, md5_hash, 0);
  1422. if (crypto_ahash_final(hp.req))
  1423. goto clear_hash;
  1424. tcp_sigpool_end(&hp);
  1425. return 0;
  1426. clear_hash:
  1427. tcp_sigpool_end(&hp);
  1428. clear_hash_nostart:
  1429. memset(md5_hash, 0, 16);
  1430. return 1;
  1431. }
  1432. EXPORT_SYMBOL(tcp_v4_md5_hash_skb);
  1433. #endif
  1434. static void tcp_v4_init_req(struct request_sock *req,
  1435. const struct sock *sk_listener,
  1436. struct sk_buff *skb)
  1437. {
  1438. struct inet_request_sock *ireq = inet_rsk(req);
  1439. struct net *net = sock_net(sk_listener);
  1440. sk_rcv_saddr_set(req_to_sk(req), ip_hdr(skb)->daddr);
  1441. sk_daddr_set(req_to_sk(req), ip_hdr(skb)->saddr);
  1442. RCU_INIT_POINTER(ireq->ireq_opt, tcp_v4_save_options(net, skb));
  1443. }
  1444. static struct dst_entry *tcp_v4_route_req(const struct sock *sk,
  1445. struct sk_buff *skb,
  1446. struct flowi *fl,
  1447. struct request_sock *req,
  1448. u32 tw_isn)
  1449. {
  1450. tcp_v4_init_req(req, sk, skb);
  1451. if (security_inet_conn_request(sk, skb, req))
  1452. return NULL;
  1453. return inet_csk_route_req(sk, &fl->u.ip4, req);
  1454. }
  1455. struct request_sock_ops tcp_request_sock_ops __read_mostly = {
  1456. .family = PF_INET,
  1457. .obj_size = sizeof(struct tcp_request_sock),
  1458. .rtx_syn_ack = tcp_rtx_synack,
  1459. .send_ack = tcp_v4_reqsk_send_ack,
  1460. .destructor = tcp_v4_reqsk_destructor,
  1461. .send_reset = tcp_v4_send_reset,
  1462. .syn_ack_timeout = tcp_syn_ack_timeout,
  1463. };
  1464. const struct tcp_request_sock_ops tcp_request_sock_ipv4_ops = {
  1465. .mss_clamp = TCP_MSS_DEFAULT,
  1466. #ifdef CONFIG_TCP_MD5SIG
  1467. .req_md5_lookup = tcp_v4_md5_lookup,
  1468. .calc_md5_hash = tcp_v4_md5_hash_skb,
  1469. #endif
  1470. #ifdef CONFIG_TCP_AO
  1471. .ao_lookup = tcp_v4_ao_lookup_rsk,
  1472. .ao_calc_key = tcp_v4_ao_calc_key_rsk,
  1473. .ao_synack_hash = tcp_v4_ao_synack_hash,
  1474. #endif
  1475. #ifdef CONFIG_SYN_COOKIES
  1476. .cookie_init_seq = cookie_v4_init_sequence,
  1477. #endif
  1478. .route_req = tcp_v4_route_req,
  1479. .init_seq = tcp_v4_init_seq,
  1480. .init_ts_off = tcp_v4_init_ts_off,
  1481. .send_synack = tcp_v4_send_synack,
  1482. };
  1483. int tcp_v4_conn_request(struct sock *sk, struct sk_buff *skb)
  1484. {
  1485. /* Never answer to SYNs send to broadcast or multicast */
  1486. if (skb_rtable(skb)->rt_flags & (RTCF_BROADCAST | RTCF_MULTICAST))
  1487. goto drop;
  1488. return tcp_conn_request(&tcp_request_sock_ops,
  1489. &tcp_request_sock_ipv4_ops, sk, skb);
  1490. drop:
  1491. tcp_listendrop(sk);
  1492. return 0;
  1493. }
  1494. EXPORT_SYMBOL(tcp_v4_conn_request);
  1495. /*
  1496. * The three way handshake has completed - we got a valid synack -
  1497. * now create the new socket.
  1498. */
  1499. struct sock *tcp_v4_syn_recv_sock(const struct sock *sk, struct sk_buff *skb,
  1500. struct request_sock *req,
  1501. struct dst_entry *dst,
  1502. struct request_sock *req_unhash,
  1503. bool *own_req)
  1504. {
  1505. struct inet_request_sock *ireq;
  1506. bool found_dup_sk = false;
  1507. struct inet_sock *newinet;
  1508. struct tcp_sock *newtp;
  1509. struct sock *newsk;
  1510. #ifdef CONFIG_TCP_MD5SIG
  1511. const union tcp_md5_addr *addr;
  1512. struct tcp_md5sig_key *key;
  1513. int l3index;
  1514. #endif
  1515. struct ip_options_rcu *inet_opt;
  1516. if (sk_acceptq_is_full(sk))
  1517. goto exit_overflow;
  1518. newsk = tcp_create_openreq_child(sk, req, skb);
  1519. if (!newsk)
  1520. goto exit_nonewsk;
  1521. newsk->sk_gso_type = SKB_GSO_TCPV4;
  1522. inet_sk_rx_dst_set(newsk, skb);
  1523. newtp = tcp_sk(newsk);
  1524. newinet = inet_sk(newsk);
  1525. ireq = inet_rsk(req);
  1526. sk_daddr_set(newsk, ireq->ir_rmt_addr);
  1527. sk_rcv_saddr_set(newsk, ireq->ir_loc_addr);
  1528. newsk->sk_bound_dev_if = ireq->ir_iif;
  1529. newinet->inet_saddr = ireq->ir_loc_addr;
  1530. inet_opt = rcu_dereference(ireq->ireq_opt);
  1531. RCU_INIT_POINTER(newinet->inet_opt, inet_opt);
  1532. newinet->mc_index = inet_iif(skb);
  1533. newinet->mc_ttl = ip_hdr(skb)->ttl;
  1534. newinet->rcv_tos = ip_hdr(skb)->tos;
  1535. inet_csk(newsk)->icsk_ext_hdr_len = 0;
  1536. if (inet_opt)
  1537. inet_csk(newsk)->icsk_ext_hdr_len = inet_opt->opt.optlen;
  1538. atomic_set(&newinet->inet_id, get_random_u16());
  1539. /* Set ToS of the new socket based upon the value of incoming SYN.
  1540. * ECT bits are set later in tcp_init_transfer().
  1541. */
  1542. if (READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_reflect_tos))
  1543. newinet->tos = tcp_rsk(req)->syn_tos & ~INET_ECN_MASK;
  1544. if (!dst) {
  1545. dst = inet_csk_route_child_sock(sk, newsk, req);
  1546. if (!dst)
  1547. goto put_and_exit;
  1548. } else {
  1549. /* syncookie case : see end of cookie_v4_check() */
  1550. }
  1551. sk_setup_caps(newsk, dst);
  1552. tcp_ca_openreq_child(newsk, dst);
  1553. tcp_sync_mss(newsk, dst_mtu(dst));
  1554. newtp->advmss = tcp_mss_clamp(tcp_sk(sk), dst_metric_advmss(dst));
  1555. tcp_initialize_rcv_mss(newsk);
  1556. #ifdef CONFIG_TCP_MD5SIG
  1557. l3index = l3mdev_master_ifindex_by_index(sock_net(sk), ireq->ir_iif);
  1558. /* Copy over the MD5 key from the original socket */
  1559. addr = (union tcp_md5_addr *)&newinet->inet_daddr;
  1560. key = tcp_md5_do_lookup(sk, l3index, addr, AF_INET);
  1561. if (key && !tcp_rsk_used_ao(req)) {
  1562. if (tcp_md5_key_copy(newsk, addr, AF_INET, 32, l3index, key))
  1563. goto put_and_exit;
  1564. sk_gso_disable(newsk);
  1565. }
  1566. #endif
  1567. #ifdef CONFIG_TCP_AO
  1568. if (tcp_ao_copy_all_matching(sk, newsk, req, skb, AF_INET))
  1569. goto put_and_exit; /* OOM, release back memory */
  1570. #endif
  1571. if (__inet_inherit_port(sk, newsk) < 0)
  1572. goto put_and_exit;
  1573. *own_req = inet_ehash_nolisten(newsk, req_to_sk(req_unhash),
  1574. &found_dup_sk);
  1575. if (likely(*own_req)) {
  1576. tcp_move_syn(newtp, req);
  1577. ireq->ireq_opt = NULL;
  1578. } else {
  1579. newinet->inet_opt = NULL;
  1580. if (!req_unhash && found_dup_sk) {
  1581. /* This code path should only be executed in the
  1582. * syncookie case only
  1583. */
  1584. bh_unlock_sock(newsk);
  1585. sock_put(newsk);
  1586. newsk = NULL;
  1587. }
  1588. }
  1589. return newsk;
  1590. exit_overflow:
  1591. NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS);
  1592. exit_nonewsk:
  1593. dst_release(dst);
  1594. exit:
  1595. tcp_listendrop(sk);
  1596. return NULL;
  1597. put_and_exit:
  1598. newinet->inet_opt = NULL;
  1599. inet_csk_prepare_forced_close(newsk);
  1600. tcp_done(newsk);
  1601. goto exit;
  1602. }
  1603. EXPORT_SYMBOL(tcp_v4_syn_recv_sock);
  1604. static struct sock *tcp_v4_cookie_check(struct sock *sk, struct sk_buff *skb)
  1605. {
  1606. #ifdef CONFIG_SYN_COOKIES
  1607. const struct tcphdr *th = tcp_hdr(skb);
  1608. if (!th->syn)
  1609. sk = cookie_v4_check(sk, skb);
  1610. #endif
  1611. return sk;
  1612. }
  1613. u16 tcp_v4_get_syncookie(struct sock *sk, struct iphdr *iph,
  1614. struct tcphdr *th, u32 *cookie)
  1615. {
  1616. u16 mss = 0;
  1617. #ifdef CONFIG_SYN_COOKIES
  1618. mss = tcp_get_syncookie_mss(&tcp_request_sock_ops,
  1619. &tcp_request_sock_ipv4_ops, sk, th);
  1620. if (mss) {
  1621. *cookie = __cookie_v4_init_sequence(iph, th, &mss);
  1622. tcp_synq_overflow(sk);
  1623. }
  1624. #endif
  1625. return mss;
  1626. }
  1627. INDIRECT_CALLABLE_DECLARE(struct dst_entry *ipv4_dst_check(struct dst_entry *,
  1628. u32));
  1629. /* The socket must have it's spinlock held when we get
  1630. * here, unless it is a TCP_LISTEN socket.
  1631. *
  1632. * We have a potential double-lock case here, so even when
  1633. * doing backlog processing we use the BH locking scheme.
  1634. * This is because we cannot sleep with the original spinlock
  1635. * held.
  1636. */
  1637. int tcp_v4_do_rcv(struct sock *sk, struct sk_buff *skb)
  1638. {
  1639. enum skb_drop_reason reason;
  1640. struct sock *rsk;
  1641. if (sk->sk_state == TCP_ESTABLISHED) { /* Fast path */
  1642. struct dst_entry *dst;
  1643. dst = rcu_dereference_protected(sk->sk_rx_dst,
  1644. lockdep_sock_is_held(sk));
  1645. sock_rps_save_rxhash(sk, skb);
  1646. sk_mark_napi_id(sk, skb);
  1647. if (dst) {
  1648. if (sk->sk_rx_dst_ifindex != skb->skb_iif ||
  1649. !INDIRECT_CALL_1(dst->ops->check, ipv4_dst_check,
  1650. dst, 0)) {
  1651. RCU_INIT_POINTER(sk->sk_rx_dst, NULL);
  1652. dst_release(dst);
  1653. }
  1654. }
  1655. tcp_rcv_established(sk, skb);
  1656. return 0;
  1657. }
  1658. if (tcp_checksum_complete(skb))
  1659. goto csum_err;
  1660. if (sk->sk_state == TCP_LISTEN) {
  1661. struct sock *nsk = tcp_v4_cookie_check(sk, skb);
  1662. if (!nsk)
  1663. return 0;
  1664. if (nsk != sk) {
  1665. reason = tcp_child_process(sk, nsk, skb);
  1666. if (reason) {
  1667. rsk = nsk;
  1668. goto reset;
  1669. }
  1670. return 0;
  1671. }
  1672. } else
  1673. sock_rps_save_rxhash(sk, skb);
  1674. reason = tcp_rcv_state_process(sk, skb);
  1675. if (reason) {
  1676. rsk = sk;
  1677. goto reset;
  1678. }
  1679. return 0;
  1680. reset:
  1681. tcp_v4_send_reset(rsk, skb, sk_rst_convert_drop_reason(reason));
  1682. discard:
  1683. sk_skb_reason_drop(sk, skb, reason);
  1684. /* Be careful here. If this function gets more complicated and
  1685. * gcc suffers from register pressure on the x86, sk (in %ebx)
  1686. * might be destroyed here. This current version compiles correctly,
  1687. * but you have been warned.
  1688. */
  1689. return 0;
  1690. csum_err:
  1691. reason = SKB_DROP_REASON_TCP_CSUM;
  1692. trace_tcp_bad_csum(skb);
  1693. TCP_INC_STATS(sock_net(sk), TCP_MIB_CSUMERRORS);
  1694. TCP_INC_STATS(sock_net(sk), TCP_MIB_INERRS);
  1695. goto discard;
  1696. }
  1697. EXPORT_SYMBOL(tcp_v4_do_rcv);
  1698. int tcp_v4_early_demux(struct sk_buff *skb)
  1699. {
  1700. struct net *net = dev_net_rcu(skb->dev);
  1701. const struct iphdr *iph;
  1702. const struct tcphdr *th;
  1703. struct sock *sk;
  1704. if (skb->pkt_type != PACKET_HOST)
  1705. return 0;
  1706. if (!pskb_may_pull(skb, skb_transport_offset(skb) + sizeof(struct tcphdr)))
  1707. return 0;
  1708. iph = ip_hdr(skb);
  1709. th = tcp_hdr(skb);
  1710. if (th->doff < sizeof(struct tcphdr) / 4)
  1711. return 0;
  1712. sk = __inet_lookup_established(net, net->ipv4.tcp_death_row.hashinfo,
  1713. iph->saddr, th->source,
  1714. iph->daddr, ntohs(th->dest),
  1715. skb->skb_iif, inet_sdif(skb));
  1716. if (sk) {
  1717. skb->sk = sk;
  1718. skb->destructor = sock_edemux;
  1719. if (sk_fullsock(sk)) {
  1720. struct dst_entry *dst = rcu_dereference(sk->sk_rx_dst);
  1721. if (dst)
  1722. dst = dst_check(dst, 0);
  1723. if (dst &&
  1724. sk->sk_rx_dst_ifindex == skb->skb_iif)
  1725. skb_dst_set_noref(skb, dst);
  1726. }
  1727. }
  1728. return 0;
  1729. }
  1730. bool tcp_add_backlog(struct sock *sk, struct sk_buff *skb,
  1731. enum skb_drop_reason *reason)
  1732. {
  1733. u32 tail_gso_size, tail_gso_segs;
  1734. struct skb_shared_info *shinfo;
  1735. const struct tcphdr *th;
  1736. struct tcphdr *thtail;
  1737. struct sk_buff *tail;
  1738. unsigned int hdrlen;
  1739. bool fragstolen;
  1740. u32 gso_segs;
  1741. u32 gso_size;
  1742. u64 limit;
  1743. int delta;
  1744. /* In case all data was pulled from skb frags (in __pskb_pull_tail()),
  1745. * we can fix skb->truesize to its real value to avoid future drops.
  1746. * This is valid because skb is not yet charged to the socket.
  1747. * It has been noticed pure SACK packets were sometimes dropped
  1748. * (if cooked by drivers without copybreak feature).
  1749. */
  1750. skb_condense(skb);
  1751. tcp_cleanup_skb(skb);
  1752. if (unlikely(tcp_checksum_complete(skb))) {
  1753. bh_unlock_sock(sk);
  1754. trace_tcp_bad_csum(skb);
  1755. *reason = SKB_DROP_REASON_TCP_CSUM;
  1756. __TCP_INC_STATS(sock_net(sk), TCP_MIB_CSUMERRORS);
  1757. __TCP_INC_STATS(sock_net(sk), TCP_MIB_INERRS);
  1758. return true;
  1759. }
  1760. /* Attempt coalescing to last skb in backlog, even if we are
  1761. * above the limits.
  1762. * This is okay because skb capacity is limited to MAX_SKB_FRAGS.
  1763. */
  1764. th = (const struct tcphdr *)skb->data;
  1765. hdrlen = th->doff * 4;
  1766. tail = sk->sk_backlog.tail;
  1767. if (!tail)
  1768. goto no_coalesce;
  1769. thtail = (struct tcphdr *)tail->data;
  1770. if (TCP_SKB_CB(tail)->end_seq != TCP_SKB_CB(skb)->seq ||
  1771. TCP_SKB_CB(tail)->ip_dsfield != TCP_SKB_CB(skb)->ip_dsfield ||
  1772. ((TCP_SKB_CB(tail)->tcp_flags |
  1773. TCP_SKB_CB(skb)->tcp_flags) & (TCPHDR_SYN | TCPHDR_RST | TCPHDR_URG)) ||
  1774. !((TCP_SKB_CB(tail)->tcp_flags &
  1775. TCP_SKB_CB(skb)->tcp_flags) & TCPHDR_ACK) ||
  1776. ((TCP_SKB_CB(tail)->tcp_flags ^
  1777. TCP_SKB_CB(skb)->tcp_flags) & (TCPHDR_ECE | TCPHDR_CWR)) ||
  1778. !tcp_skb_can_collapse_rx(tail, skb) ||
  1779. thtail->doff != th->doff ||
  1780. memcmp(thtail + 1, th + 1, hdrlen - sizeof(*th)))
  1781. goto no_coalesce;
  1782. __skb_pull(skb, hdrlen);
  1783. shinfo = skb_shinfo(skb);
  1784. gso_size = shinfo->gso_size ?: skb->len;
  1785. gso_segs = shinfo->gso_segs ?: 1;
  1786. shinfo = skb_shinfo(tail);
  1787. tail_gso_size = shinfo->gso_size ?: (tail->len - hdrlen);
  1788. tail_gso_segs = shinfo->gso_segs ?: 1;
  1789. if (skb_try_coalesce(tail, skb, &fragstolen, &delta)) {
  1790. TCP_SKB_CB(tail)->end_seq = TCP_SKB_CB(skb)->end_seq;
  1791. if (likely(!before(TCP_SKB_CB(skb)->ack_seq, TCP_SKB_CB(tail)->ack_seq))) {
  1792. TCP_SKB_CB(tail)->ack_seq = TCP_SKB_CB(skb)->ack_seq;
  1793. thtail->window = th->window;
  1794. }
  1795. /* We have to update both TCP_SKB_CB(tail)->tcp_flags and
  1796. * thtail->fin, so that the fast path in tcp_rcv_established()
  1797. * is not entered if we append a packet with a FIN.
  1798. * SYN, RST, URG are not present.
  1799. * ACK is set on both packets.
  1800. * PSH : we do not really care in TCP stack,
  1801. * at least for 'GRO' packets.
  1802. */
  1803. thtail->fin |= th->fin;
  1804. TCP_SKB_CB(tail)->tcp_flags |= TCP_SKB_CB(skb)->tcp_flags;
  1805. if (TCP_SKB_CB(skb)->has_rxtstamp) {
  1806. TCP_SKB_CB(tail)->has_rxtstamp = true;
  1807. tail->tstamp = skb->tstamp;
  1808. skb_hwtstamps(tail)->hwtstamp = skb_hwtstamps(skb)->hwtstamp;
  1809. }
  1810. /* Not as strict as GRO. We only need to carry mss max value */
  1811. shinfo->gso_size = max(gso_size, tail_gso_size);
  1812. shinfo->gso_segs = min_t(u32, gso_segs + tail_gso_segs, 0xFFFF);
  1813. sk->sk_backlog.len += delta;
  1814. __NET_INC_STATS(sock_net(sk),
  1815. LINUX_MIB_TCPBACKLOGCOALESCE);
  1816. kfree_skb_partial(skb, fragstolen);
  1817. return false;
  1818. }
  1819. __skb_push(skb, hdrlen);
  1820. no_coalesce:
  1821. /* sk->sk_backlog.len is reset only at the end of __release_sock().
  1822. * Both sk->sk_backlog.len and sk->sk_rmem_alloc could reach
  1823. * sk_rcvbuf in normal conditions.
  1824. */
  1825. limit = ((u64)READ_ONCE(sk->sk_rcvbuf)) << 1;
  1826. limit += ((u32)READ_ONCE(sk->sk_sndbuf)) >> 1;
  1827. /* Only socket owner can try to collapse/prune rx queues
  1828. * to reduce memory overhead, so add a little headroom here.
  1829. * Few sockets backlog are possibly concurrently non empty.
  1830. */
  1831. limit += 64 * 1024;
  1832. limit = min_t(u64, limit, UINT_MAX);
  1833. if (unlikely(sk_add_backlog(sk, skb, limit))) {
  1834. bh_unlock_sock(sk);
  1835. *reason = SKB_DROP_REASON_SOCKET_BACKLOG;
  1836. __NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPBACKLOGDROP);
  1837. return true;
  1838. }
  1839. return false;
  1840. }
  1841. EXPORT_SYMBOL(tcp_add_backlog);
  1842. int tcp_filter(struct sock *sk, struct sk_buff *skb)
  1843. {
  1844. struct tcphdr *th = (struct tcphdr *)skb->data;
  1845. return sk_filter_trim_cap(sk, skb, th->doff * 4);
  1846. }
  1847. EXPORT_SYMBOL(tcp_filter);
  1848. static void tcp_v4_restore_cb(struct sk_buff *skb)
  1849. {
  1850. memmove(IPCB(skb), &TCP_SKB_CB(skb)->header.h4,
  1851. sizeof(struct inet_skb_parm));
  1852. }
  1853. static void tcp_v4_fill_cb(struct sk_buff *skb, const struct iphdr *iph,
  1854. const struct tcphdr *th)
  1855. {
  1856. /* This is tricky : We move IPCB at its correct location into TCP_SKB_CB()
  1857. * barrier() makes sure compiler wont play fool^Waliasing games.
  1858. */
  1859. memmove(&TCP_SKB_CB(skb)->header.h4, IPCB(skb),
  1860. sizeof(struct inet_skb_parm));
  1861. barrier();
  1862. TCP_SKB_CB(skb)->seq = ntohl(th->seq);
  1863. TCP_SKB_CB(skb)->end_seq = (TCP_SKB_CB(skb)->seq + th->syn + th->fin +
  1864. skb->len - th->doff * 4);
  1865. TCP_SKB_CB(skb)->ack_seq = ntohl(th->ack_seq);
  1866. TCP_SKB_CB(skb)->tcp_flags = tcp_flag_byte(th);
  1867. TCP_SKB_CB(skb)->ip_dsfield = ipv4_get_dsfield(iph);
  1868. TCP_SKB_CB(skb)->sacked = 0;
  1869. TCP_SKB_CB(skb)->has_rxtstamp =
  1870. skb->tstamp || skb_hwtstamps(skb)->hwtstamp;
  1871. }
  1872. /*
  1873. * From tcp_input.c
  1874. */
  1875. int tcp_v4_rcv(struct sk_buff *skb)
  1876. {
  1877. struct net *net = dev_net_rcu(skb->dev);
  1878. enum skb_drop_reason drop_reason;
  1879. int sdif = inet_sdif(skb);
  1880. int dif = inet_iif(skb);
  1881. const struct iphdr *iph;
  1882. const struct tcphdr *th;
  1883. struct sock *sk = NULL;
  1884. bool refcounted;
  1885. int ret;
  1886. u32 isn;
  1887. drop_reason = SKB_DROP_REASON_NOT_SPECIFIED;
  1888. if (skb->pkt_type != PACKET_HOST)
  1889. goto discard_it;
  1890. /* Count it even if it's bad */
  1891. __TCP_INC_STATS(net, TCP_MIB_INSEGS);
  1892. if (!pskb_may_pull(skb, sizeof(struct tcphdr)))
  1893. goto discard_it;
  1894. th = (const struct tcphdr *)skb->data;
  1895. if (unlikely(th->doff < sizeof(struct tcphdr) / 4)) {
  1896. drop_reason = SKB_DROP_REASON_PKT_TOO_SMALL;
  1897. goto bad_packet;
  1898. }
  1899. if (!pskb_may_pull(skb, th->doff * 4))
  1900. goto discard_it;
  1901. /* An explanation is required here, I think.
  1902. * Packet length and doff are validated by header prediction,
  1903. * provided case of th->doff==0 is eliminated.
  1904. * So, we defer the checks. */
  1905. if (skb_checksum_init(skb, IPPROTO_TCP, inet_compute_pseudo))
  1906. goto csum_error;
  1907. th = (const struct tcphdr *)skb->data;
  1908. iph = ip_hdr(skb);
  1909. lookup:
  1910. sk = __inet_lookup_skb(net->ipv4.tcp_death_row.hashinfo,
  1911. skb, __tcp_hdrlen(th), th->source,
  1912. th->dest, sdif, &refcounted);
  1913. if (!sk)
  1914. goto no_tcp_socket;
  1915. if (sk->sk_state == TCP_TIME_WAIT)
  1916. goto do_time_wait;
  1917. if (sk->sk_state == TCP_NEW_SYN_RECV) {
  1918. struct request_sock *req = inet_reqsk(sk);
  1919. bool req_stolen = false;
  1920. struct sock *nsk;
  1921. sk = req->rsk_listener;
  1922. if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb))
  1923. drop_reason = SKB_DROP_REASON_XFRM_POLICY;
  1924. else
  1925. drop_reason = tcp_inbound_hash(sk, req, skb,
  1926. &iph->saddr, &iph->daddr,
  1927. AF_INET, dif, sdif);
  1928. if (unlikely(drop_reason)) {
  1929. sk_drops_add(sk, skb);
  1930. reqsk_put(req);
  1931. goto discard_it;
  1932. }
  1933. if (tcp_checksum_complete(skb)) {
  1934. reqsk_put(req);
  1935. goto csum_error;
  1936. }
  1937. if (unlikely(sk->sk_state != TCP_LISTEN)) {
  1938. nsk = reuseport_migrate_sock(sk, req_to_sk(req), skb);
  1939. if (!nsk) {
  1940. inet_csk_reqsk_queue_drop_and_put(sk, req);
  1941. goto lookup;
  1942. }
  1943. sk = nsk;
  1944. /* reuseport_migrate_sock() has already held one sk_refcnt
  1945. * before returning.
  1946. */
  1947. } else {
  1948. /* We own a reference on the listener, increase it again
  1949. * as we might lose it too soon.
  1950. */
  1951. sock_hold(sk);
  1952. }
  1953. refcounted = true;
  1954. nsk = NULL;
  1955. if (!tcp_filter(sk, skb)) {
  1956. th = (const struct tcphdr *)skb->data;
  1957. iph = ip_hdr(skb);
  1958. tcp_v4_fill_cb(skb, iph, th);
  1959. nsk = tcp_check_req(sk, skb, req, false, &req_stolen);
  1960. } else {
  1961. drop_reason = SKB_DROP_REASON_SOCKET_FILTER;
  1962. }
  1963. if (!nsk) {
  1964. reqsk_put(req);
  1965. if (req_stolen) {
  1966. /* Another cpu got exclusive access to req
  1967. * and created a full blown socket.
  1968. * Try to feed this packet to this socket
  1969. * instead of discarding it.
  1970. */
  1971. tcp_v4_restore_cb(skb);
  1972. sock_put(sk);
  1973. goto lookup;
  1974. }
  1975. goto discard_and_relse;
  1976. }
  1977. nf_reset_ct(skb);
  1978. if (nsk == sk) {
  1979. reqsk_put(req);
  1980. tcp_v4_restore_cb(skb);
  1981. } else {
  1982. drop_reason = tcp_child_process(sk, nsk, skb);
  1983. if (drop_reason) {
  1984. enum sk_rst_reason rst_reason;
  1985. rst_reason = sk_rst_convert_drop_reason(drop_reason);
  1986. tcp_v4_send_reset(nsk, skb, rst_reason);
  1987. goto discard_and_relse;
  1988. }
  1989. sock_put(sk);
  1990. return 0;
  1991. }
  1992. }
  1993. process:
  1994. if (static_branch_unlikely(&ip4_min_ttl)) {
  1995. /* min_ttl can be changed concurrently from do_ip_setsockopt() */
  1996. if (unlikely(iph->ttl < READ_ONCE(inet_sk(sk)->min_ttl))) {
  1997. __NET_INC_STATS(net, LINUX_MIB_TCPMINTTLDROP);
  1998. drop_reason = SKB_DROP_REASON_TCP_MINTTL;
  1999. goto discard_and_relse;
  2000. }
  2001. }
  2002. if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) {
  2003. drop_reason = SKB_DROP_REASON_XFRM_POLICY;
  2004. goto discard_and_relse;
  2005. }
  2006. drop_reason = tcp_inbound_hash(sk, NULL, skb, &iph->saddr, &iph->daddr,
  2007. AF_INET, dif, sdif);
  2008. if (drop_reason)
  2009. goto discard_and_relse;
  2010. nf_reset_ct(skb);
  2011. if (tcp_filter(sk, skb)) {
  2012. drop_reason = SKB_DROP_REASON_SOCKET_FILTER;
  2013. goto discard_and_relse;
  2014. }
  2015. th = (const struct tcphdr *)skb->data;
  2016. iph = ip_hdr(skb);
  2017. tcp_v4_fill_cb(skb, iph, th);
  2018. skb->dev = NULL;
  2019. if (sk->sk_state == TCP_LISTEN) {
  2020. ret = tcp_v4_do_rcv(sk, skb);
  2021. goto put_and_return;
  2022. }
  2023. sk_incoming_cpu_update(sk);
  2024. bh_lock_sock_nested(sk);
  2025. tcp_segs_in(tcp_sk(sk), skb);
  2026. ret = 0;
  2027. if (!sock_owned_by_user(sk)) {
  2028. ret = tcp_v4_do_rcv(sk, skb);
  2029. } else {
  2030. if (tcp_add_backlog(sk, skb, &drop_reason))
  2031. goto discard_and_relse;
  2032. }
  2033. bh_unlock_sock(sk);
  2034. put_and_return:
  2035. if (refcounted)
  2036. sock_put(sk);
  2037. return ret;
  2038. no_tcp_socket:
  2039. drop_reason = SKB_DROP_REASON_NO_SOCKET;
  2040. if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
  2041. goto discard_it;
  2042. tcp_v4_fill_cb(skb, iph, th);
  2043. if (tcp_checksum_complete(skb)) {
  2044. csum_error:
  2045. drop_reason = SKB_DROP_REASON_TCP_CSUM;
  2046. trace_tcp_bad_csum(skb);
  2047. __TCP_INC_STATS(net, TCP_MIB_CSUMERRORS);
  2048. bad_packet:
  2049. __TCP_INC_STATS(net, TCP_MIB_INERRS);
  2050. } else {
  2051. tcp_v4_send_reset(NULL, skb, sk_rst_convert_drop_reason(drop_reason));
  2052. }
  2053. discard_it:
  2054. SKB_DR_OR(drop_reason, NOT_SPECIFIED);
  2055. /* Discard frame. */
  2056. sk_skb_reason_drop(sk, skb, drop_reason);
  2057. return 0;
  2058. discard_and_relse:
  2059. sk_drops_add(sk, skb);
  2060. if (refcounted)
  2061. sock_put(sk);
  2062. goto discard_it;
  2063. do_time_wait:
  2064. if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb)) {
  2065. drop_reason = SKB_DROP_REASON_XFRM_POLICY;
  2066. inet_twsk_put(inet_twsk(sk));
  2067. goto discard_it;
  2068. }
  2069. tcp_v4_fill_cb(skb, iph, th);
  2070. if (tcp_checksum_complete(skb)) {
  2071. inet_twsk_put(inet_twsk(sk));
  2072. goto csum_error;
  2073. }
  2074. switch (tcp_timewait_state_process(inet_twsk(sk), skb, th, &isn)) {
  2075. case TCP_TW_SYN: {
  2076. struct sock *sk2 = inet_lookup_listener(net,
  2077. net->ipv4.tcp_death_row.hashinfo,
  2078. skb, __tcp_hdrlen(th),
  2079. iph->saddr, th->source,
  2080. iph->daddr, th->dest,
  2081. inet_iif(skb),
  2082. sdif);
  2083. if (sk2) {
  2084. inet_twsk_deschedule_put(inet_twsk(sk));
  2085. sk = sk2;
  2086. tcp_v4_restore_cb(skb);
  2087. refcounted = false;
  2088. __this_cpu_write(tcp_tw_isn, isn);
  2089. goto process;
  2090. }
  2091. }
  2092. /* to ACK */
  2093. fallthrough;
  2094. case TCP_TW_ACK:
  2095. tcp_v4_timewait_ack(sk, skb);
  2096. break;
  2097. case TCP_TW_RST:
  2098. tcp_v4_send_reset(sk, skb, SK_RST_REASON_TCP_TIMEWAIT_SOCKET);
  2099. inet_twsk_deschedule_put(inet_twsk(sk));
  2100. goto discard_it;
  2101. case TCP_TW_SUCCESS:;
  2102. }
  2103. goto discard_it;
  2104. }
  2105. static struct timewait_sock_ops tcp_timewait_sock_ops = {
  2106. .twsk_obj_size = sizeof(struct tcp_timewait_sock),
  2107. .twsk_destructor= tcp_twsk_destructor,
  2108. };
  2109. void inet_sk_rx_dst_set(struct sock *sk, const struct sk_buff *skb)
  2110. {
  2111. struct dst_entry *dst = skb_dst(skb);
  2112. if (dst && dst_hold_safe(dst)) {
  2113. rcu_assign_pointer(sk->sk_rx_dst, dst);
  2114. sk->sk_rx_dst_ifindex = skb->skb_iif;
  2115. }
  2116. }
  2117. EXPORT_SYMBOL(inet_sk_rx_dst_set);
  2118. const struct inet_connection_sock_af_ops ipv4_specific = {
  2119. .queue_xmit = ip_queue_xmit,
  2120. .send_check = tcp_v4_send_check,
  2121. .rebuild_header = inet_sk_rebuild_header,
  2122. .sk_rx_dst_set = inet_sk_rx_dst_set,
  2123. .conn_request = tcp_v4_conn_request,
  2124. .syn_recv_sock = tcp_v4_syn_recv_sock,
  2125. .net_header_len = sizeof(struct iphdr),
  2126. .setsockopt = ip_setsockopt,
  2127. .getsockopt = ip_getsockopt,
  2128. .addr2sockaddr = inet_csk_addr2sockaddr,
  2129. .sockaddr_len = sizeof(struct sockaddr_in),
  2130. .mtu_reduced = tcp_v4_mtu_reduced,
  2131. };
  2132. EXPORT_SYMBOL(ipv4_specific);
  2133. #if defined(CONFIG_TCP_MD5SIG) || defined(CONFIG_TCP_AO)
  2134. static const struct tcp_sock_af_ops tcp_sock_ipv4_specific = {
  2135. #ifdef CONFIG_TCP_MD5SIG
  2136. .md5_lookup = tcp_v4_md5_lookup,
  2137. .calc_md5_hash = tcp_v4_md5_hash_skb,
  2138. .md5_parse = tcp_v4_parse_md5_keys,
  2139. #endif
  2140. #ifdef CONFIG_TCP_AO
  2141. .ao_lookup = tcp_v4_ao_lookup,
  2142. .calc_ao_hash = tcp_v4_ao_hash_skb,
  2143. .ao_parse = tcp_v4_parse_ao,
  2144. .ao_calc_key_sk = tcp_v4_ao_calc_key_sk,
  2145. #endif
  2146. };
  2147. #endif
  2148. /* NOTE: A lot of things set to zero explicitly by call to
  2149. * sk_alloc() so need not be done here.
  2150. */
  2151. static int tcp_v4_init_sock(struct sock *sk)
  2152. {
  2153. struct inet_connection_sock *icsk = inet_csk(sk);
  2154. tcp_init_sock(sk);
  2155. icsk->icsk_af_ops = &ipv4_specific;
  2156. #if defined(CONFIG_TCP_MD5SIG) || defined(CONFIG_TCP_AO)
  2157. tcp_sk(sk)->af_specific = &tcp_sock_ipv4_specific;
  2158. #endif
  2159. return 0;
  2160. }
  2161. #ifdef CONFIG_TCP_MD5SIG
  2162. static void tcp_md5sig_info_free_rcu(struct rcu_head *head)
  2163. {
  2164. struct tcp_md5sig_info *md5sig;
  2165. md5sig = container_of(head, struct tcp_md5sig_info, rcu);
  2166. kfree(md5sig);
  2167. static_branch_slow_dec_deferred(&tcp_md5_needed);
  2168. tcp_md5_release_sigpool();
  2169. }
  2170. #endif
  2171. static void tcp_release_user_frags(struct sock *sk)
  2172. {
  2173. #ifdef CONFIG_PAGE_POOL
  2174. unsigned long index;
  2175. void *netmem;
  2176. xa_for_each(&sk->sk_user_frags, index, netmem)
  2177. WARN_ON_ONCE(!napi_pp_put_page((__force netmem_ref)netmem));
  2178. #endif
  2179. }
  2180. void tcp_v4_destroy_sock(struct sock *sk)
  2181. {
  2182. struct tcp_sock *tp = tcp_sk(sk);
  2183. tcp_release_user_frags(sk);
  2184. xa_destroy(&sk->sk_user_frags);
  2185. trace_tcp_destroy_sock(sk);
  2186. tcp_clear_xmit_timers(sk);
  2187. tcp_cleanup_congestion_control(sk);
  2188. tcp_cleanup_ulp(sk);
  2189. /* Cleanup up the write buffer. */
  2190. tcp_write_queue_purge(sk);
  2191. /* Check if we want to disable active TFO */
  2192. tcp_fastopen_active_disable_ofo_check(sk);
  2193. /* Cleans up our, hopefully empty, out_of_order_queue. */
  2194. skb_rbtree_purge(&tp->out_of_order_queue);
  2195. #ifdef CONFIG_TCP_MD5SIG
  2196. /* Clean up the MD5 key list, if any */
  2197. if (tp->md5sig_info) {
  2198. struct tcp_md5sig_info *md5sig;
  2199. md5sig = rcu_dereference_protected(tp->md5sig_info, 1);
  2200. tcp_clear_md5_list(sk);
  2201. call_rcu(&md5sig->rcu, tcp_md5sig_info_free_rcu);
  2202. rcu_assign_pointer(tp->md5sig_info, NULL);
  2203. }
  2204. #endif
  2205. tcp_ao_destroy_sock(sk, false);
  2206. /* Clean up a referenced TCP bind bucket. */
  2207. if (inet_csk(sk)->icsk_bind_hash)
  2208. inet_put_port(sk);
  2209. BUG_ON(rcu_access_pointer(tp->fastopen_rsk));
  2210. /* If socket is aborted during connect operation */
  2211. tcp_free_fastopen_req(tp);
  2212. tcp_fastopen_destroy_cipher(sk);
  2213. tcp_saved_syn_free(tp);
  2214. sk_sockets_allocated_dec(sk);
  2215. }
  2216. EXPORT_SYMBOL(tcp_v4_destroy_sock);
  2217. #ifdef CONFIG_PROC_FS
  2218. /* Proc filesystem TCP sock list dumping. */
  2219. static unsigned short seq_file_family(const struct seq_file *seq);
  2220. static bool seq_sk_match(struct seq_file *seq, const struct sock *sk)
  2221. {
  2222. unsigned short family = seq_file_family(seq);
  2223. /* AF_UNSPEC is used as a match all */
  2224. return ((family == AF_UNSPEC || family == sk->sk_family) &&
  2225. net_eq(sock_net(sk), seq_file_net(seq)));
  2226. }
  2227. /* Find a non empty bucket (starting from st->bucket)
  2228. * and return the first sk from it.
  2229. */
  2230. static void *listening_get_first(struct seq_file *seq)
  2231. {
  2232. struct inet_hashinfo *hinfo = seq_file_net(seq)->ipv4.tcp_death_row.hashinfo;
  2233. struct tcp_iter_state *st = seq->private;
  2234. st->offset = 0;
  2235. for (; st->bucket <= hinfo->lhash2_mask; st->bucket++) {
  2236. struct inet_listen_hashbucket *ilb2;
  2237. struct hlist_nulls_node *node;
  2238. struct sock *sk;
  2239. ilb2 = &hinfo->lhash2[st->bucket];
  2240. if (hlist_nulls_empty(&ilb2->nulls_head))
  2241. continue;
  2242. spin_lock(&ilb2->lock);
  2243. sk_nulls_for_each(sk, node, &ilb2->nulls_head) {
  2244. if (seq_sk_match(seq, sk))
  2245. return sk;
  2246. }
  2247. spin_unlock(&ilb2->lock);
  2248. }
  2249. return NULL;
  2250. }
  2251. /* Find the next sk of "cur" within the same bucket (i.e. st->bucket).
  2252. * If "cur" is the last one in the st->bucket,
  2253. * call listening_get_first() to return the first sk of the next
  2254. * non empty bucket.
  2255. */
  2256. static void *listening_get_next(struct seq_file *seq, void *cur)
  2257. {
  2258. struct tcp_iter_state *st = seq->private;
  2259. struct inet_listen_hashbucket *ilb2;
  2260. struct hlist_nulls_node *node;
  2261. struct inet_hashinfo *hinfo;
  2262. struct sock *sk = cur;
  2263. ++st->num;
  2264. ++st->offset;
  2265. sk = sk_nulls_next(sk);
  2266. sk_nulls_for_each_from(sk, node) {
  2267. if (seq_sk_match(seq, sk))
  2268. return sk;
  2269. }
  2270. hinfo = seq_file_net(seq)->ipv4.tcp_death_row.hashinfo;
  2271. ilb2 = &hinfo->lhash2[st->bucket];
  2272. spin_unlock(&ilb2->lock);
  2273. ++st->bucket;
  2274. return listening_get_first(seq);
  2275. }
  2276. static void *listening_get_idx(struct seq_file *seq, loff_t *pos)
  2277. {
  2278. struct tcp_iter_state *st = seq->private;
  2279. void *rc;
  2280. st->bucket = 0;
  2281. st->offset = 0;
  2282. rc = listening_get_first(seq);
  2283. while (rc && *pos) {
  2284. rc = listening_get_next(seq, rc);
  2285. --*pos;
  2286. }
  2287. return rc;
  2288. }
  2289. static inline bool empty_bucket(struct inet_hashinfo *hinfo,
  2290. const struct tcp_iter_state *st)
  2291. {
  2292. return hlist_nulls_empty(&hinfo->ehash[st->bucket].chain);
  2293. }
  2294. /*
  2295. * Get first established socket starting from bucket given in st->bucket.
  2296. * If st->bucket is zero, the very first socket in the hash is returned.
  2297. */
  2298. static void *established_get_first(struct seq_file *seq)
  2299. {
  2300. struct inet_hashinfo *hinfo = seq_file_net(seq)->ipv4.tcp_death_row.hashinfo;
  2301. struct tcp_iter_state *st = seq->private;
  2302. st->offset = 0;
  2303. for (; st->bucket <= hinfo->ehash_mask; ++st->bucket) {
  2304. struct sock *sk;
  2305. struct hlist_nulls_node *node;
  2306. spinlock_t *lock = inet_ehash_lockp(hinfo, st->bucket);
  2307. cond_resched();
  2308. /* Lockless fast path for the common case of empty buckets */
  2309. if (empty_bucket(hinfo, st))
  2310. continue;
  2311. spin_lock_bh(lock);
  2312. sk_nulls_for_each(sk, node, &hinfo->ehash[st->bucket].chain) {
  2313. if (seq_sk_match(seq, sk))
  2314. return sk;
  2315. }
  2316. spin_unlock_bh(lock);
  2317. }
  2318. return NULL;
  2319. }
  2320. static void *established_get_next(struct seq_file *seq, void *cur)
  2321. {
  2322. struct inet_hashinfo *hinfo = seq_file_net(seq)->ipv4.tcp_death_row.hashinfo;
  2323. struct tcp_iter_state *st = seq->private;
  2324. struct hlist_nulls_node *node;
  2325. struct sock *sk = cur;
  2326. ++st->num;
  2327. ++st->offset;
  2328. sk = sk_nulls_next(sk);
  2329. sk_nulls_for_each_from(sk, node) {
  2330. if (seq_sk_match(seq, sk))
  2331. return sk;
  2332. }
  2333. spin_unlock_bh(inet_ehash_lockp(hinfo, st->bucket));
  2334. ++st->bucket;
  2335. return established_get_first(seq);
  2336. }
  2337. static void *established_get_idx(struct seq_file *seq, loff_t pos)
  2338. {
  2339. struct tcp_iter_state *st = seq->private;
  2340. void *rc;
  2341. st->bucket = 0;
  2342. rc = established_get_first(seq);
  2343. while (rc && pos) {
  2344. rc = established_get_next(seq, rc);
  2345. --pos;
  2346. }
  2347. return rc;
  2348. }
  2349. static void *tcp_get_idx(struct seq_file *seq, loff_t pos)
  2350. {
  2351. void *rc;
  2352. struct tcp_iter_state *st = seq->private;
  2353. st->state = TCP_SEQ_STATE_LISTENING;
  2354. rc = listening_get_idx(seq, &pos);
  2355. if (!rc) {
  2356. st->state = TCP_SEQ_STATE_ESTABLISHED;
  2357. rc = established_get_idx(seq, pos);
  2358. }
  2359. return rc;
  2360. }
  2361. static void *tcp_seek_last_pos(struct seq_file *seq)
  2362. {
  2363. struct inet_hashinfo *hinfo = seq_file_net(seq)->ipv4.tcp_death_row.hashinfo;
  2364. struct tcp_iter_state *st = seq->private;
  2365. int bucket = st->bucket;
  2366. int offset = st->offset;
  2367. int orig_num = st->num;
  2368. void *rc = NULL;
  2369. switch (st->state) {
  2370. case TCP_SEQ_STATE_LISTENING:
  2371. if (st->bucket > hinfo->lhash2_mask)
  2372. break;
  2373. rc = listening_get_first(seq);
  2374. while (offset-- && rc && bucket == st->bucket)
  2375. rc = listening_get_next(seq, rc);
  2376. if (rc)
  2377. break;
  2378. st->bucket = 0;
  2379. st->state = TCP_SEQ_STATE_ESTABLISHED;
  2380. fallthrough;
  2381. case TCP_SEQ_STATE_ESTABLISHED:
  2382. if (st->bucket > hinfo->ehash_mask)
  2383. break;
  2384. rc = established_get_first(seq);
  2385. while (offset-- && rc && bucket == st->bucket)
  2386. rc = established_get_next(seq, rc);
  2387. }
  2388. st->num = orig_num;
  2389. return rc;
  2390. }
  2391. void *tcp_seq_start(struct seq_file *seq, loff_t *pos)
  2392. {
  2393. struct tcp_iter_state *st = seq->private;
  2394. void *rc;
  2395. if (*pos && *pos == st->last_pos) {
  2396. rc = tcp_seek_last_pos(seq);
  2397. if (rc)
  2398. goto out;
  2399. }
  2400. st->state = TCP_SEQ_STATE_LISTENING;
  2401. st->num = 0;
  2402. st->bucket = 0;
  2403. st->offset = 0;
  2404. rc = *pos ? tcp_get_idx(seq, *pos - 1) : SEQ_START_TOKEN;
  2405. out:
  2406. st->last_pos = *pos;
  2407. return rc;
  2408. }
  2409. EXPORT_SYMBOL(tcp_seq_start);
  2410. void *tcp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
  2411. {
  2412. struct tcp_iter_state *st = seq->private;
  2413. void *rc = NULL;
  2414. if (v == SEQ_START_TOKEN) {
  2415. rc = tcp_get_idx(seq, 0);
  2416. goto out;
  2417. }
  2418. switch (st->state) {
  2419. case TCP_SEQ_STATE_LISTENING:
  2420. rc = listening_get_next(seq, v);
  2421. if (!rc) {
  2422. st->state = TCP_SEQ_STATE_ESTABLISHED;
  2423. st->bucket = 0;
  2424. st->offset = 0;
  2425. rc = established_get_first(seq);
  2426. }
  2427. break;
  2428. case TCP_SEQ_STATE_ESTABLISHED:
  2429. rc = established_get_next(seq, v);
  2430. break;
  2431. }
  2432. out:
  2433. ++*pos;
  2434. st->last_pos = *pos;
  2435. return rc;
  2436. }
  2437. EXPORT_SYMBOL(tcp_seq_next);
  2438. void tcp_seq_stop(struct seq_file *seq, void *v)
  2439. {
  2440. struct inet_hashinfo *hinfo = seq_file_net(seq)->ipv4.tcp_death_row.hashinfo;
  2441. struct tcp_iter_state *st = seq->private;
  2442. switch (st->state) {
  2443. case TCP_SEQ_STATE_LISTENING:
  2444. if (v != SEQ_START_TOKEN)
  2445. spin_unlock(&hinfo->lhash2[st->bucket].lock);
  2446. break;
  2447. case TCP_SEQ_STATE_ESTABLISHED:
  2448. if (v)
  2449. spin_unlock_bh(inet_ehash_lockp(hinfo, st->bucket));
  2450. break;
  2451. }
  2452. }
  2453. EXPORT_SYMBOL(tcp_seq_stop);
  2454. static void get_openreq4(const struct request_sock *req,
  2455. struct seq_file *f, int i)
  2456. {
  2457. const struct inet_request_sock *ireq = inet_rsk(req);
  2458. long delta = req->rsk_timer.expires - jiffies;
  2459. seq_printf(f, "%4d: %08X:%04X %08X:%04X"
  2460. " %02X %08X:%08X %02X:%08lX %08X %5u %8d %u %d %pK",
  2461. i,
  2462. ireq->ir_loc_addr,
  2463. ireq->ir_num,
  2464. ireq->ir_rmt_addr,
  2465. ntohs(ireq->ir_rmt_port),
  2466. TCP_SYN_RECV,
  2467. 0, 0, /* could print option size, but that is af dependent. */
  2468. 1, /* timers active (only the expire timer) */
  2469. jiffies_delta_to_clock_t(delta),
  2470. req->num_timeout,
  2471. from_kuid_munged(seq_user_ns(f),
  2472. sock_i_uid(req->rsk_listener)),
  2473. 0, /* non standard timer */
  2474. 0, /* open_requests have no inode */
  2475. 0,
  2476. req);
  2477. }
  2478. static void get_tcp4_sock(struct sock *sk, struct seq_file *f, int i)
  2479. {
  2480. int timer_active;
  2481. unsigned long timer_expires;
  2482. const struct tcp_sock *tp = tcp_sk(sk);
  2483. const struct inet_connection_sock *icsk = inet_csk(sk);
  2484. const struct inet_sock *inet = inet_sk(sk);
  2485. const struct fastopen_queue *fastopenq = &icsk->icsk_accept_queue.fastopenq;
  2486. __be32 dest = inet->inet_daddr;
  2487. __be32 src = inet->inet_rcv_saddr;
  2488. __u16 destp = ntohs(inet->inet_dport);
  2489. __u16 srcp = ntohs(inet->inet_sport);
  2490. int rx_queue;
  2491. int state;
  2492. if (icsk->icsk_pending == ICSK_TIME_RETRANS ||
  2493. icsk->icsk_pending == ICSK_TIME_REO_TIMEOUT ||
  2494. icsk->icsk_pending == ICSK_TIME_LOSS_PROBE) {
  2495. timer_active = 1;
  2496. timer_expires = icsk->icsk_timeout;
  2497. } else if (icsk->icsk_pending == ICSK_TIME_PROBE0) {
  2498. timer_active = 4;
  2499. timer_expires = icsk->icsk_timeout;
  2500. } else if (timer_pending(&sk->sk_timer)) {
  2501. timer_active = 2;
  2502. timer_expires = sk->sk_timer.expires;
  2503. } else {
  2504. timer_active = 0;
  2505. timer_expires = jiffies;
  2506. }
  2507. state = inet_sk_state_load(sk);
  2508. if (state == TCP_LISTEN)
  2509. rx_queue = READ_ONCE(sk->sk_ack_backlog);
  2510. else
  2511. /* Because we don't lock the socket,
  2512. * we might find a transient negative value.
  2513. */
  2514. rx_queue = max_t(int, READ_ONCE(tp->rcv_nxt) -
  2515. READ_ONCE(tp->copied_seq), 0);
  2516. seq_printf(f, "%4d: %08X:%04X %08X:%04X %02X %08X:%08X %02X:%08lX "
  2517. "%08X %5u %8d %lu %d %pK %lu %lu %u %u %d",
  2518. i, src, srcp, dest, destp, state,
  2519. READ_ONCE(tp->write_seq) - tp->snd_una,
  2520. rx_queue,
  2521. timer_active,
  2522. jiffies_delta_to_clock_t(timer_expires - jiffies),
  2523. icsk->icsk_retransmits,
  2524. from_kuid_munged(seq_user_ns(f), sock_i_uid(sk)),
  2525. icsk->icsk_probes_out,
  2526. sock_i_ino(sk),
  2527. refcount_read(&sk->sk_refcnt), sk,
  2528. jiffies_to_clock_t(icsk->icsk_rto),
  2529. jiffies_to_clock_t(icsk->icsk_ack.ato),
  2530. (icsk->icsk_ack.quick << 1) | inet_csk_in_pingpong_mode(sk),
  2531. tcp_snd_cwnd(tp),
  2532. state == TCP_LISTEN ?
  2533. fastopenq->max_qlen :
  2534. (tcp_in_initial_slowstart(tp) ? -1 : tp->snd_ssthresh));
  2535. }
  2536. static void get_timewait4_sock(const struct inet_timewait_sock *tw,
  2537. struct seq_file *f, int i)
  2538. {
  2539. long delta = tw->tw_timer.expires - jiffies;
  2540. __be32 dest, src;
  2541. __u16 destp, srcp;
  2542. dest = tw->tw_daddr;
  2543. src = tw->tw_rcv_saddr;
  2544. destp = ntohs(tw->tw_dport);
  2545. srcp = ntohs(tw->tw_sport);
  2546. seq_printf(f, "%4d: %08X:%04X %08X:%04X"
  2547. " %02X %08X:%08X %02X:%08lX %08X %5d %8d %d %d %pK",
  2548. i, src, srcp, dest, destp, READ_ONCE(tw->tw_substate), 0, 0,
  2549. 3, jiffies_delta_to_clock_t(delta), 0, 0, 0, 0,
  2550. refcount_read(&tw->tw_refcnt), tw);
  2551. }
  2552. #define TMPSZ 150
  2553. static int tcp4_seq_show(struct seq_file *seq, void *v)
  2554. {
  2555. struct tcp_iter_state *st;
  2556. struct sock *sk = v;
  2557. seq_setwidth(seq, TMPSZ - 1);
  2558. if (v == SEQ_START_TOKEN) {
  2559. seq_puts(seq, " sl local_address rem_address st tx_queue "
  2560. "rx_queue tr tm->when retrnsmt uid timeout "
  2561. "inode");
  2562. goto out;
  2563. }
  2564. st = seq->private;
  2565. if (sk->sk_state == TCP_TIME_WAIT)
  2566. get_timewait4_sock(v, seq, st->num);
  2567. else if (sk->sk_state == TCP_NEW_SYN_RECV)
  2568. get_openreq4(v, seq, st->num);
  2569. else
  2570. get_tcp4_sock(v, seq, st->num);
  2571. out:
  2572. seq_pad(seq, '\n');
  2573. return 0;
  2574. }
  2575. #ifdef CONFIG_BPF_SYSCALL
  2576. struct bpf_tcp_iter_state {
  2577. struct tcp_iter_state state;
  2578. unsigned int cur_sk;
  2579. unsigned int end_sk;
  2580. unsigned int max_sk;
  2581. struct sock **batch;
  2582. bool st_bucket_done;
  2583. };
  2584. struct bpf_iter__tcp {
  2585. __bpf_md_ptr(struct bpf_iter_meta *, meta);
  2586. __bpf_md_ptr(struct sock_common *, sk_common);
  2587. uid_t uid __aligned(8);
  2588. };
  2589. static int tcp_prog_seq_show(struct bpf_prog *prog, struct bpf_iter_meta *meta,
  2590. struct sock_common *sk_common, uid_t uid)
  2591. {
  2592. struct bpf_iter__tcp ctx;
  2593. meta->seq_num--; /* skip SEQ_START_TOKEN */
  2594. ctx.meta = meta;
  2595. ctx.sk_common = sk_common;
  2596. ctx.uid = uid;
  2597. return bpf_iter_run_prog(prog, &ctx);
  2598. }
  2599. static void bpf_iter_tcp_put_batch(struct bpf_tcp_iter_state *iter)
  2600. {
  2601. while (iter->cur_sk < iter->end_sk)
  2602. sock_gen_put(iter->batch[iter->cur_sk++]);
  2603. }
  2604. static int bpf_iter_tcp_realloc_batch(struct bpf_tcp_iter_state *iter,
  2605. unsigned int new_batch_sz)
  2606. {
  2607. struct sock **new_batch;
  2608. new_batch = kvmalloc(sizeof(*new_batch) * new_batch_sz,
  2609. GFP_USER | __GFP_NOWARN);
  2610. if (!new_batch)
  2611. return -ENOMEM;
  2612. bpf_iter_tcp_put_batch(iter);
  2613. kvfree(iter->batch);
  2614. iter->batch = new_batch;
  2615. iter->max_sk = new_batch_sz;
  2616. return 0;
  2617. }
  2618. static unsigned int bpf_iter_tcp_listening_batch(struct seq_file *seq,
  2619. struct sock *start_sk)
  2620. {
  2621. struct inet_hashinfo *hinfo = seq_file_net(seq)->ipv4.tcp_death_row.hashinfo;
  2622. struct bpf_tcp_iter_state *iter = seq->private;
  2623. struct tcp_iter_state *st = &iter->state;
  2624. struct hlist_nulls_node *node;
  2625. unsigned int expected = 1;
  2626. struct sock *sk;
  2627. sock_hold(start_sk);
  2628. iter->batch[iter->end_sk++] = start_sk;
  2629. sk = sk_nulls_next(start_sk);
  2630. sk_nulls_for_each_from(sk, node) {
  2631. if (seq_sk_match(seq, sk)) {
  2632. if (iter->end_sk < iter->max_sk) {
  2633. sock_hold(sk);
  2634. iter->batch[iter->end_sk++] = sk;
  2635. }
  2636. expected++;
  2637. }
  2638. }
  2639. spin_unlock(&hinfo->lhash2[st->bucket].lock);
  2640. return expected;
  2641. }
  2642. static unsigned int bpf_iter_tcp_established_batch(struct seq_file *seq,
  2643. struct sock *start_sk)
  2644. {
  2645. struct inet_hashinfo *hinfo = seq_file_net(seq)->ipv4.tcp_death_row.hashinfo;
  2646. struct bpf_tcp_iter_state *iter = seq->private;
  2647. struct tcp_iter_state *st = &iter->state;
  2648. struct hlist_nulls_node *node;
  2649. unsigned int expected = 1;
  2650. struct sock *sk;
  2651. sock_hold(start_sk);
  2652. iter->batch[iter->end_sk++] = start_sk;
  2653. sk = sk_nulls_next(start_sk);
  2654. sk_nulls_for_each_from(sk, node) {
  2655. if (seq_sk_match(seq, sk)) {
  2656. if (iter->end_sk < iter->max_sk) {
  2657. sock_hold(sk);
  2658. iter->batch[iter->end_sk++] = sk;
  2659. }
  2660. expected++;
  2661. }
  2662. }
  2663. spin_unlock_bh(inet_ehash_lockp(hinfo, st->bucket));
  2664. return expected;
  2665. }
  2666. static struct sock *bpf_iter_tcp_batch(struct seq_file *seq)
  2667. {
  2668. struct inet_hashinfo *hinfo = seq_file_net(seq)->ipv4.tcp_death_row.hashinfo;
  2669. struct bpf_tcp_iter_state *iter = seq->private;
  2670. struct tcp_iter_state *st = &iter->state;
  2671. unsigned int expected;
  2672. bool resized = false;
  2673. struct sock *sk;
  2674. /* The st->bucket is done. Directly advance to the next
  2675. * bucket instead of having the tcp_seek_last_pos() to skip
  2676. * one by one in the current bucket and eventually find out
  2677. * it has to advance to the next bucket.
  2678. */
  2679. if (iter->st_bucket_done) {
  2680. st->offset = 0;
  2681. st->bucket++;
  2682. if (st->state == TCP_SEQ_STATE_LISTENING &&
  2683. st->bucket > hinfo->lhash2_mask) {
  2684. st->state = TCP_SEQ_STATE_ESTABLISHED;
  2685. st->bucket = 0;
  2686. }
  2687. }
  2688. again:
  2689. /* Get a new batch */
  2690. iter->cur_sk = 0;
  2691. iter->end_sk = 0;
  2692. iter->st_bucket_done = false;
  2693. sk = tcp_seek_last_pos(seq);
  2694. if (!sk)
  2695. return NULL; /* Done */
  2696. if (st->state == TCP_SEQ_STATE_LISTENING)
  2697. expected = bpf_iter_tcp_listening_batch(seq, sk);
  2698. else
  2699. expected = bpf_iter_tcp_established_batch(seq, sk);
  2700. if (iter->end_sk == expected) {
  2701. iter->st_bucket_done = true;
  2702. return sk;
  2703. }
  2704. if (!resized && !bpf_iter_tcp_realloc_batch(iter, expected * 3 / 2)) {
  2705. resized = true;
  2706. goto again;
  2707. }
  2708. return sk;
  2709. }
  2710. static void *bpf_iter_tcp_seq_start(struct seq_file *seq, loff_t *pos)
  2711. {
  2712. /* bpf iter does not support lseek, so it always
  2713. * continue from where it was stop()-ped.
  2714. */
  2715. if (*pos)
  2716. return bpf_iter_tcp_batch(seq);
  2717. return SEQ_START_TOKEN;
  2718. }
  2719. static void *bpf_iter_tcp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
  2720. {
  2721. struct bpf_tcp_iter_state *iter = seq->private;
  2722. struct tcp_iter_state *st = &iter->state;
  2723. struct sock *sk;
  2724. /* Whenever seq_next() is called, the iter->cur_sk is
  2725. * done with seq_show(), so advance to the next sk in
  2726. * the batch.
  2727. */
  2728. if (iter->cur_sk < iter->end_sk) {
  2729. /* Keeping st->num consistent in tcp_iter_state.
  2730. * bpf_iter_tcp does not use st->num.
  2731. * meta.seq_num is used instead.
  2732. */
  2733. st->num++;
  2734. /* Move st->offset to the next sk in the bucket such that
  2735. * the future start() will resume at st->offset in
  2736. * st->bucket. See tcp_seek_last_pos().
  2737. */
  2738. st->offset++;
  2739. sock_gen_put(iter->batch[iter->cur_sk++]);
  2740. }
  2741. if (iter->cur_sk < iter->end_sk)
  2742. sk = iter->batch[iter->cur_sk];
  2743. else
  2744. sk = bpf_iter_tcp_batch(seq);
  2745. ++*pos;
  2746. /* Keeping st->last_pos consistent in tcp_iter_state.
  2747. * bpf iter does not do lseek, so st->last_pos always equals to *pos.
  2748. */
  2749. st->last_pos = *pos;
  2750. return sk;
  2751. }
  2752. static int bpf_iter_tcp_seq_show(struct seq_file *seq, void *v)
  2753. {
  2754. struct bpf_iter_meta meta;
  2755. struct bpf_prog *prog;
  2756. struct sock *sk = v;
  2757. uid_t uid;
  2758. int ret;
  2759. if (v == SEQ_START_TOKEN)
  2760. return 0;
  2761. if (sk_fullsock(sk))
  2762. lock_sock(sk);
  2763. if (unlikely(sk_unhashed(sk))) {
  2764. ret = SEQ_SKIP;
  2765. goto unlock;
  2766. }
  2767. if (sk->sk_state == TCP_TIME_WAIT) {
  2768. uid = 0;
  2769. } else if (sk->sk_state == TCP_NEW_SYN_RECV) {
  2770. const struct request_sock *req = v;
  2771. uid = from_kuid_munged(seq_user_ns(seq),
  2772. sock_i_uid(req->rsk_listener));
  2773. } else {
  2774. uid = from_kuid_munged(seq_user_ns(seq), sock_i_uid(sk));
  2775. }
  2776. meta.seq = seq;
  2777. prog = bpf_iter_get_info(&meta, false);
  2778. ret = tcp_prog_seq_show(prog, &meta, v, uid);
  2779. unlock:
  2780. if (sk_fullsock(sk))
  2781. release_sock(sk);
  2782. return ret;
  2783. }
  2784. static void bpf_iter_tcp_seq_stop(struct seq_file *seq, void *v)
  2785. {
  2786. struct bpf_tcp_iter_state *iter = seq->private;
  2787. struct bpf_iter_meta meta;
  2788. struct bpf_prog *prog;
  2789. if (!v) {
  2790. meta.seq = seq;
  2791. prog = bpf_iter_get_info(&meta, true);
  2792. if (prog)
  2793. (void)tcp_prog_seq_show(prog, &meta, v, 0);
  2794. }
  2795. if (iter->cur_sk < iter->end_sk) {
  2796. bpf_iter_tcp_put_batch(iter);
  2797. iter->st_bucket_done = false;
  2798. }
  2799. }
  2800. static const struct seq_operations bpf_iter_tcp_seq_ops = {
  2801. .show = bpf_iter_tcp_seq_show,
  2802. .start = bpf_iter_tcp_seq_start,
  2803. .next = bpf_iter_tcp_seq_next,
  2804. .stop = bpf_iter_tcp_seq_stop,
  2805. };
  2806. #endif
  2807. static unsigned short seq_file_family(const struct seq_file *seq)
  2808. {
  2809. const struct tcp_seq_afinfo *afinfo;
  2810. #ifdef CONFIG_BPF_SYSCALL
  2811. /* Iterated from bpf_iter. Let the bpf prog to filter instead. */
  2812. if (seq->op == &bpf_iter_tcp_seq_ops)
  2813. return AF_UNSPEC;
  2814. #endif
  2815. /* Iterated from proc fs */
  2816. afinfo = pde_data(file_inode(seq->file));
  2817. return afinfo->family;
  2818. }
  2819. static const struct seq_operations tcp4_seq_ops = {
  2820. .show = tcp4_seq_show,
  2821. .start = tcp_seq_start,
  2822. .next = tcp_seq_next,
  2823. .stop = tcp_seq_stop,
  2824. };
  2825. static struct tcp_seq_afinfo tcp4_seq_afinfo = {
  2826. .family = AF_INET,
  2827. };
  2828. static int __net_init tcp4_proc_init_net(struct net *net)
  2829. {
  2830. if (!proc_create_net_data("tcp", 0444, net->proc_net, &tcp4_seq_ops,
  2831. sizeof(struct tcp_iter_state), &tcp4_seq_afinfo))
  2832. return -ENOMEM;
  2833. return 0;
  2834. }
  2835. static void __net_exit tcp4_proc_exit_net(struct net *net)
  2836. {
  2837. remove_proc_entry("tcp", net->proc_net);
  2838. }
  2839. static struct pernet_operations tcp4_net_ops = {
  2840. .init = tcp4_proc_init_net,
  2841. .exit = tcp4_proc_exit_net,
  2842. };
  2843. int __init tcp4_proc_init(void)
  2844. {
  2845. return register_pernet_subsys(&tcp4_net_ops);
  2846. }
  2847. void tcp4_proc_exit(void)
  2848. {
  2849. unregister_pernet_subsys(&tcp4_net_ops);
  2850. }
  2851. #endif /* CONFIG_PROC_FS */
  2852. /* @wake is one when sk_stream_write_space() calls us.
  2853. * This sends EPOLLOUT only if notsent_bytes is half the limit.
  2854. * This mimics the strategy used in sock_def_write_space().
  2855. */
  2856. bool tcp_stream_memory_free(const struct sock *sk, int wake)
  2857. {
  2858. const struct tcp_sock *tp = tcp_sk(sk);
  2859. u32 notsent_bytes = READ_ONCE(tp->write_seq) -
  2860. READ_ONCE(tp->snd_nxt);
  2861. return (notsent_bytes << wake) < tcp_notsent_lowat(tp);
  2862. }
  2863. EXPORT_SYMBOL(tcp_stream_memory_free);
  2864. struct proto tcp_prot = {
  2865. .name = "TCP",
  2866. .owner = THIS_MODULE,
  2867. .close = tcp_close,
  2868. .pre_connect = tcp_v4_pre_connect,
  2869. .connect = tcp_v4_connect,
  2870. .disconnect = tcp_disconnect,
  2871. .accept = inet_csk_accept,
  2872. .ioctl = tcp_ioctl,
  2873. .init = tcp_v4_init_sock,
  2874. .destroy = tcp_v4_destroy_sock,
  2875. .shutdown = tcp_shutdown,
  2876. .setsockopt = tcp_setsockopt,
  2877. .getsockopt = tcp_getsockopt,
  2878. .bpf_bypass_getsockopt = tcp_bpf_bypass_getsockopt,
  2879. .keepalive = tcp_set_keepalive,
  2880. .recvmsg = tcp_recvmsg,
  2881. .sendmsg = tcp_sendmsg,
  2882. .splice_eof = tcp_splice_eof,
  2883. .backlog_rcv = tcp_v4_do_rcv,
  2884. .release_cb = tcp_release_cb,
  2885. .hash = inet_hash,
  2886. .unhash = inet_unhash,
  2887. .get_port = inet_csk_get_port,
  2888. .put_port = inet_put_port,
  2889. #ifdef CONFIG_BPF_SYSCALL
  2890. .psock_update_sk_prot = tcp_bpf_update_proto,
  2891. #endif
  2892. .enter_memory_pressure = tcp_enter_memory_pressure,
  2893. .leave_memory_pressure = tcp_leave_memory_pressure,
  2894. .stream_memory_free = tcp_stream_memory_free,
  2895. .sockets_allocated = &tcp_sockets_allocated,
  2896. .orphan_count = &tcp_orphan_count,
  2897. .memory_allocated = &tcp_memory_allocated,
  2898. .per_cpu_fw_alloc = &tcp_memory_per_cpu_fw_alloc,
  2899. .memory_pressure = &tcp_memory_pressure,
  2900. .sysctl_mem = sysctl_tcp_mem,
  2901. .sysctl_wmem_offset = offsetof(struct net, ipv4.sysctl_tcp_wmem),
  2902. .sysctl_rmem_offset = offsetof(struct net, ipv4.sysctl_tcp_rmem),
  2903. .max_header = MAX_TCP_HEADER,
  2904. .obj_size = sizeof(struct tcp_sock),
  2905. .slab_flags = SLAB_TYPESAFE_BY_RCU,
  2906. .twsk_prot = &tcp_timewait_sock_ops,
  2907. .rsk_prot = &tcp_request_sock_ops,
  2908. .h.hashinfo = NULL,
  2909. .no_autobind = true,
  2910. .diag_destroy = tcp_abort,
  2911. };
  2912. EXPORT_SYMBOL(tcp_prot);
  2913. static void __net_exit tcp_sk_exit(struct net *net)
  2914. {
  2915. if (net->ipv4.tcp_congestion_control)
  2916. bpf_module_put(net->ipv4.tcp_congestion_control,
  2917. net->ipv4.tcp_congestion_control->owner);
  2918. }
  2919. static void __net_init tcp_set_hashinfo(struct net *net)
  2920. {
  2921. struct inet_hashinfo *hinfo;
  2922. unsigned int ehash_entries;
  2923. struct net *old_net;
  2924. if (net_eq(net, &init_net))
  2925. goto fallback;
  2926. old_net = current->nsproxy->net_ns;
  2927. ehash_entries = READ_ONCE(old_net->ipv4.sysctl_tcp_child_ehash_entries);
  2928. if (!ehash_entries)
  2929. goto fallback;
  2930. ehash_entries = roundup_pow_of_two(ehash_entries);
  2931. hinfo = inet_pernet_hashinfo_alloc(&tcp_hashinfo, ehash_entries);
  2932. if (!hinfo) {
  2933. pr_warn("Failed to allocate TCP ehash (entries: %u) "
  2934. "for a netns, fallback to the global one\n",
  2935. ehash_entries);
  2936. fallback:
  2937. hinfo = &tcp_hashinfo;
  2938. ehash_entries = tcp_hashinfo.ehash_mask + 1;
  2939. }
  2940. net->ipv4.tcp_death_row.hashinfo = hinfo;
  2941. net->ipv4.tcp_death_row.sysctl_max_tw_buckets = ehash_entries / 2;
  2942. net->ipv4.sysctl_max_syn_backlog = max(128U, ehash_entries / 128);
  2943. }
  2944. static int __net_init tcp_sk_init(struct net *net)
  2945. {
  2946. net->ipv4.sysctl_tcp_ecn = 2;
  2947. net->ipv4.sysctl_tcp_ecn_fallback = 1;
  2948. net->ipv4.sysctl_tcp_base_mss = TCP_BASE_MSS;
  2949. net->ipv4.sysctl_tcp_min_snd_mss = TCP_MIN_SND_MSS;
  2950. net->ipv4.sysctl_tcp_probe_threshold = TCP_PROBE_THRESHOLD;
  2951. net->ipv4.sysctl_tcp_probe_interval = TCP_PROBE_INTERVAL;
  2952. net->ipv4.sysctl_tcp_mtu_probe_floor = TCP_MIN_SND_MSS;
  2953. net->ipv4.sysctl_tcp_keepalive_time = TCP_KEEPALIVE_TIME;
  2954. net->ipv4.sysctl_tcp_keepalive_probes = TCP_KEEPALIVE_PROBES;
  2955. net->ipv4.sysctl_tcp_keepalive_intvl = TCP_KEEPALIVE_INTVL;
  2956. net->ipv4.sysctl_tcp_syn_retries = TCP_SYN_RETRIES;
  2957. net->ipv4.sysctl_tcp_synack_retries = TCP_SYNACK_RETRIES;
  2958. net->ipv4.sysctl_tcp_syncookies = 1;
  2959. net->ipv4.sysctl_tcp_reordering = TCP_FASTRETRANS_THRESH;
  2960. net->ipv4.sysctl_tcp_retries1 = TCP_RETR1;
  2961. net->ipv4.sysctl_tcp_retries2 = TCP_RETR2;
  2962. net->ipv4.sysctl_tcp_orphan_retries = 0;
  2963. net->ipv4.sysctl_tcp_fin_timeout = TCP_FIN_TIMEOUT;
  2964. net->ipv4.sysctl_tcp_notsent_lowat = UINT_MAX;
  2965. net->ipv4.sysctl_tcp_tw_reuse = 2;
  2966. net->ipv4.sysctl_tcp_no_ssthresh_metrics_save = 1;
  2967. refcount_set(&net->ipv4.tcp_death_row.tw_refcount, 1);
  2968. tcp_set_hashinfo(net);
  2969. net->ipv4.sysctl_tcp_sack = 1;
  2970. net->ipv4.sysctl_tcp_window_scaling = 1;
  2971. net->ipv4.sysctl_tcp_timestamps = 1;
  2972. net->ipv4.sysctl_tcp_early_retrans = 3;
  2973. net->ipv4.sysctl_tcp_recovery = TCP_RACK_LOSS_DETECTION;
  2974. net->ipv4.sysctl_tcp_slow_start_after_idle = 1; /* By default, RFC2861 behavior. */
  2975. net->ipv4.sysctl_tcp_retrans_collapse = 1;
  2976. net->ipv4.sysctl_tcp_max_reordering = 300;
  2977. net->ipv4.sysctl_tcp_dsack = 1;
  2978. net->ipv4.sysctl_tcp_app_win = 31;
  2979. net->ipv4.sysctl_tcp_adv_win_scale = 1;
  2980. net->ipv4.sysctl_tcp_frto = 2;
  2981. net->ipv4.sysctl_tcp_moderate_rcvbuf = 1;
  2982. /* This limits the percentage of the congestion window which we
  2983. * will allow a single TSO frame to consume. Building TSO frames
  2984. * which are too large can cause TCP streams to be bursty.
  2985. */
  2986. net->ipv4.sysctl_tcp_tso_win_divisor = 3;
  2987. /* Default TSQ limit of 16 TSO segments */
  2988. net->ipv4.sysctl_tcp_limit_output_bytes = 16 * 65536;
  2989. /* rfc5961 challenge ack rate limiting, per net-ns, disabled by default. */
  2990. net->ipv4.sysctl_tcp_challenge_ack_limit = INT_MAX;
  2991. net->ipv4.sysctl_tcp_min_tso_segs = 2;
  2992. net->ipv4.sysctl_tcp_tso_rtt_log = 9; /* 2^9 = 512 usec */
  2993. net->ipv4.sysctl_tcp_min_rtt_wlen = 300;
  2994. net->ipv4.sysctl_tcp_autocorking = 1;
  2995. net->ipv4.sysctl_tcp_invalid_ratelimit = HZ/2;
  2996. net->ipv4.sysctl_tcp_pacing_ss_ratio = 200;
  2997. net->ipv4.sysctl_tcp_pacing_ca_ratio = 120;
  2998. if (net != &init_net) {
  2999. memcpy(net->ipv4.sysctl_tcp_rmem,
  3000. init_net.ipv4.sysctl_tcp_rmem,
  3001. sizeof(init_net.ipv4.sysctl_tcp_rmem));
  3002. memcpy(net->ipv4.sysctl_tcp_wmem,
  3003. init_net.ipv4.sysctl_tcp_wmem,
  3004. sizeof(init_net.ipv4.sysctl_tcp_wmem));
  3005. }
  3006. net->ipv4.sysctl_tcp_comp_sack_delay_ns = NSEC_PER_MSEC;
  3007. net->ipv4.sysctl_tcp_comp_sack_slack_ns = 100 * NSEC_PER_USEC;
  3008. net->ipv4.sysctl_tcp_comp_sack_nr = 44;
  3009. net->ipv4.sysctl_tcp_backlog_ack_defer = 1;
  3010. net->ipv4.sysctl_tcp_fastopen = TFO_CLIENT_ENABLE;
  3011. net->ipv4.sysctl_tcp_fastopen_blackhole_timeout = 0;
  3012. atomic_set(&net->ipv4.tfo_active_disable_times, 0);
  3013. /* Set default values for PLB */
  3014. net->ipv4.sysctl_tcp_plb_enabled = 0; /* Disabled by default */
  3015. net->ipv4.sysctl_tcp_plb_idle_rehash_rounds = 3;
  3016. net->ipv4.sysctl_tcp_plb_rehash_rounds = 12;
  3017. net->ipv4.sysctl_tcp_plb_suspend_rto_sec = 60;
  3018. /* Default congestion threshold for PLB to mark a round is 50% */
  3019. net->ipv4.sysctl_tcp_plb_cong_thresh = (1 << TCP_PLB_SCALE) / 2;
  3020. /* Reno is always built in */
  3021. if (!net_eq(net, &init_net) &&
  3022. bpf_try_module_get(init_net.ipv4.tcp_congestion_control,
  3023. init_net.ipv4.tcp_congestion_control->owner))
  3024. net->ipv4.tcp_congestion_control = init_net.ipv4.tcp_congestion_control;
  3025. else
  3026. net->ipv4.tcp_congestion_control = &tcp_reno;
  3027. net->ipv4.sysctl_tcp_syn_linear_timeouts = 4;
  3028. net->ipv4.sysctl_tcp_shrink_window = 0;
  3029. net->ipv4.sysctl_tcp_pingpong_thresh = 1;
  3030. net->ipv4.sysctl_tcp_rto_min_us = jiffies_to_usecs(TCP_RTO_MIN);
  3031. return 0;
  3032. }
  3033. static void __net_exit tcp_sk_exit_batch(struct list_head *net_exit_list)
  3034. {
  3035. struct net *net;
  3036. /* make sure concurrent calls to tcp_sk_exit_batch from net_cleanup_work
  3037. * and failed setup_net error unwinding path are serialized.
  3038. *
  3039. * tcp_twsk_purge() handles twsk in any dead netns, not just those in
  3040. * net_exit_list, the thread that dismantles a particular twsk must
  3041. * do so without other thread progressing to refcount_dec_and_test() of
  3042. * tcp_death_row.tw_refcount.
  3043. */
  3044. mutex_lock(&tcp_exit_batch_mutex);
  3045. tcp_twsk_purge(net_exit_list);
  3046. list_for_each_entry(net, net_exit_list, exit_list) {
  3047. inet_pernet_hashinfo_free(net->ipv4.tcp_death_row.hashinfo);
  3048. WARN_ON_ONCE(!refcount_dec_and_test(&net->ipv4.tcp_death_row.tw_refcount));
  3049. tcp_fastopen_ctx_destroy(net);
  3050. }
  3051. mutex_unlock(&tcp_exit_batch_mutex);
  3052. }
  3053. static struct pernet_operations __net_initdata tcp_sk_ops = {
  3054. .init = tcp_sk_init,
  3055. .exit = tcp_sk_exit,
  3056. .exit_batch = tcp_sk_exit_batch,
  3057. };
  3058. #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
  3059. DEFINE_BPF_ITER_FUNC(tcp, struct bpf_iter_meta *meta,
  3060. struct sock_common *sk_common, uid_t uid)
  3061. #define INIT_BATCH_SZ 16
  3062. static int bpf_iter_init_tcp(void *priv_data, struct bpf_iter_aux_info *aux)
  3063. {
  3064. struct bpf_tcp_iter_state *iter = priv_data;
  3065. int err;
  3066. err = bpf_iter_init_seq_net(priv_data, aux);
  3067. if (err)
  3068. return err;
  3069. err = bpf_iter_tcp_realloc_batch(iter, INIT_BATCH_SZ);
  3070. if (err) {
  3071. bpf_iter_fini_seq_net(priv_data);
  3072. return err;
  3073. }
  3074. return 0;
  3075. }
  3076. static void bpf_iter_fini_tcp(void *priv_data)
  3077. {
  3078. struct bpf_tcp_iter_state *iter = priv_data;
  3079. bpf_iter_fini_seq_net(priv_data);
  3080. kvfree(iter->batch);
  3081. }
  3082. static const struct bpf_iter_seq_info tcp_seq_info = {
  3083. .seq_ops = &bpf_iter_tcp_seq_ops,
  3084. .init_seq_private = bpf_iter_init_tcp,
  3085. .fini_seq_private = bpf_iter_fini_tcp,
  3086. .seq_priv_size = sizeof(struct bpf_tcp_iter_state),
  3087. };
  3088. static const struct bpf_func_proto *
  3089. bpf_iter_tcp_get_func_proto(enum bpf_func_id func_id,
  3090. const struct bpf_prog *prog)
  3091. {
  3092. switch (func_id) {
  3093. case BPF_FUNC_setsockopt:
  3094. return &bpf_sk_setsockopt_proto;
  3095. case BPF_FUNC_getsockopt:
  3096. return &bpf_sk_getsockopt_proto;
  3097. default:
  3098. return NULL;
  3099. }
  3100. }
  3101. static struct bpf_iter_reg tcp_reg_info = {
  3102. .target = "tcp",
  3103. .ctx_arg_info_size = 1,
  3104. .ctx_arg_info = {
  3105. { offsetof(struct bpf_iter__tcp, sk_common),
  3106. PTR_TO_BTF_ID_OR_NULL | PTR_TRUSTED },
  3107. },
  3108. .get_func_proto = bpf_iter_tcp_get_func_proto,
  3109. .seq_info = &tcp_seq_info,
  3110. };
  3111. static void __init bpf_iter_register(void)
  3112. {
  3113. tcp_reg_info.ctx_arg_info[0].btf_id = btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON];
  3114. if (bpf_iter_reg_target(&tcp_reg_info))
  3115. pr_warn("Warning: could not register bpf iterator tcp\n");
  3116. }
  3117. #endif
  3118. void __init tcp_v4_init(void)
  3119. {
  3120. int cpu, res;
  3121. for_each_possible_cpu(cpu) {
  3122. struct sock *sk;
  3123. res = inet_ctl_sock_create(&sk, PF_INET, SOCK_RAW,
  3124. IPPROTO_TCP, &init_net);
  3125. if (res)
  3126. panic("Failed to create the TCP control socket.\n");
  3127. sock_set_flag(sk, SOCK_USE_WRITE_QUEUE);
  3128. /* Please enforce IP_DF and IPID==0 for RST and
  3129. * ACK sent in SYN-RECV and TIME-WAIT state.
  3130. */
  3131. inet_sk(sk)->pmtudisc = IP_PMTUDISC_DO;
  3132. sk->sk_clockid = CLOCK_MONOTONIC;
  3133. per_cpu(ipv4_tcp_sk.sock, cpu) = sk;
  3134. }
  3135. if (register_pernet_subsys(&tcp_sk_ops))
  3136. panic("Failed to create the TCP control socket.\n");
  3137. #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
  3138. bpf_iter_register();
  3139. #endif
  3140. }