tcp_ipv4.c 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645
  1. /*
  2. * INET An implementation of the TCP/IP protocol suite for the LINUX
  3. * operating system. INET is implemented using the BSD Socket
  4. * interface as the means of communication with the user level.
  5. *
  6. * Implementation of the Transmission Control Protocol(TCP).
  7. *
  8. * IPv4 specific functions
  9. *
  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. * This program is free software; you can redistribute it and/or
  19. * modify it under the terms of the GNU General Public License
  20. * as published by the Free Software Foundation; either version
  21. * 2 of the License, or (at your option) any later version.
  22. */
  23. /*
  24. * Changes:
  25. * David S. Miller : New socket lookup architecture.
  26. * This code is dedicated to John Dyson.
  27. * David S. Miller : Change semantics of established hash,
  28. * half is devoted to TIME_WAIT sockets
  29. * and the rest go in the other half.
  30. * Andi Kleen : Add support for syncookies and fixed
  31. * some bugs: ip options weren't passed to
  32. * the TCP layer, missed a check for an
  33. * ACK bit.
  34. * Andi Kleen : Implemented fast path mtu discovery.
  35. * Fixed many serious bugs in the
  36. * request_sock handling and moved
  37. * most of it into the af independent code.
  38. * Added tail drop and some other bugfixes.
  39. * Added new listen semantics.
  40. * Mike McLagan : Routing by source
  41. * Juan Jose Ciarlante: ip_dynaddr bits
  42. * Andi Kleen: various fixes.
  43. * Vitaly E. Lavrov : Transparent proxy revived after year
  44. * coma.
  45. * Andi Kleen : Fix new listen.
  46. * Andi Kleen : Fix accept error reporting.
  47. * YOSHIFUJI Hideaki @USAGI and: Support IPV6_V6ONLY socket option, which
  48. * Alexey Kuznetsov allow both IPv4 and IPv6 sockets to bind
  49. * a single port at the same time.
  50. */
  51. #define pr_fmt(fmt) "TCP: " fmt
  52. #include <linux/bottom_half.h>
  53. #include <linux/types.h>
  54. #include <linux/fcntl.h>
  55. #include <linux/module.h>
  56. #include <linux/random.h>
  57. #include <linux/cache.h>
  58. #include <linux/jhash.h>
  59. #include <linux/init.h>
  60. #include <linux/times.h>
  61. #include <linux/slab.h>
  62. #include <net/net_namespace.h>
  63. #include <net/icmp.h>
  64. #include <net/inet_hashtables.h>
  65. #include <net/tcp.h>
  66. #include <net/transp_v6.h>
  67. #include <net/ipv6.h>
  68. #include <net/inet_common.h>
  69. #include <net/timewait_sock.h>
  70. #include <net/xfrm.h>
  71. #include <net/secure_seq.h>
  72. #include <net/busy_poll.h>
  73. #include <linux/inet.h>
  74. #include <linux/ipv6.h>
  75. #include <linux/stddef.h>
  76. #include <linux/proc_fs.h>
  77. #include <linux/seq_file.h>
  78. #include <linux/inetdevice.h>
  79. #include <crypto/hash.h>
  80. #include <linux/scatterlist.h>
  81. #include <trace/events/tcp.h>
  82. #ifdef CONFIG_TCP_MD5SIG
  83. static int tcp_v4_md5_hash_hdr(char *md5_hash, const struct tcp_md5sig_key *key,
  84. __be32 daddr, __be32 saddr, const struct tcphdr *th);
  85. #endif
  86. struct inet_hashinfo tcp_hashinfo;
  87. EXPORT_SYMBOL(tcp_hashinfo);
  88. static u32 tcp_v4_init_seq(const struct sk_buff *skb)
  89. {
  90. return secure_tcp_seq(ip_hdr(skb)->daddr,
  91. ip_hdr(skb)->saddr,
  92. tcp_hdr(skb)->dest,
  93. tcp_hdr(skb)->source);
  94. }
  95. static u32 tcp_v4_init_ts_off(const struct net *net, const struct sk_buff *skb)
  96. {
  97. return secure_tcp_ts_off(net, ip_hdr(skb)->daddr, ip_hdr(skb)->saddr);
  98. }
  99. int tcp_twsk_unique(struct sock *sk, struct sock *sktw, void *twp)
  100. {
  101. const struct inet_timewait_sock *tw = inet_twsk(sktw);
  102. const struct tcp_timewait_sock *tcptw = tcp_twsk(sktw);
  103. struct tcp_sock *tp = tcp_sk(sk);
  104. int reuse = sock_net(sk)->ipv4.sysctl_tcp_tw_reuse;
  105. if (reuse == 2) {
  106. /* Still does not detect *everything* that goes through
  107. * lo, since we require a loopback src or dst address
  108. * or direct binding to 'lo' interface.
  109. */
  110. bool loopback = false;
  111. if (tw->tw_bound_dev_if == LOOPBACK_IFINDEX)
  112. loopback = true;
  113. #if IS_ENABLED(CONFIG_IPV6)
  114. if (tw->tw_family == AF_INET6) {
  115. if (ipv6_addr_loopback(&tw->tw_v6_daddr) ||
  116. (ipv6_addr_v4mapped(&tw->tw_v6_daddr) &&
  117. (tw->tw_v6_daddr.s6_addr[12] == 127)) ||
  118. ipv6_addr_loopback(&tw->tw_v6_rcv_saddr) ||
  119. (ipv6_addr_v4mapped(&tw->tw_v6_rcv_saddr) &&
  120. (tw->tw_v6_rcv_saddr.s6_addr[12] == 127)))
  121. loopback = true;
  122. } else
  123. #endif
  124. {
  125. if (ipv4_is_loopback(tw->tw_daddr) ||
  126. ipv4_is_loopback(tw->tw_rcv_saddr))
  127. loopback = true;
  128. }
  129. if (!loopback)
  130. reuse = 0;
  131. }
  132. /* With PAWS, it is safe from the viewpoint
  133. of data integrity. Even without PAWS it is safe provided sequence
  134. spaces do not overlap i.e. at data rates <= 80Mbit/sec.
  135. Actually, the idea is close to VJ's one, only timestamp cache is
  136. held not per host, but per port pair and TW bucket is used as state
  137. holder.
  138. If TW bucket has been already destroyed we fall back to VJ's scheme
  139. and use initial timestamp retrieved from peer table.
  140. */
  141. if (tcptw->tw_ts_recent_stamp &&
  142. (!twp || (reuse && time_after32(ktime_get_seconds(),
  143. tcptw->tw_ts_recent_stamp)))) {
  144. /* In case of repair and re-using TIME-WAIT sockets we still
  145. * want to be sure that it is safe as above but honor the
  146. * sequence numbers and time stamps set as part of the repair
  147. * process.
  148. *
  149. * Without this check re-using a TIME-WAIT socket with TCP
  150. * repair would accumulate a -1 on the repair assigned
  151. * sequence number. The first time it is reused the sequence
  152. * is -1, the second time -2, etc. This fixes that issue
  153. * without appearing to create any others.
  154. */
  155. if (likely(!tp->repair)) {
  156. u32 seq = tcptw->tw_snd_nxt + 65535 + 2;
  157. if (!seq)
  158. seq = 1;
  159. WRITE_ONCE(tp->write_seq, seq);
  160. tp->rx_opt.ts_recent = tcptw->tw_ts_recent;
  161. tp->rx_opt.ts_recent_stamp = tcptw->tw_ts_recent_stamp;
  162. }
  163. sock_hold(sktw);
  164. return 1;
  165. }
  166. return 0;
  167. }
  168. EXPORT_SYMBOL_GPL(tcp_twsk_unique);
  169. static int tcp_v4_pre_connect(struct sock *sk, struct sockaddr *uaddr,
  170. int addr_len)
  171. {
  172. /* This check is replicated from tcp_v4_connect() and intended to
  173. * prevent BPF program called below from accessing bytes that are out
  174. * of the bound specified by user in addr_len.
  175. */
  176. if (addr_len < sizeof(struct sockaddr_in))
  177. return -EINVAL;
  178. sock_owned_by_me(sk);
  179. return BPF_CGROUP_RUN_PROG_INET4_CONNECT(sk, uaddr);
  180. }
  181. /* This will initiate an outgoing connection. */
  182. int tcp_v4_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
  183. {
  184. struct sockaddr_in *usin = (struct sockaddr_in *)uaddr;
  185. struct inet_sock *inet = inet_sk(sk);
  186. struct tcp_sock *tp = tcp_sk(sk);
  187. __be16 orig_sport, orig_dport;
  188. __be32 daddr, nexthop;
  189. struct flowi4 *fl4;
  190. struct rtable *rt;
  191. int err;
  192. struct ip_options_rcu *inet_opt;
  193. struct inet_timewait_death_row *tcp_death_row = &sock_net(sk)->ipv4.tcp_death_row;
  194. if (addr_len < sizeof(struct sockaddr_in))
  195. return -EINVAL;
  196. if (usin->sin_family != AF_INET)
  197. return -EAFNOSUPPORT;
  198. nexthop = daddr = usin->sin_addr.s_addr;
  199. inet_opt = rcu_dereference_protected(inet->inet_opt,
  200. lockdep_sock_is_held(sk));
  201. if (inet_opt && inet_opt->opt.srr) {
  202. if (!daddr)
  203. return -EINVAL;
  204. nexthop = inet_opt->opt.faddr;
  205. }
  206. orig_sport = inet->inet_sport;
  207. orig_dport = usin->sin_port;
  208. fl4 = &inet->cork.fl.u.ip4;
  209. rt = ip_route_connect(fl4, nexthop, inet->inet_saddr,
  210. RT_CONN_FLAGS(sk), sk->sk_bound_dev_if,
  211. IPPROTO_TCP,
  212. orig_sport, orig_dport, sk);
  213. if (IS_ERR(rt)) {
  214. err = PTR_ERR(rt);
  215. if (err == -ENETUNREACH)
  216. IP_INC_STATS(sock_net(sk), IPSTATS_MIB_OUTNOROUTES);
  217. return err;
  218. }
  219. if (rt->rt_flags & (RTCF_MULTICAST | RTCF_BROADCAST)) {
  220. ip_rt_put(rt);
  221. return -ENETUNREACH;
  222. }
  223. if (!inet_opt || !inet_opt->opt.srr)
  224. daddr = fl4->daddr;
  225. if (!inet->inet_saddr)
  226. inet->inet_saddr = fl4->saddr;
  227. sk_rcv_saddr_set(sk, inet->inet_saddr);
  228. if (tp->rx_opt.ts_recent_stamp && inet->inet_daddr != daddr) {
  229. /* Reset inherited state */
  230. tp->rx_opt.ts_recent = 0;
  231. tp->rx_opt.ts_recent_stamp = 0;
  232. if (likely(!tp->repair))
  233. WRITE_ONCE(tp->write_seq, 0);
  234. }
  235. inet->inet_dport = usin->sin_port;
  236. sk_daddr_set(sk, daddr);
  237. inet_csk(sk)->icsk_ext_hdr_len = 0;
  238. if (inet_opt)
  239. inet_csk(sk)->icsk_ext_hdr_len = inet_opt->opt.optlen;
  240. tp->rx_opt.mss_clamp = TCP_MSS_DEFAULT;
  241. /* Socket identity is still unknown (sport may be zero).
  242. * However we set state to SYN-SENT and not releasing socket
  243. * lock select source port, enter ourselves into the hash tables and
  244. * complete initialization after this.
  245. */
  246. tcp_set_state(sk, TCP_SYN_SENT);
  247. err = inet_hash_connect(tcp_death_row, sk);
  248. if (err)
  249. goto failure;
  250. sk_set_txhash(sk);
  251. rt = ip_route_newports(fl4, rt, orig_sport, orig_dport,
  252. inet->inet_sport, inet->inet_dport, sk);
  253. if (IS_ERR(rt)) {
  254. err = PTR_ERR(rt);
  255. rt = NULL;
  256. goto failure;
  257. }
  258. /* OK, now commit destination to socket. */
  259. sk->sk_gso_type = SKB_GSO_TCPV4;
  260. sk_setup_caps(sk, &rt->dst);
  261. rt = NULL;
  262. if (likely(!tp->repair)) {
  263. if (!tp->write_seq)
  264. WRITE_ONCE(tp->write_seq,
  265. secure_tcp_seq(inet->inet_saddr,
  266. inet->inet_daddr,
  267. inet->inet_sport,
  268. usin->sin_port));
  269. tp->tsoffset = secure_tcp_ts_off(sock_net(sk),
  270. inet->inet_saddr,
  271. inet->inet_daddr);
  272. }
  273. inet->inet_id = prandom_u32();
  274. if (tcp_fastopen_defer_connect(sk, &err))
  275. return err;
  276. if (err)
  277. goto failure;
  278. err = tcp_connect(sk);
  279. if (err)
  280. goto failure;
  281. return 0;
  282. failure:
  283. /*
  284. * This unhashes the socket and releases the local port,
  285. * if necessary.
  286. */
  287. tcp_set_state(sk, TCP_CLOSE);
  288. ip_rt_put(rt);
  289. sk->sk_route_caps = 0;
  290. inet->inet_dport = 0;
  291. return err;
  292. }
  293. EXPORT_SYMBOL(tcp_v4_connect);
  294. /*
  295. * This routine reacts to ICMP_FRAG_NEEDED mtu indications as defined in RFC1191.
  296. * It can be called through tcp_release_cb() if socket was owned by user
  297. * at the time tcp_v4_err() was called to handle ICMP message.
  298. */
  299. void tcp_v4_mtu_reduced(struct sock *sk)
  300. {
  301. struct inet_sock *inet = inet_sk(sk);
  302. struct dst_entry *dst;
  303. u32 mtu;
  304. if ((1 << sk->sk_state) & (TCPF_LISTEN | TCPF_CLOSE))
  305. return;
  306. mtu = tcp_sk(sk)->mtu_info;
  307. dst = inet_csk_update_pmtu(sk, mtu);
  308. if (!dst)
  309. return;
  310. /* Something is about to be wrong... Remember soft error
  311. * for the case, if this connection will not able to recover.
  312. */
  313. if (mtu < dst_mtu(dst) && ip_dont_fragment(sk, dst))
  314. sk->sk_err_soft = EMSGSIZE;
  315. mtu = dst_mtu(dst);
  316. if (inet->pmtudisc != IP_PMTUDISC_DONT &&
  317. ip_sk_accept_pmtu(sk) &&
  318. inet_csk(sk)->icsk_pmtu_cookie > mtu) {
  319. tcp_sync_mss(sk, mtu);
  320. /* Resend the TCP packet because it's
  321. * clear that the old packet has been
  322. * dropped. This is the new "fast" path mtu
  323. * discovery.
  324. */
  325. tcp_simple_retransmit(sk);
  326. } /* else let the usual retransmit timer handle it */
  327. }
  328. EXPORT_SYMBOL(tcp_v4_mtu_reduced);
  329. static void do_redirect(struct sk_buff *skb, struct sock *sk)
  330. {
  331. struct dst_entry *dst = __sk_dst_check(sk, 0);
  332. if (dst)
  333. dst->ops->redirect(dst, sk, skb);
  334. }
  335. /* handle ICMP messages on TCP_NEW_SYN_RECV request sockets */
  336. void tcp_req_err(struct sock *sk, u32 seq, bool abort)
  337. {
  338. struct request_sock *req = inet_reqsk(sk);
  339. struct net *net = sock_net(sk);
  340. /* ICMPs are not backlogged, hence we cannot get
  341. * an established socket here.
  342. */
  343. if (seq != tcp_rsk(req)->snt_isn) {
  344. __NET_INC_STATS(net, LINUX_MIB_OUTOFWINDOWICMPS);
  345. } else if (abort) {
  346. /*
  347. * Still in SYN_RECV, just remove it silently.
  348. * There is no good way to pass the error to the newly
  349. * created socket, and POSIX does not want network
  350. * errors returned from accept().
  351. */
  352. inet_csk_reqsk_queue_drop(req->rsk_listener, req);
  353. tcp_listendrop(req->rsk_listener);
  354. }
  355. reqsk_put(req);
  356. }
  357. EXPORT_SYMBOL(tcp_req_err);
  358. /*
  359. * This routine is called by the ICMP module when it gets some
  360. * sort of error condition. If err < 0 then the socket should
  361. * be closed and the error returned to the user. If err > 0
  362. * it's just the icmp type << 8 | icmp code. After adjustment
  363. * header points to the first 8 bytes of the tcp header. We need
  364. * to find the appropriate port.
  365. *
  366. * The locking strategy used here is very "optimistic". When
  367. * someone else accesses the socket the ICMP is just dropped
  368. * and for some paths there is no check at all.
  369. * A more general error queue to queue errors for later handling
  370. * is probably better.
  371. *
  372. */
  373. void tcp_v4_err(struct sk_buff *icmp_skb, u32 info)
  374. {
  375. const struct iphdr *iph = (const struct iphdr *)icmp_skb->data;
  376. struct tcphdr *th = (struct tcphdr *)(icmp_skb->data + (iph->ihl << 2));
  377. struct inet_connection_sock *icsk;
  378. struct tcp_sock *tp;
  379. struct inet_sock *inet;
  380. const int type = icmp_hdr(icmp_skb)->type;
  381. const int code = icmp_hdr(icmp_skb)->code;
  382. struct sock *sk;
  383. struct sk_buff *skb;
  384. struct request_sock *fastopen;
  385. u32 seq, snd_una;
  386. s32 remaining;
  387. u32 delta_us;
  388. int err;
  389. struct net *net = dev_net(icmp_skb->dev);
  390. sk = __inet_lookup_established(net, &tcp_hashinfo, iph->daddr,
  391. th->dest, iph->saddr, ntohs(th->source),
  392. inet_iif(icmp_skb), 0);
  393. if (!sk) {
  394. __ICMP_INC_STATS(net, ICMP_MIB_INERRORS);
  395. return;
  396. }
  397. if (sk->sk_state == TCP_TIME_WAIT) {
  398. inet_twsk_put(inet_twsk(sk));
  399. return;
  400. }
  401. seq = ntohl(th->seq);
  402. if (sk->sk_state == TCP_NEW_SYN_RECV)
  403. return tcp_req_err(sk, seq,
  404. type == ICMP_PARAMETERPROB ||
  405. type == ICMP_TIME_EXCEEDED ||
  406. (type == ICMP_DEST_UNREACH &&
  407. (code == ICMP_NET_UNREACH ||
  408. code == ICMP_HOST_UNREACH)));
  409. bh_lock_sock(sk);
  410. /* If too many ICMPs get dropped on busy
  411. * servers this needs to be solved differently.
  412. * We do take care of PMTU discovery (RFC1191) special case :
  413. * we can receive locally generated ICMP messages while socket is held.
  414. */
  415. if (sock_owned_by_user(sk)) {
  416. if (!(type == ICMP_DEST_UNREACH && code == ICMP_FRAG_NEEDED))
  417. __NET_INC_STATS(net, LINUX_MIB_LOCKDROPPEDICMPS);
  418. }
  419. if (sk->sk_state == TCP_CLOSE)
  420. goto out;
  421. if (unlikely(iph->ttl < inet_sk(sk)->min_ttl)) {
  422. __NET_INC_STATS(net, LINUX_MIB_TCPMINTTLDROP);
  423. goto out;
  424. }
  425. icsk = inet_csk(sk);
  426. tp = tcp_sk(sk);
  427. /* XXX (TFO) - tp->snd_una should be ISN (tcp_create_openreq_child() */
  428. fastopen = tp->fastopen_rsk;
  429. snd_una = fastopen ? tcp_rsk(fastopen)->snt_isn : tp->snd_una;
  430. if (sk->sk_state != TCP_LISTEN &&
  431. !between(seq, snd_una, tp->snd_nxt)) {
  432. __NET_INC_STATS(net, LINUX_MIB_OUTOFWINDOWICMPS);
  433. goto out;
  434. }
  435. switch (type) {
  436. case ICMP_REDIRECT:
  437. if (!sock_owned_by_user(sk))
  438. do_redirect(icmp_skb, sk);
  439. goto out;
  440. case ICMP_SOURCE_QUENCH:
  441. /* Just silently ignore these. */
  442. goto out;
  443. case ICMP_PARAMETERPROB:
  444. err = EPROTO;
  445. break;
  446. case ICMP_DEST_UNREACH:
  447. if (code > NR_ICMP_UNREACH)
  448. goto out;
  449. if (code == ICMP_FRAG_NEEDED) { /* PMTU discovery (RFC1191) */
  450. /* We are not interested in TCP_LISTEN and open_requests
  451. * (SYN-ACKs send out by Linux are always <576bytes so
  452. * they should go through unfragmented).
  453. */
  454. if (sk->sk_state == TCP_LISTEN)
  455. goto out;
  456. tp->mtu_info = info;
  457. if (!sock_owned_by_user(sk)) {
  458. tcp_v4_mtu_reduced(sk);
  459. } else {
  460. if (!test_and_set_bit(TCP_MTU_REDUCED_DEFERRED, &sk->sk_tsq_flags))
  461. sock_hold(sk);
  462. }
  463. goto out;
  464. }
  465. err = icmp_err_convert[code].errno;
  466. /* check if icmp_skb allows revert of backoff
  467. * (see draft-zimmermann-tcp-lcd) */
  468. if (code != ICMP_NET_UNREACH && code != ICMP_HOST_UNREACH)
  469. break;
  470. if (seq != tp->snd_una || !icsk->icsk_retransmits ||
  471. !icsk->icsk_backoff || fastopen)
  472. break;
  473. if (sock_owned_by_user(sk))
  474. break;
  475. skb = tcp_rtx_queue_head(sk);
  476. if (WARN_ON_ONCE(!skb))
  477. break;
  478. icsk->icsk_backoff--;
  479. icsk->icsk_rto = tp->srtt_us ? __tcp_set_rto(tp) :
  480. TCP_TIMEOUT_INIT;
  481. icsk->icsk_rto = inet_csk_rto_backoff(icsk, TCP_RTO_MAX);
  482. tcp_mstamp_refresh(tp);
  483. delta_us = (u32)(tp->tcp_mstamp - skb->skb_mstamp);
  484. remaining = icsk->icsk_rto -
  485. usecs_to_jiffies(delta_us);
  486. if (remaining > 0) {
  487. inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS,
  488. remaining, TCP_RTO_MAX);
  489. } else {
  490. /* RTO revert clocked out retransmission.
  491. * Will retransmit now */
  492. tcp_retransmit_timer(sk);
  493. }
  494. break;
  495. case ICMP_TIME_EXCEEDED:
  496. err = EHOSTUNREACH;
  497. break;
  498. default:
  499. goto out;
  500. }
  501. switch (sk->sk_state) {
  502. case TCP_SYN_SENT:
  503. case TCP_SYN_RECV:
  504. /* Only in fast or simultaneous open. If a fast open socket is
  505. * is already accepted it is treated as a connected one below.
  506. */
  507. if (fastopen && !fastopen->sk)
  508. break;
  509. if (!sock_owned_by_user(sk)) {
  510. sk->sk_err = err;
  511. sk->sk_error_report(sk);
  512. tcp_done(sk);
  513. } else {
  514. sk->sk_err_soft = err;
  515. }
  516. goto out;
  517. }
  518. /* If we've already connected we will keep trying
  519. * until we time out, or the user gives up.
  520. *
  521. * rfc1122 4.2.3.9 allows to consider as hard errors
  522. * only PROTO_UNREACH and PORT_UNREACH (well, FRAG_FAILED too,
  523. * but it is obsoleted by pmtu discovery).
  524. *
  525. * Note, that in modern internet, where routing is unreliable
  526. * and in each dark corner broken firewalls sit, sending random
  527. * errors ordered by their masters even this two messages finally lose
  528. * their original sense (even Linux sends invalid PORT_UNREACHs)
  529. *
  530. * Now we are in compliance with RFCs.
  531. * --ANK (980905)
  532. */
  533. inet = inet_sk(sk);
  534. if (!sock_owned_by_user(sk) && inet->recverr) {
  535. sk->sk_err = err;
  536. sk->sk_error_report(sk);
  537. } else { /* Only an error on timeout */
  538. sk->sk_err_soft = err;
  539. }
  540. out:
  541. bh_unlock_sock(sk);
  542. sock_put(sk);
  543. }
  544. void __tcp_v4_send_check(struct sk_buff *skb, __be32 saddr, __be32 daddr)
  545. {
  546. struct tcphdr *th = tcp_hdr(skb);
  547. th->check = ~tcp_v4_check(skb->len, saddr, daddr, 0);
  548. skb->csum_start = skb_transport_header(skb) - skb->head;
  549. skb->csum_offset = offsetof(struct tcphdr, check);
  550. }
  551. /* This routine computes an IPv4 TCP checksum. */
  552. void tcp_v4_send_check(struct sock *sk, struct sk_buff *skb)
  553. {
  554. const struct inet_sock *inet = inet_sk(sk);
  555. __tcp_v4_send_check(skb, inet->inet_saddr, inet->inet_daddr);
  556. }
  557. EXPORT_SYMBOL(tcp_v4_send_check);
  558. /*
  559. * This routine will send an RST to the other tcp.
  560. *
  561. * Someone asks: why I NEVER use socket parameters (TOS, TTL etc.)
  562. * for reset.
  563. * Answer: if a packet caused RST, it is not for a socket
  564. * existing in our system, if it is matched to a socket,
  565. * it is just duplicate segment or bug in other side's TCP.
  566. * So that we build reply only basing on parameters
  567. * arrived with segment.
  568. * Exception: precedence violation. We do not implement it in any case.
  569. */
  570. static void tcp_v4_send_reset(const struct sock *sk, struct sk_buff *skb)
  571. {
  572. const struct tcphdr *th = tcp_hdr(skb);
  573. struct {
  574. struct tcphdr th;
  575. #ifdef CONFIG_TCP_MD5SIG
  576. __be32 opt[(TCPOLEN_MD5SIG_ALIGNED >> 2)];
  577. #endif
  578. } rep;
  579. struct ip_reply_arg arg;
  580. #ifdef CONFIG_TCP_MD5SIG
  581. struct tcp_md5sig_key *key = NULL;
  582. const __u8 *hash_location = NULL;
  583. unsigned char newhash[16];
  584. int genhash;
  585. struct sock *sk1 = NULL;
  586. #endif
  587. struct net *net;
  588. struct sock *ctl_sk;
  589. /* Never send a reset in response to a reset. */
  590. if (th->rst)
  591. return;
  592. /* If sk not NULL, it means we did a successful lookup and incoming
  593. * route had to be correct. prequeue might have dropped our dst.
  594. */
  595. if (!sk && skb_rtable(skb)->rt_type != RTN_LOCAL)
  596. return;
  597. /* Swap the send and the receive. */
  598. memset(&rep, 0, sizeof(rep));
  599. rep.th.dest = th->source;
  600. rep.th.source = th->dest;
  601. rep.th.doff = sizeof(struct tcphdr) / 4;
  602. rep.th.rst = 1;
  603. if (th->ack) {
  604. rep.th.seq = th->ack_seq;
  605. } else {
  606. rep.th.ack = 1;
  607. rep.th.ack_seq = htonl(ntohl(th->seq) + th->syn + th->fin +
  608. skb->len - (th->doff << 2));
  609. }
  610. memset(&arg, 0, sizeof(arg));
  611. arg.iov[0].iov_base = (unsigned char *)&rep;
  612. arg.iov[0].iov_len = sizeof(rep.th);
  613. net = sk ? sock_net(sk) : dev_net(skb_dst(skb)->dev);
  614. #ifdef CONFIG_TCP_MD5SIG
  615. rcu_read_lock();
  616. hash_location = tcp_parse_md5sig_option(th);
  617. if (sk && sk_fullsock(sk)) {
  618. key = tcp_md5_do_lookup(sk, (union tcp_md5_addr *)
  619. &ip_hdr(skb)->saddr, AF_INET);
  620. } else if (hash_location) {
  621. /*
  622. * active side is lost. Try to find listening socket through
  623. * source port, and then find md5 key through listening socket.
  624. * we are not loose security here:
  625. * Incoming packet is checked with md5 hash with finding key,
  626. * no RST generated if md5 hash doesn't match.
  627. */
  628. sk1 = __inet_lookup_listener(net, &tcp_hashinfo, NULL, 0,
  629. ip_hdr(skb)->saddr,
  630. th->source, ip_hdr(skb)->daddr,
  631. ntohs(th->source), inet_iif(skb),
  632. tcp_v4_sdif(skb));
  633. /* don't send rst if it can't find key */
  634. if (!sk1)
  635. goto out;
  636. key = tcp_md5_do_lookup(sk1, (union tcp_md5_addr *)
  637. &ip_hdr(skb)->saddr, AF_INET);
  638. if (!key)
  639. goto out;
  640. genhash = tcp_v4_md5_hash_skb(newhash, key, NULL, skb);
  641. if (genhash || memcmp(hash_location, newhash, 16) != 0)
  642. goto out;
  643. }
  644. if (key) {
  645. rep.opt[0] = htonl((TCPOPT_NOP << 24) |
  646. (TCPOPT_NOP << 16) |
  647. (TCPOPT_MD5SIG << 8) |
  648. TCPOLEN_MD5SIG);
  649. /* Update length and the length the header thinks exists */
  650. arg.iov[0].iov_len += TCPOLEN_MD5SIG_ALIGNED;
  651. rep.th.doff = arg.iov[0].iov_len / 4;
  652. tcp_v4_md5_hash_hdr((__u8 *) &rep.opt[1],
  653. key, ip_hdr(skb)->saddr,
  654. ip_hdr(skb)->daddr, &rep.th);
  655. }
  656. #endif
  657. arg.csum = csum_tcpudp_nofold(ip_hdr(skb)->daddr,
  658. ip_hdr(skb)->saddr, /* XXX */
  659. arg.iov[0].iov_len, IPPROTO_TCP, 0);
  660. arg.csumoffset = offsetof(struct tcphdr, check) / 2;
  661. arg.flags = (sk && inet_sk_transparent(sk)) ? IP_REPLY_ARG_NOSRCCHECK : 0;
  662. /* When socket is gone, all binding information is lost.
  663. * routing might fail in this case. No choice here, if we choose to force
  664. * input interface, we will misroute in case of asymmetric route.
  665. */
  666. if (sk) {
  667. arg.bound_dev_if = sk->sk_bound_dev_if;
  668. if (sk_fullsock(sk))
  669. trace_tcp_send_reset(sk, skb);
  670. }
  671. BUILD_BUG_ON(offsetof(struct sock, sk_bound_dev_if) !=
  672. offsetof(struct inet_timewait_sock, tw_bound_dev_if));
  673. arg.tos = ip_hdr(skb)->tos;
  674. arg.uid = sock_net_uid(net, sk && sk_fullsock(sk) ? sk : NULL);
  675. local_bh_disable();
  676. ctl_sk = *this_cpu_ptr(net->ipv4.tcp_sk);
  677. if (sk)
  678. ctl_sk->sk_mark = (sk->sk_state == TCP_TIME_WAIT) ?
  679. inet_twsk(sk)->tw_mark : sk->sk_mark;
  680. ip_send_unicast_reply(ctl_sk,
  681. skb, &TCP_SKB_CB(skb)->header.h4.opt,
  682. ip_hdr(skb)->saddr, ip_hdr(skb)->daddr,
  683. &arg, arg.iov[0].iov_len);
  684. ctl_sk->sk_mark = 0;
  685. __TCP_INC_STATS(net, TCP_MIB_OUTSEGS);
  686. __TCP_INC_STATS(net, TCP_MIB_OUTRSTS);
  687. local_bh_enable();
  688. #ifdef CONFIG_TCP_MD5SIG
  689. out:
  690. rcu_read_unlock();
  691. #endif
  692. }
  693. /* The code following below sending ACKs in SYN-RECV and TIME-WAIT states
  694. outside socket context is ugly, certainly. What can I do?
  695. */
  696. static void tcp_v4_send_ack(const struct sock *sk,
  697. struct sk_buff *skb, u32 seq, u32 ack,
  698. u32 win, u32 tsval, u32 tsecr, int oif,
  699. struct tcp_md5sig_key *key,
  700. int reply_flags, u8 tos)
  701. {
  702. const struct tcphdr *th = tcp_hdr(skb);
  703. struct {
  704. struct tcphdr th;
  705. __be32 opt[(TCPOLEN_TSTAMP_ALIGNED >> 2)
  706. #ifdef CONFIG_TCP_MD5SIG
  707. + (TCPOLEN_MD5SIG_ALIGNED >> 2)
  708. #endif
  709. ];
  710. } rep;
  711. struct net *net = sock_net(sk);
  712. struct ip_reply_arg arg;
  713. struct sock *ctl_sk;
  714. memset(&rep.th, 0, sizeof(struct tcphdr));
  715. memset(&arg, 0, sizeof(arg));
  716. arg.iov[0].iov_base = (unsigned char *)&rep;
  717. arg.iov[0].iov_len = sizeof(rep.th);
  718. if (tsecr) {
  719. rep.opt[0] = htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) |
  720. (TCPOPT_TIMESTAMP << 8) |
  721. TCPOLEN_TIMESTAMP);
  722. rep.opt[1] = htonl(tsval);
  723. rep.opt[2] = htonl(tsecr);
  724. arg.iov[0].iov_len += TCPOLEN_TSTAMP_ALIGNED;
  725. }
  726. /* Swap the send and the receive. */
  727. rep.th.dest = th->source;
  728. rep.th.source = th->dest;
  729. rep.th.doff = arg.iov[0].iov_len / 4;
  730. rep.th.seq = htonl(seq);
  731. rep.th.ack_seq = htonl(ack);
  732. rep.th.ack = 1;
  733. rep.th.window = htons(win);
  734. #ifdef CONFIG_TCP_MD5SIG
  735. if (key) {
  736. int offset = (tsecr) ? 3 : 0;
  737. rep.opt[offset++] = htonl((TCPOPT_NOP << 24) |
  738. (TCPOPT_NOP << 16) |
  739. (TCPOPT_MD5SIG << 8) |
  740. TCPOLEN_MD5SIG);
  741. arg.iov[0].iov_len += TCPOLEN_MD5SIG_ALIGNED;
  742. rep.th.doff = arg.iov[0].iov_len/4;
  743. tcp_v4_md5_hash_hdr((__u8 *) &rep.opt[offset],
  744. key, ip_hdr(skb)->saddr,
  745. ip_hdr(skb)->daddr, &rep.th);
  746. }
  747. #endif
  748. arg.flags = reply_flags;
  749. arg.csum = csum_tcpudp_nofold(ip_hdr(skb)->daddr,
  750. ip_hdr(skb)->saddr, /* XXX */
  751. arg.iov[0].iov_len, IPPROTO_TCP, 0);
  752. arg.csumoffset = offsetof(struct tcphdr, check) / 2;
  753. if (oif)
  754. arg.bound_dev_if = oif;
  755. arg.tos = tos;
  756. arg.uid = sock_net_uid(net, sk_fullsock(sk) ? sk : NULL);
  757. local_bh_disable();
  758. ctl_sk = *this_cpu_ptr(net->ipv4.tcp_sk);
  759. if (sk)
  760. ctl_sk->sk_mark = (sk->sk_state == TCP_TIME_WAIT) ?
  761. inet_twsk(sk)->tw_mark : sk->sk_mark;
  762. ip_send_unicast_reply(ctl_sk,
  763. skb, &TCP_SKB_CB(skb)->header.h4.opt,
  764. ip_hdr(skb)->saddr, ip_hdr(skb)->daddr,
  765. &arg, arg.iov[0].iov_len);
  766. ctl_sk->sk_mark = 0;
  767. __TCP_INC_STATS(net, TCP_MIB_OUTSEGS);
  768. local_bh_enable();
  769. }
  770. static void tcp_v4_timewait_ack(struct sock *sk, struct sk_buff *skb)
  771. {
  772. struct inet_timewait_sock *tw = inet_twsk(sk);
  773. struct tcp_timewait_sock *tcptw = tcp_twsk(sk);
  774. tcp_v4_send_ack(sk, skb,
  775. tcptw->tw_snd_nxt, tcptw->tw_rcv_nxt,
  776. tcptw->tw_rcv_wnd >> tw->tw_rcv_wscale,
  777. tcp_time_stamp_raw() + tcptw->tw_ts_offset,
  778. tcptw->tw_ts_recent,
  779. tw->tw_bound_dev_if,
  780. tcp_twsk_md5_key(tcptw),
  781. tw->tw_transparent ? IP_REPLY_ARG_NOSRCCHECK : 0,
  782. tw->tw_tos
  783. );
  784. inet_twsk_put(tw);
  785. }
  786. static void tcp_v4_reqsk_send_ack(const struct sock *sk, struct sk_buff *skb,
  787. struct request_sock *req)
  788. {
  789. /* sk->sk_state == TCP_LISTEN -> for regular TCP_SYN_RECV
  790. * sk->sk_state == TCP_SYN_RECV -> for Fast Open.
  791. */
  792. u32 seq = (sk->sk_state == TCP_LISTEN) ? tcp_rsk(req)->snt_isn + 1 :
  793. tcp_sk(sk)->snd_nxt;
  794. /* RFC 7323 2.3
  795. * The window field (SEG.WND) of every outgoing segment, with the
  796. * exception of <SYN> segments, MUST be right-shifted by
  797. * Rcv.Wind.Shift bits:
  798. */
  799. tcp_v4_send_ack(sk, skb, seq,
  800. tcp_rsk(req)->rcv_nxt,
  801. req->rsk_rcv_wnd >> inet_rsk(req)->rcv_wscale,
  802. tcp_time_stamp_raw() + tcp_rsk(req)->ts_off,
  803. req->ts_recent,
  804. 0,
  805. tcp_md5_do_lookup(sk, (union tcp_md5_addr *)&ip_hdr(skb)->saddr,
  806. AF_INET),
  807. inet_rsk(req)->no_srccheck ? IP_REPLY_ARG_NOSRCCHECK : 0,
  808. ip_hdr(skb)->tos);
  809. }
  810. /*
  811. * Send a SYN-ACK after having received a SYN.
  812. * This still operates on a request_sock only, not on a big
  813. * socket.
  814. */
  815. static int tcp_v4_send_synack(const struct sock *sk, struct dst_entry *dst,
  816. struct flowi *fl,
  817. struct request_sock *req,
  818. struct tcp_fastopen_cookie *foc,
  819. enum tcp_synack_type synack_type)
  820. {
  821. const struct inet_request_sock *ireq = inet_rsk(req);
  822. struct flowi4 fl4;
  823. int err = -1;
  824. struct sk_buff *skb;
  825. /* First, grab a route. */
  826. if (!dst && (dst = inet_csk_route_req(sk, &fl4, req)) == NULL)
  827. return -1;
  828. skb = tcp_make_synack(sk, dst, req, foc, synack_type);
  829. if (skb) {
  830. __tcp_v4_send_check(skb, ireq->ir_loc_addr, ireq->ir_rmt_addr);
  831. rcu_read_lock();
  832. err = ip_build_and_send_pkt(skb, sk, ireq->ir_loc_addr,
  833. ireq->ir_rmt_addr,
  834. rcu_dereference(ireq->ireq_opt));
  835. rcu_read_unlock();
  836. err = net_xmit_eval(err);
  837. }
  838. return err;
  839. }
  840. /*
  841. * IPv4 request_sock destructor.
  842. */
  843. static void tcp_v4_reqsk_destructor(struct request_sock *req)
  844. {
  845. kfree(rcu_dereference_protected(inet_rsk(req)->ireq_opt, 1));
  846. }
  847. #ifdef CONFIG_TCP_MD5SIG
  848. /*
  849. * RFC2385 MD5 checksumming requires a mapping of
  850. * IP address->MD5 Key.
  851. * We need to maintain these in the sk structure.
  852. */
  853. /* Find the Key structure for an address. */
  854. struct tcp_md5sig_key *tcp_md5_do_lookup(const struct sock *sk,
  855. const union tcp_md5_addr *addr,
  856. int family)
  857. {
  858. const struct tcp_sock *tp = tcp_sk(sk);
  859. struct tcp_md5sig_key *key;
  860. const struct tcp_md5sig_info *md5sig;
  861. __be32 mask;
  862. struct tcp_md5sig_key *best_match = NULL;
  863. bool match;
  864. /* caller either holds rcu_read_lock() or socket lock */
  865. md5sig = rcu_dereference_check(tp->md5sig_info,
  866. lockdep_sock_is_held(sk));
  867. if (!md5sig)
  868. return NULL;
  869. hlist_for_each_entry_rcu(key, &md5sig->head, node) {
  870. if (key->family != family)
  871. continue;
  872. if (family == AF_INET) {
  873. mask = inet_make_mask(key->prefixlen);
  874. match = (key->addr.a4.s_addr & mask) ==
  875. (addr->a4.s_addr & mask);
  876. #if IS_ENABLED(CONFIG_IPV6)
  877. } else if (family == AF_INET6) {
  878. match = ipv6_prefix_equal(&key->addr.a6, &addr->a6,
  879. key->prefixlen);
  880. #endif
  881. } else {
  882. match = false;
  883. }
  884. if (match && (!best_match ||
  885. key->prefixlen > best_match->prefixlen))
  886. best_match = key;
  887. }
  888. return best_match;
  889. }
  890. EXPORT_SYMBOL(tcp_md5_do_lookup);
  891. static struct tcp_md5sig_key *tcp_md5_do_lookup_exact(const struct sock *sk,
  892. const union tcp_md5_addr *addr,
  893. int family, u8 prefixlen)
  894. {
  895. const struct tcp_sock *tp = tcp_sk(sk);
  896. struct tcp_md5sig_key *key;
  897. unsigned int size = sizeof(struct in_addr);
  898. const struct tcp_md5sig_info *md5sig;
  899. /* caller either holds rcu_read_lock() or socket lock */
  900. md5sig = rcu_dereference_check(tp->md5sig_info,
  901. lockdep_sock_is_held(sk));
  902. if (!md5sig)
  903. return NULL;
  904. #if IS_ENABLED(CONFIG_IPV6)
  905. if (family == AF_INET6)
  906. size = sizeof(struct in6_addr);
  907. #endif
  908. hlist_for_each_entry_rcu(key, &md5sig->head, node) {
  909. if (key->family != family)
  910. continue;
  911. if (!memcmp(&key->addr, addr, size) &&
  912. key->prefixlen == prefixlen)
  913. return key;
  914. }
  915. return NULL;
  916. }
  917. struct tcp_md5sig_key *tcp_v4_md5_lookup(const struct sock *sk,
  918. const struct sock *addr_sk)
  919. {
  920. const union tcp_md5_addr *addr;
  921. addr = (const union tcp_md5_addr *)&addr_sk->sk_daddr;
  922. return tcp_md5_do_lookup(sk, addr, AF_INET);
  923. }
  924. EXPORT_SYMBOL(tcp_v4_md5_lookup);
  925. /* This can be called on a newly created socket, from other files */
  926. int tcp_md5_do_add(struct sock *sk, const union tcp_md5_addr *addr,
  927. int family, u8 prefixlen, const u8 *newkey, u8 newkeylen,
  928. gfp_t gfp)
  929. {
  930. /* Add Key to the list */
  931. struct tcp_md5sig_key *key;
  932. struct tcp_sock *tp = tcp_sk(sk);
  933. struct tcp_md5sig_info *md5sig;
  934. key = tcp_md5_do_lookup_exact(sk, addr, family, prefixlen);
  935. if (key) {
  936. /* Pre-existing entry - just update that one.
  937. * Note that the key might be used concurrently.
  938. */
  939. memcpy(key->key, newkey, newkeylen);
  940. /* Pairs with READ_ONCE() in tcp_md5_hash_key().
  941. * Also note that a reader could catch new key->keylen value
  942. * but old key->key[], this is the reason we use __GFP_ZERO
  943. * at sock_kmalloc() time below these lines.
  944. */
  945. WRITE_ONCE(key->keylen, newkeylen);
  946. return 0;
  947. }
  948. md5sig = rcu_dereference_protected(tp->md5sig_info,
  949. lockdep_sock_is_held(sk));
  950. if (!md5sig) {
  951. md5sig = kmalloc(sizeof(*md5sig), gfp);
  952. if (!md5sig)
  953. return -ENOMEM;
  954. sk_nocaps_add(sk, NETIF_F_GSO_MASK);
  955. INIT_HLIST_HEAD(&md5sig->head);
  956. rcu_assign_pointer(tp->md5sig_info, md5sig);
  957. }
  958. key = sock_kmalloc(sk, sizeof(*key), gfp | __GFP_ZERO);
  959. if (!key)
  960. return -ENOMEM;
  961. if (!tcp_alloc_md5sig_pool()) {
  962. sock_kfree_s(sk, key, sizeof(*key));
  963. return -ENOMEM;
  964. }
  965. memcpy(key->key, newkey, newkeylen);
  966. key->keylen = newkeylen;
  967. key->family = family;
  968. key->prefixlen = prefixlen;
  969. memcpy(&key->addr, addr,
  970. (family == AF_INET6) ? sizeof(struct in6_addr) :
  971. sizeof(struct in_addr));
  972. hlist_add_head_rcu(&key->node, &md5sig->head);
  973. return 0;
  974. }
  975. EXPORT_SYMBOL(tcp_md5_do_add);
  976. int tcp_md5_do_del(struct sock *sk, const union tcp_md5_addr *addr, int family,
  977. u8 prefixlen)
  978. {
  979. struct tcp_md5sig_key *key;
  980. key = tcp_md5_do_lookup_exact(sk, addr, family, prefixlen);
  981. if (!key)
  982. return -ENOENT;
  983. hlist_del_rcu(&key->node);
  984. atomic_sub(sizeof(*key), &sk->sk_omem_alloc);
  985. kfree_rcu(key, rcu);
  986. return 0;
  987. }
  988. EXPORT_SYMBOL(tcp_md5_do_del);
  989. static void tcp_clear_md5_list(struct sock *sk)
  990. {
  991. struct tcp_sock *tp = tcp_sk(sk);
  992. struct tcp_md5sig_key *key;
  993. struct hlist_node *n;
  994. struct tcp_md5sig_info *md5sig;
  995. md5sig = rcu_dereference_protected(tp->md5sig_info, 1);
  996. hlist_for_each_entry_safe(key, n, &md5sig->head, node) {
  997. hlist_del_rcu(&key->node);
  998. atomic_sub(sizeof(*key), &sk->sk_omem_alloc);
  999. kfree_rcu(key, rcu);
  1000. }
  1001. }
  1002. static int tcp_v4_parse_md5_keys(struct sock *sk, int optname,
  1003. char __user *optval, int optlen)
  1004. {
  1005. struct tcp_md5sig cmd;
  1006. struct sockaddr_in *sin = (struct sockaddr_in *)&cmd.tcpm_addr;
  1007. u8 prefixlen = 32;
  1008. if (optlen < sizeof(cmd))
  1009. return -EINVAL;
  1010. if (copy_from_user(&cmd, optval, sizeof(cmd)))
  1011. return -EFAULT;
  1012. if (sin->sin_family != AF_INET)
  1013. return -EINVAL;
  1014. if (optname == TCP_MD5SIG_EXT &&
  1015. cmd.tcpm_flags & TCP_MD5SIG_FLAG_PREFIX) {
  1016. prefixlen = cmd.tcpm_prefixlen;
  1017. if (prefixlen > 32)
  1018. return -EINVAL;
  1019. }
  1020. if (!cmd.tcpm_keylen)
  1021. return tcp_md5_do_del(sk, (union tcp_md5_addr *)&sin->sin_addr.s_addr,
  1022. AF_INET, prefixlen);
  1023. if (cmd.tcpm_keylen > TCP_MD5SIG_MAXKEYLEN)
  1024. return -EINVAL;
  1025. return tcp_md5_do_add(sk, (union tcp_md5_addr *)&sin->sin_addr.s_addr,
  1026. AF_INET, prefixlen, cmd.tcpm_key, cmd.tcpm_keylen,
  1027. GFP_KERNEL);
  1028. }
  1029. static int tcp_v4_md5_hash_headers(struct tcp_md5sig_pool *hp,
  1030. __be32 daddr, __be32 saddr,
  1031. const struct tcphdr *th, int nbytes)
  1032. {
  1033. struct tcp4_pseudohdr *bp;
  1034. struct scatterlist sg;
  1035. struct tcphdr *_th;
  1036. bp = hp->scratch;
  1037. bp->saddr = saddr;
  1038. bp->daddr = daddr;
  1039. bp->pad = 0;
  1040. bp->protocol = IPPROTO_TCP;
  1041. bp->len = cpu_to_be16(nbytes);
  1042. _th = (struct tcphdr *)(bp + 1);
  1043. memcpy(_th, th, sizeof(*th));
  1044. _th->check = 0;
  1045. sg_init_one(&sg, bp, sizeof(*bp) + sizeof(*th));
  1046. ahash_request_set_crypt(hp->md5_req, &sg, NULL,
  1047. sizeof(*bp) + sizeof(*th));
  1048. return crypto_ahash_update(hp->md5_req);
  1049. }
  1050. static int tcp_v4_md5_hash_hdr(char *md5_hash, const struct tcp_md5sig_key *key,
  1051. __be32 daddr, __be32 saddr, const struct tcphdr *th)
  1052. {
  1053. struct tcp_md5sig_pool *hp;
  1054. struct ahash_request *req;
  1055. hp = tcp_get_md5sig_pool();
  1056. if (!hp)
  1057. goto clear_hash_noput;
  1058. req = hp->md5_req;
  1059. if (crypto_ahash_init(req))
  1060. goto clear_hash;
  1061. if (tcp_v4_md5_hash_headers(hp, daddr, saddr, th, th->doff << 2))
  1062. goto clear_hash;
  1063. if (tcp_md5_hash_key(hp, key))
  1064. goto clear_hash;
  1065. ahash_request_set_crypt(req, NULL, md5_hash, 0);
  1066. if (crypto_ahash_final(req))
  1067. goto clear_hash;
  1068. tcp_put_md5sig_pool();
  1069. return 0;
  1070. clear_hash:
  1071. tcp_put_md5sig_pool();
  1072. clear_hash_noput:
  1073. memset(md5_hash, 0, 16);
  1074. return 1;
  1075. }
  1076. int tcp_v4_md5_hash_skb(char *md5_hash, const struct tcp_md5sig_key *key,
  1077. const struct sock *sk,
  1078. const struct sk_buff *skb)
  1079. {
  1080. struct tcp_md5sig_pool *hp;
  1081. struct ahash_request *req;
  1082. const struct tcphdr *th = tcp_hdr(skb);
  1083. __be32 saddr, daddr;
  1084. if (sk) { /* valid for establish/request sockets */
  1085. saddr = sk->sk_rcv_saddr;
  1086. daddr = sk->sk_daddr;
  1087. } else {
  1088. const struct iphdr *iph = ip_hdr(skb);
  1089. saddr = iph->saddr;
  1090. daddr = iph->daddr;
  1091. }
  1092. hp = tcp_get_md5sig_pool();
  1093. if (!hp)
  1094. goto clear_hash_noput;
  1095. req = hp->md5_req;
  1096. if (crypto_ahash_init(req))
  1097. goto clear_hash;
  1098. if (tcp_v4_md5_hash_headers(hp, daddr, saddr, th, skb->len))
  1099. goto clear_hash;
  1100. if (tcp_md5_hash_skb_data(hp, skb, th->doff << 2))
  1101. goto clear_hash;
  1102. if (tcp_md5_hash_key(hp, key))
  1103. goto clear_hash;
  1104. ahash_request_set_crypt(req, NULL, md5_hash, 0);
  1105. if (crypto_ahash_final(req))
  1106. goto clear_hash;
  1107. tcp_put_md5sig_pool();
  1108. return 0;
  1109. clear_hash:
  1110. tcp_put_md5sig_pool();
  1111. clear_hash_noput:
  1112. memset(md5_hash, 0, 16);
  1113. return 1;
  1114. }
  1115. EXPORT_SYMBOL(tcp_v4_md5_hash_skb);
  1116. #endif
  1117. /* Called with rcu_read_lock() */
  1118. static bool tcp_v4_inbound_md5_hash(const struct sock *sk,
  1119. const struct sk_buff *skb)
  1120. {
  1121. #ifdef CONFIG_TCP_MD5SIG
  1122. /*
  1123. * This gets called for each TCP segment that arrives
  1124. * so we want to be efficient.
  1125. * We have 3 drop cases:
  1126. * o No MD5 hash and one expected.
  1127. * o MD5 hash and we're not expecting one.
  1128. * o MD5 hash and its wrong.
  1129. */
  1130. const __u8 *hash_location = NULL;
  1131. struct tcp_md5sig_key *hash_expected;
  1132. const struct iphdr *iph = ip_hdr(skb);
  1133. const struct tcphdr *th = tcp_hdr(skb);
  1134. int genhash;
  1135. unsigned char newhash[16];
  1136. hash_expected = tcp_md5_do_lookup(sk, (union tcp_md5_addr *)&iph->saddr,
  1137. AF_INET);
  1138. hash_location = tcp_parse_md5sig_option(th);
  1139. /* We've parsed the options - do we have a hash? */
  1140. if (!hash_expected && !hash_location)
  1141. return false;
  1142. if (hash_expected && !hash_location) {
  1143. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMD5NOTFOUND);
  1144. return true;
  1145. }
  1146. if (!hash_expected && hash_location) {
  1147. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMD5UNEXPECTED);
  1148. return true;
  1149. }
  1150. /* Okay, so this is hash_expected and hash_location -
  1151. * so we need to calculate the checksum.
  1152. */
  1153. genhash = tcp_v4_md5_hash_skb(newhash,
  1154. hash_expected,
  1155. NULL, skb);
  1156. if (genhash || memcmp(hash_location, newhash, 16) != 0) {
  1157. NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMD5FAILURE);
  1158. net_info_ratelimited("MD5 Hash failed for (%pI4, %d)->(%pI4, %d)%s\n",
  1159. &iph->saddr, ntohs(th->source),
  1160. &iph->daddr, ntohs(th->dest),
  1161. genhash ? " tcp_v4_calc_md5_hash failed"
  1162. : "");
  1163. return true;
  1164. }
  1165. return false;
  1166. #endif
  1167. return false;
  1168. }
  1169. static void tcp_v4_init_req(struct request_sock *req,
  1170. const struct sock *sk_listener,
  1171. struct sk_buff *skb)
  1172. {
  1173. struct inet_request_sock *ireq = inet_rsk(req);
  1174. struct net *net = sock_net(sk_listener);
  1175. sk_rcv_saddr_set(req_to_sk(req), ip_hdr(skb)->daddr);
  1176. sk_daddr_set(req_to_sk(req), ip_hdr(skb)->saddr);
  1177. RCU_INIT_POINTER(ireq->ireq_opt, tcp_v4_save_options(net, skb));
  1178. }
  1179. static struct dst_entry *tcp_v4_route_req(const struct sock *sk,
  1180. struct flowi *fl,
  1181. const struct request_sock *req)
  1182. {
  1183. return inet_csk_route_req(sk, &fl->u.ip4, req);
  1184. }
  1185. struct request_sock_ops tcp_request_sock_ops __read_mostly = {
  1186. .family = PF_INET,
  1187. .obj_size = sizeof(struct tcp_request_sock),
  1188. .rtx_syn_ack = tcp_rtx_synack,
  1189. .send_ack = tcp_v4_reqsk_send_ack,
  1190. .destructor = tcp_v4_reqsk_destructor,
  1191. .send_reset = tcp_v4_send_reset,
  1192. .syn_ack_timeout = tcp_syn_ack_timeout,
  1193. };
  1194. static const struct tcp_request_sock_ops tcp_request_sock_ipv4_ops = {
  1195. .mss_clamp = TCP_MSS_DEFAULT,
  1196. #ifdef CONFIG_TCP_MD5SIG
  1197. .req_md5_lookup = tcp_v4_md5_lookup,
  1198. .calc_md5_hash = tcp_v4_md5_hash_skb,
  1199. #endif
  1200. .init_req = tcp_v4_init_req,
  1201. #ifdef CONFIG_SYN_COOKIES
  1202. .cookie_init_seq = cookie_v4_init_sequence,
  1203. #endif
  1204. .route_req = tcp_v4_route_req,
  1205. .init_seq = tcp_v4_init_seq,
  1206. .init_ts_off = tcp_v4_init_ts_off,
  1207. .send_synack = tcp_v4_send_synack,
  1208. };
  1209. int tcp_v4_conn_request(struct sock *sk, struct sk_buff *skb)
  1210. {
  1211. /* Never answer to SYNs send to broadcast or multicast */
  1212. if (skb_rtable(skb)->rt_flags & (RTCF_BROADCAST | RTCF_MULTICAST))
  1213. goto drop;
  1214. return tcp_conn_request(&tcp_request_sock_ops,
  1215. &tcp_request_sock_ipv4_ops, sk, skb);
  1216. drop:
  1217. tcp_listendrop(sk);
  1218. return 0;
  1219. }
  1220. EXPORT_SYMBOL(tcp_v4_conn_request);
  1221. /*
  1222. * The three way handshake has completed - we got a valid synack -
  1223. * now create the new socket.
  1224. */
  1225. struct sock *tcp_v4_syn_recv_sock(const struct sock *sk, struct sk_buff *skb,
  1226. struct request_sock *req,
  1227. struct dst_entry *dst,
  1228. struct request_sock *req_unhash,
  1229. bool *own_req)
  1230. {
  1231. struct inet_request_sock *ireq;
  1232. struct inet_sock *newinet;
  1233. struct tcp_sock *newtp;
  1234. struct sock *newsk;
  1235. #ifdef CONFIG_TCP_MD5SIG
  1236. struct tcp_md5sig_key *key;
  1237. #endif
  1238. struct ip_options_rcu *inet_opt;
  1239. if (sk_acceptq_is_full(sk))
  1240. goto exit_overflow;
  1241. newsk = tcp_create_openreq_child(sk, req, skb);
  1242. if (!newsk)
  1243. goto exit_nonewsk;
  1244. newsk->sk_gso_type = SKB_GSO_TCPV4;
  1245. inet_sk_rx_dst_set(newsk, skb);
  1246. newtp = tcp_sk(newsk);
  1247. newinet = inet_sk(newsk);
  1248. ireq = inet_rsk(req);
  1249. sk_daddr_set(newsk, ireq->ir_rmt_addr);
  1250. sk_rcv_saddr_set(newsk, ireq->ir_loc_addr);
  1251. newsk->sk_bound_dev_if = ireq->ir_iif;
  1252. newinet->inet_saddr = ireq->ir_loc_addr;
  1253. inet_opt = rcu_dereference(ireq->ireq_opt);
  1254. RCU_INIT_POINTER(newinet->inet_opt, inet_opt);
  1255. newinet->mc_index = inet_iif(skb);
  1256. newinet->mc_ttl = ip_hdr(skb)->ttl;
  1257. newinet->rcv_tos = ip_hdr(skb)->tos;
  1258. inet_csk(newsk)->icsk_ext_hdr_len = 0;
  1259. if (inet_opt)
  1260. inet_csk(newsk)->icsk_ext_hdr_len = inet_opt->opt.optlen;
  1261. newinet->inet_id = prandom_u32();
  1262. if (!dst) {
  1263. dst = inet_csk_route_child_sock(sk, newsk, req);
  1264. if (!dst)
  1265. goto put_and_exit;
  1266. } else {
  1267. /* syncookie case : see end of cookie_v4_check() */
  1268. }
  1269. sk_setup_caps(newsk, dst);
  1270. tcp_ca_openreq_child(newsk, dst);
  1271. tcp_sync_mss(newsk, dst_mtu(dst));
  1272. newtp->advmss = tcp_mss_clamp(tcp_sk(sk), dst_metric_advmss(dst));
  1273. tcp_initialize_rcv_mss(newsk);
  1274. #ifdef CONFIG_TCP_MD5SIG
  1275. /* Copy over the MD5 key from the original socket */
  1276. key = tcp_md5_do_lookup(sk, (union tcp_md5_addr *)&newinet->inet_daddr,
  1277. AF_INET);
  1278. if (key) {
  1279. /*
  1280. * We're using one, so create a matching key
  1281. * on the newsk structure. If we fail to get
  1282. * memory, then we end up not copying the key
  1283. * across. Shucks.
  1284. */
  1285. tcp_md5_do_add(newsk, (union tcp_md5_addr *)&newinet->inet_daddr,
  1286. AF_INET, 32, key->key, key->keylen, GFP_ATOMIC);
  1287. sk_nocaps_add(newsk, NETIF_F_GSO_MASK);
  1288. }
  1289. #endif
  1290. if (__inet_inherit_port(sk, newsk) < 0)
  1291. goto put_and_exit;
  1292. *own_req = inet_ehash_nolisten(newsk, req_to_sk(req_unhash));
  1293. if (likely(*own_req)) {
  1294. tcp_move_syn(newtp, req);
  1295. ireq->ireq_opt = NULL;
  1296. } else {
  1297. newinet->inet_opt = NULL;
  1298. }
  1299. return newsk;
  1300. exit_overflow:
  1301. NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS);
  1302. exit_nonewsk:
  1303. dst_release(dst);
  1304. exit:
  1305. tcp_listendrop(sk);
  1306. return NULL;
  1307. put_and_exit:
  1308. newinet->inet_opt = NULL;
  1309. inet_csk_prepare_forced_close(newsk);
  1310. tcp_done(newsk);
  1311. goto exit;
  1312. }
  1313. EXPORT_SYMBOL(tcp_v4_syn_recv_sock);
  1314. static struct sock *tcp_v4_cookie_check(struct sock *sk, struct sk_buff *skb)
  1315. {
  1316. #ifdef CONFIG_SYN_COOKIES
  1317. const struct tcphdr *th = tcp_hdr(skb);
  1318. if (!th->syn)
  1319. sk = cookie_v4_check(sk, skb);
  1320. #endif
  1321. return sk;
  1322. }
  1323. /* The socket must have it's spinlock held when we get
  1324. * here, unless it is a TCP_LISTEN socket.
  1325. *
  1326. * We have a potential double-lock case here, so even when
  1327. * doing backlog processing we use the BH locking scheme.
  1328. * This is because we cannot sleep with the original spinlock
  1329. * held.
  1330. */
  1331. int tcp_v4_do_rcv(struct sock *sk, struct sk_buff *skb)
  1332. {
  1333. struct sock *rsk;
  1334. if (sk->sk_state == TCP_ESTABLISHED) { /* Fast path */
  1335. struct dst_entry *dst = sk->sk_rx_dst;
  1336. sock_rps_save_rxhash(sk, skb);
  1337. sk_mark_napi_id(sk, skb);
  1338. if (dst) {
  1339. if (inet_sk(sk)->rx_dst_ifindex != skb->skb_iif ||
  1340. !dst->ops->check(dst, 0)) {
  1341. dst_release(dst);
  1342. sk->sk_rx_dst = NULL;
  1343. }
  1344. }
  1345. tcp_rcv_established(sk, skb);
  1346. return 0;
  1347. }
  1348. if (tcp_checksum_complete(skb))
  1349. goto csum_err;
  1350. if (sk->sk_state == TCP_LISTEN) {
  1351. struct sock *nsk = tcp_v4_cookie_check(sk, skb);
  1352. if (!nsk)
  1353. goto discard;
  1354. if (nsk != sk) {
  1355. if (tcp_child_process(sk, nsk, skb)) {
  1356. rsk = nsk;
  1357. goto reset;
  1358. }
  1359. return 0;
  1360. }
  1361. } else
  1362. sock_rps_save_rxhash(sk, skb);
  1363. if (tcp_rcv_state_process(sk, skb)) {
  1364. rsk = sk;
  1365. goto reset;
  1366. }
  1367. return 0;
  1368. reset:
  1369. tcp_v4_send_reset(rsk, skb);
  1370. discard:
  1371. kfree_skb(skb);
  1372. /* Be careful here. If this function gets more complicated and
  1373. * gcc suffers from register pressure on the x86, sk (in %ebx)
  1374. * might be destroyed here. This current version compiles correctly,
  1375. * but you have been warned.
  1376. */
  1377. return 0;
  1378. csum_err:
  1379. TCP_INC_STATS(sock_net(sk), TCP_MIB_CSUMERRORS);
  1380. TCP_INC_STATS(sock_net(sk), TCP_MIB_INERRS);
  1381. goto discard;
  1382. }
  1383. EXPORT_SYMBOL(tcp_v4_do_rcv);
  1384. int tcp_v4_early_demux(struct sk_buff *skb)
  1385. {
  1386. const struct iphdr *iph;
  1387. const struct tcphdr *th;
  1388. struct sock *sk;
  1389. if (skb->pkt_type != PACKET_HOST)
  1390. return 0;
  1391. if (!pskb_may_pull(skb, skb_transport_offset(skb) + sizeof(struct tcphdr)))
  1392. return 0;
  1393. iph = ip_hdr(skb);
  1394. th = tcp_hdr(skb);
  1395. if (th->doff < sizeof(struct tcphdr) / 4)
  1396. return 0;
  1397. sk = __inet_lookup_established(dev_net(skb->dev), &tcp_hashinfo,
  1398. iph->saddr, th->source,
  1399. iph->daddr, ntohs(th->dest),
  1400. skb->skb_iif, inet_sdif(skb));
  1401. if (sk) {
  1402. skb->sk = sk;
  1403. skb->destructor = sock_edemux;
  1404. if (sk_fullsock(sk)) {
  1405. struct dst_entry *dst = READ_ONCE(sk->sk_rx_dst);
  1406. if (dst)
  1407. dst = dst_check(dst, 0);
  1408. if (dst &&
  1409. inet_sk(sk)->rx_dst_ifindex == skb->skb_iif)
  1410. skb_dst_set_noref(skb, dst);
  1411. }
  1412. }
  1413. return 0;
  1414. }
  1415. bool tcp_add_backlog(struct sock *sk, struct sk_buff *skb)
  1416. {
  1417. u32 limit = sk->sk_rcvbuf + sk->sk_sndbuf;
  1418. /* Only socket owner can try to collapse/prune rx queues
  1419. * to reduce memory overhead, so add a little headroom here.
  1420. * Few sockets backlog are possibly concurrently non empty.
  1421. */
  1422. limit += 64*1024;
  1423. /* In case all data was pulled from skb frags (in __pskb_pull_tail()),
  1424. * we can fix skb->truesize to its real value to avoid future drops.
  1425. * This is valid because skb is not yet charged to the socket.
  1426. * It has been noticed pure SACK packets were sometimes dropped
  1427. * (if cooked by drivers without copybreak feature).
  1428. */
  1429. skb_condense(skb);
  1430. if (unlikely(sk_add_backlog(sk, skb, limit))) {
  1431. bh_unlock_sock(sk);
  1432. __NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPBACKLOGDROP);
  1433. return true;
  1434. }
  1435. return false;
  1436. }
  1437. EXPORT_SYMBOL(tcp_add_backlog);
  1438. int tcp_filter(struct sock *sk, struct sk_buff *skb)
  1439. {
  1440. struct tcphdr *th = (struct tcphdr *)skb->data;
  1441. return sk_filter_trim_cap(sk, skb, th->doff * 4);
  1442. }
  1443. EXPORT_SYMBOL(tcp_filter);
  1444. static void tcp_v4_restore_cb(struct sk_buff *skb)
  1445. {
  1446. memmove(IPCB(skb), &TCP_SKB_CB(skb)->header.h4,
  1447. sizeof(struct inet_skb_parm));
  1448. }
  1449. static void tcp_v4_fill_cb(struct sk_buff *skb, const struct iphdr *iph,
  1450. const struct tcphdr *th)
  1451. {
  1452. /* This is tricky : We move IPCB at its correct location into TCP_SKB_CB()
  1453. * barrier() makes sure compiler wont play fool^Waliasing games.
  1454. */
  1455. memmove(&TCP_SKB_CB(skb)->header.h4, IPCB(skb),
  1456. sizeof(struct inet_skb_parm));
  1457. barrier();
  1458. TCP_SKB_CB(skb)->seq = ntohl(th->seq);
  1459. TCP_SKB_CB(skb)->end_seq = (TCP_SKB_CB(skb)->seq + th->syn + th->fin +
  1460. skb->len - th->doff * 4);
  1461. TCP_SKB_CB(skb)->ack_seq = ntohl(th->ack_seq);
  1462. TCP_SKB_CB(skb)->tcp_flags = tcp_flag_byte(th);
  1463. TCP_SKB_CB(skb)->tcp_tw_isn = 0;
  1464. TCP_SKB_CB(skb)->ip_dsfield = ipv4_get_dsfield(iph);
  1465. TCP_SKB_CB(skb)->sacked = 0;
  1466. TCP_SKB_CB(skb)->has_rxtstamp =
  1467. skb->tstamp || skb_hwtstamps(skb)->hwtstamp;
  1468. }
  1469. /*
  1470. * From tcp_input.c
  1471. */
  1472. int tcp_v4_rcv(struct sk_buff *skb)
  1473. {
  1474. struct net *net = dev_net(skb->dev);
  1475. int sdif = inet_sdif(skb);
  1476. const struct iphdr *iph;
  1477. const struct tcphdr *th;
  1478. bool refcounted;
  1479. struct sock *sk;
  1480. int ret;
  1481. if (skb->pkt_type != PACKET_HOST)
  1482. goto discard_it;
  1483. /* Count it even if it's bad */
  1484. __TCP_INC_STATS(net, TCP_MIB_INSEGS);
  1485. if (!pskb_may_pull(skb, sizeof(struct tcphdr)))
  1486. goto discard_it;
  1487. th = (const struct tcphdr *)skb->data;
  1488. if (unlikely(th->doff < sizeof(struct tcphdr) / 4))
  1489. goto bad_packet;
  1490. if (!pskb_may_pull(skb, th->doff * 4))
  1491. goto discard_it;
  1492. /* An explanation is required here, I think.
  1493. * Packet length and doff are validated by header prediction,
  1494. * provided case of th->doff==0 is eliminated.
  1495. * So, we defer the checks. */
  1496. if (skb_checksum_init(skb, IPPROTO_TCP, inet_compute_pseudo))
  1497. goto csum_error;
  1498. th = (const struct tcphdr *)skb->data;
  1499. iph = ip_hdr(skb);
  1500. lookup:
  1501. sk = __inet_lookup_skb(&tcp_hashinfo, skb, __tcp_hdrlen(th), th->source,
  1502. th->dest, sdif, &refcounted);
  1503. if (!sk)
  1504. goto no_tcp_socket;
  1505. process:
  1506. if (sk->sk_state == TCP_TIME_WAIT)
  1507. goto do_time_wait;
  1508. if (sk->sk_state == TCP_NEW_SYN_RECV) {
  1509. struct request_sock *req = inet_reqsk(sk);
  1510. bool req_stolen = false;
  1511. struct sock *nsk;
  1512. sk = req->rsk_listener;
  1513. if (unlikely(tcp_v4_inbound_md5_hash(sk, skb))) {
  1514. sk_drops_add(sk, skb);
  1515. reqsk_put(req);
  1516. goto discard_it;
  1517. }
  1518. if (tcp_checksum_complete(skb)) {
  1519. reqsk_put(req);
  1520. goto csum_error;
  1521. }
  1522. if (unlikely(sk->sk_state != TCP_LISTEN)) {
  1523. inet_csk_reqsk_queue_drop_and_put(sk, req);
  1524. goto lookup;
  1525. }
  1526. /* We own a reference on the listener, increase it again
  1527. * as we might lose it too soon.
  1528. */
  1529. sock_hold(sk);
  1530. refcounted = true;
  1531. nsk = NULL;
  1532. if (!tcp_filter(sk, skb)) {
  1533. th = (const struct tcphdr *)skb->data;
  1534. iph = ip_hdr(skb);
  1535. tcp_v4_fill_cb(skb, iph, th);
  1536. nsk = tcp_check_req(sk, skb, req, false, &req_stolen);
  1537. }
  1538. if (!nsk) {
  1539. reqsk_put(req);
  1540. if (req_stolen) {
  1541. /* Another cpu got exclusive access to req
  1542. * and created a full blown socket.
  1543. * Try to feed this packet to this socket
  1544. * instead of discarding it.
  1545. */
  1546. tcp_v4_restore_cb(skb);
  1547. sock_put(sk);
  1548. goto lookup;
  1549. }
  1550. goto discard_and_relse;
  1551. }
  1552. if (nsk == sk) {
  1553. reqsk_put(req);
  1554. tcp_v4_restore_cb(skb);
  1555. } else if (tcp_child_process(sk, nsk, skb)) {
  1556. tcp_v4_send_reset(nsk, skb);
  1557. goto discard_and_relse;
  1558. } else {
  1559. sock_put(sk);
  1560. return 0;
  1561. }
  1562. }
  1563. if (unlikely(iph->ttl < inet_sk(sk)->min_ttl)) {
  1564. __NET_INC_STATS(net, LINUX_MIB_TCPMINTTLDROP);
  1565. goto discard_and_relse;
  1566. }
  1567. if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb))
  1568. goto discard_and_relse;
  1569. if (tcp_v4_inbound_md5_hash(sk, skb))
  1570. goto discard_and_relse;
  1571. nf_reset(skb);
  1572. if (tcp_filter(sk, skb))
  1573. goto discard_and_relse;
  1574. th = (const struct tcphdr *)skb->data;
  1575. iph = ip_hdr(skb);
  1576. tcp_v4_fill_cb(skb, iph, th);
  1577. skb->dev = NULL;
  1578. if (sk->sk_state == TCP_LISTEN) {
  1579. ret = tcp_v4_do_rcv(sk, skb);
  1580. goto put_and_return;
  1581. }
  1582. sk_incoming_cpu_update(sk);
  1583. bh_lock_sock_nested(sk);
  1584. tcp_segs_in(tcp_sk(sk), skb);
  1585. ret = 0;
  1586. if (!sock_owned_by_user(sk)) {
  1587. ret = tcp_v4_do_rcv(sk, skb);
  1588. } else if (tcp_add_backlog(sk, skb)) {
  1589. goto discard_and_relse;
  1590. }
  1591. bh_unlock_sock(sk);
  1592. put_and_return:
  1593. if (refcounted)
  1594. sock_put(sk);
  1595. return ret;
  1596. no_tcp_socket:
  1597. if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
  1598. goto discard_it;
  1599. tcp_v4_fill_cb(skb, iph, th);
  1600. if (tcp_checksum_complete(skb)) {
  1601. csum_error:
  1602. __TCP_INC_STATS(net, TCP_MIB_CSUMERRORS);
  1603. bad_packet:
  1604. __TCP_INC_STATS(net, TCP_MIB_INERRS);
  1605. } else {
  1606. tcp_v4_send_reset(NULL, skb);
  1607. }
  1608. discard_it:
  1609. /* Discard frame. */
  1610. kfree_skb(skb);
  1611. return 0;
  1612. discard_and_relse:
  1613. sk_drops_add(sk, skb);
  1614. if (refcounted)
  1615. sock_put(sk);
  1616. goto discard_it;
  1617. do_time_wait:
  1618. if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb)) {
  1619. inet_twsk_put(inet_twsk(sk));
  1620. goto discard_it;
  1621. }
  1622. tcp_v4_fill_cb(skb, iph, th);
  1623. if (tcp_checksum_complete(skb)) {
  1624. inet_twsk_put(inet_twsk(sk));
  1625. goto csum_error;
  1626. }
  1627. switch (tcp_timewait_state_process(inet_twsk(sk), skb, th)) {
  1628. case TCP_TW_SYN: {
  1629. struct sock *sk2 = inet_lookup_listener(dev_net(skb->dev),
  1630. &tcp_hashinfo, skb,
  1631. __tcp_hdrlen(th),
  1632. iph->saddr, th->source,
  1633. iph->daddr, th->dest,
  1634. inet_iif(skb),
  1635. sdif);
  1636. if (sk2) {
  1637. inet_twsk_deschedule_put(inet_twsk(sk));
  1638. sk = sk2;
  1639. tcp_v4_restore_cb(skb);
  1640. refcounted = false;
  1641. goto process;
  1642. }
  1643. }
  1644. /* to ACK */
  1645. /* fall through */
  1646. case TCP_TW_ACK:
  1647. tcp_v4_timewait_ack(sk, skb);
  1648. break;
  1649. case TCP_TW_RST:
  1650. tcp_v4_send_reset(sk, skb);
  1651. inet_twsk_deschedule_put(inet_twsk(sk));
  1652. goto discard_it;
  1653. case TCP_TW_SUCCESS:;
  1654. }
  1655. goto discard_it;
  1656. }
  1657. static struct timewait_sock_ops tcp_timewait_sock_ops = {
  1658. .twsk_obj_size = sizeof(struct tcp_timewait_sock),
  1659. .twsk_unique = tcp_twsk_unique,
  1660. .twsk_destructor= tcp_twsk_destructor,
  1661. };
  1662. void inet_sk_rx_dst_set(struct sock *sk, const struct sk_buff *skb)
  1663. {
  1664. struct dst_entry *dst = skb_dst(skb);
  1665. if (dst && dst_hold_safe(dst)) {
  1666. sk->sk_rx_dst = dst;
  1667. inet_sk(sk)->rx_dst_ifindex = skb->skb_iif;
  1668. }
  1669. }
  1670. EXPORT_SYMBOL(inet_sk_rx_dst_set);
  1671. const struct inet_connection_sock_af_ops ipv4_specific = {
  1672. .queue_xmit = ip_queue_xmit,
  1673. .send_check = tcp_v4_send_check,
  1674. .rebuild_header = inet_sk_rebuild_header,
  1675. .sk_rx_dst_set = inet_sk_rx_dst_set,
  1676. .conn_request = tcp_v4_conn_request,
  1677. .syn_recv_sock = tcp_v4_syn_recv_sock,
  1678. .net_header_len = sizeof(struct iphdr),
  1679. .setsockopt = ip_setsockopt,
  1680. .getsockopt = ip_getsockopt,
  1681. .addr2sockaddr = inet_csk_addr2sockaddr,
  1682. .sockaddr_len = sizeof(struct sockaddr_in),
  1683. #ifdef CONFIG_COMPAT
  1684. .compat_setsockopt = compat_ip_setsockopt,
  1685. .compat_getsockopt = compat_ip_getsockopt,
  1686. #endif
  1687. .mtu_reduced = tcp_v4_mtu_reduced,
  1688. };
  1689. EXPORT_SYMBOL(ipv4_specific);
  1690. #ifdef CONFIG_TCP_MD5SIG
  1691. static const struct tcp_sock_af_ops tcp_sock_ipv4_specific = {
  1692. .md5_lookup = tcp_v4_md5_lookup,
  1693. .calc_md5_hash = tcp_v4_md5_hash_skb,
  1694. .md5_parse = tcp_v4_parse_md5_keys,
  1695. };
  1696. #endif
  1697. /* NOTE: A lot of things set to zero explicitly by call to
  1698. * sk_alloc() so need not be done here.
  1699. */
  1700. static int tcp_v4_init_sock(struct sock *sk)
  1701. {
  1702. struct inet_connection_sock *icsk = inet_csk(sk);
  1703. tcp_init_sock(sk);
  1704. icsk->icsk_af_ops = &ipv4_specific;
  1705. #ifdef CONFIG_TCP_MD5SIG
  1706. tcp_sk(sk)->af_specific = &tcp_sock_ipv4_specific;
  1707. #endif
  1708. return 0;
  1709. }
  1710. void tcp_v4_destroy_sock(struct sock *sk)
  1711. {
  1712. struct tcp_sock *tp = tcp_sk(sk);
  1713. trace_tcp_destroy_sock(sk);
  1714. tcp_clear_xmit_timers(sk);
  1715. tcp_cleanup_congestion_control(sk);
  1716. tcp_cleanup_ulp(sk);
  1717. /* Cleanup up the write buffer. */
  1718. tcp_write_queue_purge(sk);
  1719. /* Check if we want to disable active TFO */
  1720. tcp_fastopen_active_disable_ofo_check(sk);
  1721. /* Cleans up our, hopefully empty, out_of_order_queue. */
  1722. skb_rbtree_purge(&tp->out_of_order_queue);
  1723. #ifdef CONFIG_TCP_MD5SIG
  1724. /* Clean up the MD5 key list, if any */
  1725. if (tp->md5sig_info) {
  1726. tcp_clear_md5_list(sk);
  1727. kfree_rcu(rcu_dereference_protected(tp->md5sig_info, 1), rcu);
  1728. tp->md5sig_info = NULL;
  1729. }
  1730. #endif
  1731. /* Clean up a referenced TCP bind bucket. */
  1732. if (inet_csk(sk)->icsk_bind_hash)
  1733. inet_put_port(sk);
  1734. BUG_ON(tp->fastopen_rsk);
  1735. /* If socket is aborted during connect operation */
  1736. tcp_free_fastopen_req(tp);
  1737. tcp_fastopen_destroy_cipher(sk);
  1738. tcp_saved_syn_free(tp);
  1739. sk_sockets_allocated_dec(sk);
  1740. }
  1741. EXPORT_SYMBOL(tcp_v4_destroy_sock);
  1742. #ifdef CONFIG_PROC_FS
  1743. /* Proc filesystem TCP sock list dumping. */
  1744. /*
  1745. * Get next listener socket follow cur. If cur is NULL, get first socket
  1746. * starting from bucket given in st->bucket; when st->bucket is zero the
  1747. * very first socket in the hash table is returned.
  1748. */
  1749. static void *listening_get_next(struct seq_file *seq, void *cur)
  1750. {
  1751. struct tcp_seq_afinfo *afinfo = PDE_DATA(file_inode(seq->file));
  1752. struct tcp_iter_state *st = seq->private;
  1753. struct net *net = seq_file_net(seq);
  1754. struct inet_listen_hashbucket *ilb;
  1755. struct hlist_nulls_node *node;
  1756. struct sock *sk = cur;
  1757. if (!sk) {
  1758. get_head:
  1759. ilb = &tcp_hashinfo.listening_hash[st->bucket];
  1760. spin_lock(&ilb->lock);
  1761. sk = sk_nulls_head(&ilb->nulls_head);
  1762. st->offset = 0;
  1763. goto get_sk;
  1764. }
  1765. ilb = &tcp_hashinfo.listening_hash[st->bucket];
  1766. ++st->num;
  1767. ++st->offset;
  1768. sk = sk_nulls_next(sk);
  1769. get_sk:
  1770. sk_nulls_for_each_from(sk, node) {
  1771. if (!net_eq(sock_net(sk), net))
  1772. continue;
  1773. if (sk->sk_family == afinfo->family)
  1774. return sk;
  1775. }
  1776. spin_unlock(&ilb->lock);
  1777. st->offset = 0;
  1778. if (++st->bucket < INET_LHTABLE_SIZE)
  1779. goto get_head;
  1780. return NULL;
  1781. }
  1782. static void *listening_get_idx(struct seq_file *seq, loff_t *pos)
  1783. {
  1784. struct tcp_iter_state *st = seq->private;
  1785. void *rc;
  1786. st->bucket = 0;
  1787. st->offset = 0;
  1788. rc = listening_get_next(seq, NULL);
  1789. while (rc && *pos) {
  1790. rc = listening_get_next(seq, rc);
  1791. --*pos;
  1792. }
  1793. return rc;
  1794. }
  1795. static inline bool empty_bucket(const struct tcp_iter_state *st)
  1796. {
  1797. return hlist_nulls_empty(&tcp_hashinfo.ehash[st->bucket].chain);
  1798. }
  1799. /*
  1800. * Get first established socket starting from bucket given in st->bucket.
  1801. * If st->bucket is zero, the very first socket in the hash is returned.
  1802. */
  1803. static void *established_get_first(struct seq_file *seq)
  1804. {
  1805. struct tcp_seq_afinfo *afinfo = PDE_DATA(file_inode(seq->file));
  1806. struct tcp_iter_state *st = seq->private;
  1807. struct net *net = seq_file_net(seq);
  1808. void *rc = NULL;
  1809. st->offset = 0;
  1810. for (; st->bucket <= tcp_hashinfo.ehash_mask; ++st->bucket) {
  1811. struct sock *sk;
  1812. struct hlist_nulls_node *node;
  1813. spinlock_t *lock = inet_ehash_lockp(&tcp_hashinfo, st->bucket);
  1814. /* Lockless fast path for the common case of empty buckets */
  1815. if (empty_bucket(st))
  1816. continue;
  1817. spin_lock_bh(lock);
  1818. sk_nulls_for_each(sk, node, &tcp_hashinfo.ehash[st->bucket].chain) {
  1819. if (sk->sk_family != afinfo->family ||
  1820. !net_eq(sock_net(sk), net)) {
  1821. continue;
  1822. }
  1823. rc = sk;
  1824. goto out;
  1825. }
  1826. spin_unlock_bh(lock);
  1827. }
  1828. out:
  1829. return rc;
  1830. }
  1831. static void *established_get_next(struct seq_file *seq, void *cur)
  1832. {
  1833. struct tcp_seq_afinfo *afinfo = PDE_DATA(file_inode(seq->file));
  1834. struct sock *sk = cur;
  1835. struct hlist_nulls_node *node;
  1836. struct tcp_iter_state *st = seq->private;
  1837. struct net *net = seq_file_net(seq);
  1838. ++st->num;
  1839. ++st->offset;
  1840. sk = sk_nulls_next(sk);
  1841. sk_nulls_for_each_from(sk, node) {
  1842. if (sk->sk_family == afinfo->family &&
  1843. net_eq(sock_net(sk), net))
  1844. return sk;
  1845. }
  1846. spin_unlock_bh(inet_ehash_lockp(&tcp_hashinfo, st->bucket));
  1847. ++st->bucket;
  1848. return established_get_first(seq);
  1849. }
  1850. static void *established_get_idx(struct seq_file *seq, loff_t pos)
  1851. {
  1852. struct tcp_iter_state *st = seq->private;
  1853. void *rc;
  1854. st->bucket = 0;
  1855. rc = established_get_first(seq);
  1856. while (rc && pos) {
  1857. rc = established_get_next(seq, rc);
  1858. --pos;
  1859. }
  1860. return rc;
  1861. }
  1862. static void *tcp_get_idx(struct seq_file *seq, loff_t pos)
  1863. {
  1864. void *rc;
  1865. struct tcp_iter_state *st = seq->private;
  1866. st->state = TCP_SEQ_STATE_LISTENING;
  1867. rc = listening_get_idx(seq, &pos);
  1868. if (!rc) {
  1869. st->state = TCP_SEQ_STATE_ESTABLISHED;
  1870. rc = established_get_idx(seq, pos);
  1871. }
  1872. return rc;
  1873. }
  1874. static void *tcp_seek_last_pos(struct seq_file *seq)
  1875. {
  1876. struct tcp_iter_state *st = seq->private;
  1877. int offset = st->offset;
  1878. int orig_num = st->num;
  1879. void *rc = NULL;
  1880. switch (st->state) {
  1881. case TCP_SEQ_STATE_LISTENING:
  1882. if (st->bucket >= INET_LHTABLE_SIZE)
  1883. break;
  1884. st->state = TCP_SEQ_STATE_LISTENING;
  1885. rc = listening_get_next(seq, NULL);
  1886. while (offset-- && rc)
  1887. rc = listening_get_next(seq, rc);
  1888. if (rc)
  1889. break;
  1890. st->bucket = 0;
  1891. st->state = TCP_SEQ_STATE_ESTABLISHED;
  1892. /* Fallthrough */
  1893. case TCP_SEQ_STATE_ESTABLISHED:
  1894. if (st->bucket > tcp_hashinfo.ehash_mask)
  1895. break;
  1896. rc = established_get_first(seq);
  1897. while (offset-- && rc)
  1898. rc = established_get_next(seq, rc);
  1899. }
  1900. st->num = orig_num;
  1901. return rc;
  1902. }
  1903. void *tcp_seq_start(struct seq_file *seq, loff_t *pos)
  1904. {
  1905. struct tcp_iter_state *st = seq->private;
  1906. void *rc;
  1907. if (*pos && *pos == st->last_pos) {
  1908. rc = tcp_seek_last_pos(seq);
  1909. if (rc)
  1910. goto out;
  1911. }
  1912. st->state = TCP_SEQ_STATE_LISTENING;
  1913. st->num = 0;
  1914. st->bucket = 0;
  1915. st->offset = 0;
  1916. rc = *pos ? tcp_get_idx(seq, *pos - 1) : SEQ_START_TOKEN;
  1917. out:
  1918. st->last_pos = *pos;
  1919. return rc;
  1920. }
  1921. EXPORT_SYMBOL(tcp_seq_start);
  1922. void *tcp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
  1923. {
  1924. struct tcp_iter_state *st = seq->private;
  1925. void *rc = NULL;
  1926. if (v == SEQ_START_TOKEN) {
  1927. rc = tcp_get_idx(seq, 0);
  1928. goto out;
  1929. }
  1930. switch (st->state) {
  1931. case TCP_SEQ_STATE_LISTENING:
  1932. rc = listening_get_next(seq, v);
  1933. if (!rc) {
  1934. st->state = TCP_SEQ_STATE_ESTABLISHED;
  1935. st->bucket = 0;
  1936. st->offset = 0;
  1937. rc = established_get_first(seq);
  1938. }
  1939. break;
  1940. case TCP_SEQ_STATE_ESTABLISHED:
  1941. rc = established_get_next(seq, v);
  1942. break;
  1943. }
  1944. out:
  1945. ++*pos;
  1946. st->last_pos = *pos;
  1947. return rc;
  1948. }
  1949. EXPORT_SYMBOL(tcp_seq_next);
  1950. void tcp_seq_stop(struct seq_file *seq, void *v)
  1951. {
  1952. struct tcp_iter_state *st = seq->private;
  1953. switch (st->state) {
  1954. case TCP_SEQ_STATE_LISTENING:
  1955. if (v != SEQ_START_TOKEN)
  1956. spin_unlock(&tcp_hashinfo.listening_hash[st->bucket].lock);
  1957. break;
  1958. case TCP_SEQ_STATE_ESTABLISHED:
  1959. if (v)
  1960. spin_unlock_bh(inet_ehash_lockp(&tcp_hashinfo, st->bucket));
  1961. break;
  1962. }
  1963. }
  1964. EXPORT_SYMBOL(tcp_seq_stop);
  1965. static void get_openreq4(const struct request_sock *req,
  1966. struct seq_file *f, int i)
  1967. {
  1968. const struct inet_request_sock *ireq = inet_rsk(req);
  1969. long delta = req->rsk_timer.expires - jiffies;
  1970. seq_printf(f, "%4d: %08X:%04X %08X:%04X"
  1971. " %02X %08X:%08X %02X:%08lX %08X %5u %8d %u %d %pK",
  1972. i,
  1973. ireq->ir_loc_addr,
  1974. ireq->ir_num,
  1975. ireq->ir_rmt_addr,
  1976. ntohs(ireq->ir_rmt_port),
  1977. TCP_SYN_RECV,
  1978. 0, 0, /* could print option size, but that is af dependent. */
  1979. 1, /* timers active (only the expire timer) */
  1980. jiffies_delta_to_clock_t(delta),
  1981. req->num_timeout,
  1982. from_kuid_munged(seq_user_ns(f),
  1983. sock_i_uid(req->rsk_listener)),
  1984. 0, /* non standard timer */
  1985. 0, /* open_requests have no inode */
  1986. 0,
  1987. req);
  1988. }
  1989. static void get_tcp4_sock(struct sock *sk, struct seq_file *f, int i)
  1990. {
  1991. int timer_active;
  1992. unsigned long timer_expires;
  1993. const struct tcp_sock *tp = tcp_sk(sk);
  1994. const struct inet_connection_sock *icsk = inet_csk(sk);
  1995. const struct inet_sock *inet = inet_sk(sk);
  1996. const struct fastopen_queue *fastopenq = &icsk->icsk_accept_queue.fastopenq;
  1997. __be32 dest = inet->inet_daddr;
  1998. __be32 src = inet->inet_rcv_saddr;
  1999. __u16 destp = ntohs(inet->inet_dport);
  2000. __u16 srcp = ntohs(inet->inet_sport);
  2001. int rx_queue;
  2002. int state;
  2003. if (icsk->icsk_pending == ICSK_TIME_RETRANS ||
  2004. icsk->icsk_pending == ICSK_TIME_REO_TIMEOUT ||
  2005. icsk->icsk_pending == ICSK_TIME_LOSS_PROBE) {
  2006. timer_active = 1;
  2007. timer_expires = icsk->icsk_timeout;
  2008. } else if (icsk->icsk_pending == ICSK_TIME_PROBE0) {
  2009. timer_active = 4;
  2010. timer_expires = icsk->icsk_timeout;
  2011. } else if (timer_pending(&sk->sk_timer)) {
  2012. timer_active = 2;
  2013. timer_expires = sk->sk_timer.expires;
  2014. } else {
  2015. timer_active = 0;
  2016. timer_expires = jiffies;
  2017. }
  2018. state = inet_sk_state_load(sk);
  2019. if (state == TCP_LISTEN)
  2020. rx_queue = sk->sk_ack_backlog;
  2021. else
  2022. /* Because we don't lock the socket,
  2023. * we might find a transient negative value.
  2024. */
  2025. rx_queue = max_t(int, READ_ONCE(tp->rcv_nxt) -
  2026. READ_ONCE(tp->copied_seq), 0);
  2027. seq_printf(f, "%4d: %08X:%04X %08X:%04X %02X %08X:%08X %02X:%08lX "
  2028. "%08X %5u %8d %lu %d %pK %lu %lu %u %u %d",
  2029. i, src, srcp, dest, destp, state,
  2030. READ_ONCE(tp->write_seq) - tp->snd_una,
  2031. rx_queue,
  2032. timer_active,
  2033. jiffies_delta_to_clock_t(timer_expires - jiffies),
  2034. icsk->icsk_retransmits,
  2035. from_kuid_munged(seq_user_ns(f), sock_i_uid(sk)),
  2036. icsk->icsk_probes_out,
  2037. sock_i_ino(sk),
  2038. refcount_read(&sk->sk_refcnt), sk,
  2039. jiffies_to_clock_t(icsk->icsk_rto),
  2040. jiffies_to_clock_t(icsk->icsk_ack.ato),
  2041. (icsk->icsk_ack.quick << 1) | icsk->icsk_ack.pingpong,
  2042. tp->snd_cwnd,
  2043. state == TCP_LISTEN ?
  2044. fastopenq->max_qlen :
  2045. (tcp_in_initial_slowstart(tp) ? -1 : tp->snd_ssthresh));
  2046. }
  2047. static void get_timewait4_sock(const struct inet_timewait_sock *tw,
  2048. struct seq_file *f, int i)
  2049. {
  2050. long delta = tw->tw_timer.expires - jiffies;
  2051. __be32 dest, src;
  2052. __u16 destp, srcp;
  2053. dest = tw->tw_daddr;
  2054. src = tw->tw_rcv_saddr;
  2055. destp = ntohs(tw->tw_dport);
  2056. srcp = ntohs(tw->tw_sport);
  2057. seq_printf(f, "%4d: %08X:%04X %08X:%04X"
  2058. " %02X %08X:%08X %02X:%08lX %08X %5d %8d %d %d %pK",
  2059. i, src, srcp, dest, destp, tw->tw_substate, 0, 0,
  2060. 3, jiffies_delta_to_clock_t(delta), 0, 0, 0, 0,
  2061. refcount_read(&tw->tw_refcnt), tw);
  2062. }
  2063. #define TMPSZ 150
  2064. static int tcp4_seq_show(struct seq_file *seq, void *v)
  2065. {
  2066. struct tcp_iter_state *st;
  2067. struct sock *sk = v;
  2068. seq_setwidth(seq, TMPSZ - 1);
  2069. if (v == SEQ_START_TOKEN) {
  2070. seq_puts(seq, " sl local_address rem_address st tx_queue "
  2071. "rx_queue tr tm->when retrnsmt uid timeout "
  2072. "inode");
  2073. goto out;
  2074. }
  2075. st = seq->private;
  2076. if (sk->sk_state == TCP_TIME_WAIT)
  2077. get_timewait4_sock(v, seq, st->num);
  2078. else if (sk->sk_state == TCP_NEW_SYN_RECV)
  2079. get_openreq4(v, seq, st->num);
  2080. else
  2081. get_tcp4_sock(v, seq, st->num);
  2082. out:
  2083. seq_pad(seq, '\n');
  2084. return 0;
  2085. }
  2086. static const struct seq_operations tcp4_seq_ops = {
  2087. .show = tcp4_seq_show,
  2088. .start = tcp_seq_start,
  2089. .next = tcp_seq_next,
  2090. .stop = tcp_seq_stop,
  2091. };
  2092. static struct tcp_seq_afinfo tcp4_seq_afinfo = {
  2093. .family = AF_INET,
  2094. };
  2095. static int __net_init tcp4_proc_init_net(struct net *net)
  2096. {
  2097. if (!proc_create_net_data("tcp", 0444, net->proc_net, &tcp4_seq_ops,
  2098. sizeof(struct tcp_iter_state), &tcp4_seq_afinfo))
  2099. return -ENOMEM;
  2100. return 0;
  2101. }
  2102. static void __net_exit tcp4_proc_exit_net(struct net *net)
  2103. {
  2104. remove_proc_entry("tcp", net->proc_net);
  2105. }
  2106. static struct pernet_operations tcp4_net_ops = {
  2107. .init = tcp4_proc_init_net,
  2108. .exit = tcp4_proc_exit_net,
  2109. };
  2110. int __init tcp4_proc_init(void)
  2111. {
  2112. return register_pernet_subsys(&tcp4_net_ops);
  2113. }
  2114. void tcp4_proc_exit(void)
  2115. {
  2116. unregister_pernet_subsys(&tcp4_net_ops);
  2117. }
  2118. #endif /* CONFIG_PROC_FS */
  2119. struct proto tcp_prot = {
  2120. .name = "TCP",
  2121. .owner = THIS_MODULE,
  2122. .close = tcp_close,
  2123. .pre_connect = tcp_v4_pre_connect,
  2124. .connect = tcp_v4_connect,
  2125. .disconnect = tcp_disconnect,
  2126. .accept = inet_csk_accept,
  2127. .ioctl = tcp_ioctl,
  2128. .init = tcp_v4_init_sock,
  2129. .destroy = tcp_v4_destroy_sock,
  2130. .shutdown = tcp_shutdown,
  2131. .setsockopt = tcp_setsockopt,
  2132. .getsockopt = tcp_getsockopt,
  2133. .keepalive = tcp_set_keepalive,
  2134. .recvmsg = tcp_recvmsg,
  2135. .sendmsg = tcp_sendmsg,
  2136. .sendpage = tcp_sendpage,
  2137. .backlog_rcv = tcp_v4_do_rcv,
  2138. .release_cb = tcp_release_cb,
  2139. .hash = inet_hash,
  2140. .unhash = inet_unhash,
  2141. .get_port = inet_csk_get_port,
  2142. .enter_memory_pressure = tcp_enter_memory_pressure,
  2143. .leave_memory_pressure = tcp_leave_memory_pressure,
  2144. .stream_memory_free = tcp_stream_memory_free,
  2145. .sockets_allocated = &tcp_sockets_allocated,
  2146. .orphan_count = &tcp_orphan_count,
  2147. .memory_allocated = &tcp_memory_allocated,
  2148. .memory_pressure = &tcp_memory_pressure,
  2149. .sysctl_mem = sysctl_tcp_mem,
  2150. .sysctl_wmem_offset = offsetof(struct net, ipv4.sysctl_tcp_wmem),
  2151. .sysctl_rmem_offset = offsetof(struct net, ipv4.sysctl_tcp_rmem),
  2152. .max_header = MAX_TCP_HEADER,
  2153. .obj_size = sizeof(struct tcp_sock),
  2154. .slab_flags = SLAB_TYPESAFE_BY_RCU,
  2155. .twsk_prot = &tcp_timewait_sock_ops,
  2156. .rsk_prot = &tcp_request_sock_ops,
  2157. .h.hashinfo = &tcp_hashinfo,
  2158. .no_autobind = true,
  2159. #ifdef CONFIG_COMPAT
  2160. .compat_setsockopt = compat_tcp_setsockopt,
  2161. .compat_getsockopt = compat_tcp_getsockopt,
  2162. #endif
  2163. .diag_destroy = tcp_abort,
  2164. };
  2165. EXPORT_SYMBOL(tcp_prot);
  2166. static void __net_exit tcp_sk_exit(struct net *net)
  2167. {
  2168. int cpu;
  2169. if (net->ipv4.tcp_congestion_control)
  2170. module_put(net->ipv4.tcp_congestion_control->owner);
  2171. for_each_possible_cpu(cpu)
  2172. inet_ctl_sock_destroy(*per_cpu_ptr(net->ipv4.tcp_sk, cpu));
  2173. free_percpu(net->ipv4.tcp_sk);
  2174. }
  2175. static int __net_init tcp_sk_init(struct net *net)
  2176. {
  2177. int res, cpu, cnt;
  2178. net->ipv4.tcp_sk = alloc_percpu(struct sock *);
  2179. if (!net->ipv4.tcp_sk)
  2180. return -ENOMEM;
  2181. for_each_possible_cpu(cpu) {
  2182. struct sock *sk;
  2183. res = inet_ctl_sock_create(&sk, PF_INET, SOCK_RAW,
  2184. IPPROTO_TCP, net);
  2185. if (res)
  2186. goto fail;
  2187. sock_set_flag(sk, SOCK_USE_WRITE_QUEUE);
  2188. /* Please enforce IP_DF and IPID==0 for RST and
  2189. * ACK sent in SYN-RECV and TIME-WAIT state.
  2190. */
  2191. inet_sk(sk)->pmtudisc = IP_PMTUDISC_DO;
  2192. *per_cpu_ptr(net->ipv4.tcp_sk, cpu) = sk;
  2193. }
  2194. net->ipv4.sysctl_tcp_ecn = 2;
  2195. net->ipv4.sysctl_tcp_ecn_fallback = 1;
  2196. net->ipv4.sysctl_tcp_base_mss = TCP_BASE_MSS;
  2197. net->ipv4.sysctl_tcp_min_snd_mss = TCP_MIN_SND_MSS;
  2198. net->ipv4.sysctl_tcp_probe_threshold = TCP_PROBE_THRESHOLD;
  2199. net->ipv4.sysctl_tcp_probe_interval = TCP_PROBE_INTERVAL;
  2200. net->ipv4.sysctl_tcp_keepalive_time = TCP_KEEPALIVE_TIME;
  2201. net->ipv4.sysctl_tcp_keepalive_probes = TCP_KEEPALIVE_PROBES;
  2202. net->ipv4.sysctl_tcp_keepalive_intvl = TCP_KEEPALIVE_INTVL;
  2203. net->ipv4.sysctl_tcp_syn_retries = TCP_SYN_RETRIES;
  2204. net->ipv4.sysctl_tcp_synack_retries = TCP_SYNACK_RETRIES;
  2205. net->ipv4.sysctl_tcp_syncookies = 1;
  2206. net->ipv4.sysctl_tcp_reordering = TCP_FASTRETRANS_THRESH;
  2207. net->ipv4.sysctl_tcp_retries1 = TCP_RETR1;
  2208. net->ipv4.sysctl_tcp_retries2 = TCP_RETR2;
  2209. net->ipv4.sysctl_tcp_orphan_retries = 0;
  2210. net->ipv4.sysctl_tcp_fin_timeout = TCP_FIN_TIMEOUT;
  2211. net->ipv4.sysctl_tcp_notsent_lowat = UINT_MAX;
  2212. net->ipv4.sysctl_tcp_tw_reuse = 2;
  2213. cnt = tcp_hashinfo.ehash_mask + 1;
  2214. net->ipv4.tcp_death_row.sysctl_max_tw_buckets = (cnt + 1) / 2;
  2215. net->ipv4.tcp_death_row.hashinfo = &tcp_hashinfo;
  2216. net->ipv4.sysctl_max_syn_backlog = max(128, cnt / 256);
  2217. net->ipv4.sysctl_tcp_sack = 1;
  2218. net->ipv4.sysctl_tcp_window_scaling = 1;
  2219. net->ipv4.sysctl_tcp_timestamps = 1;
  2220. net->ipv4.sysctl_tcp_early_retrans = 3;
  2221. net->ipv4.sysctl_tcp_recovery = TCP_RACK_LOSS_DETECTION;
  2222. net->ipv4.sysctl_tcp_slow_start_after_idle = 1; /* By default, RFC2861 behavior. */
  2223. net->ipv4.sysctl_tcp_retrans_collapse = 1;
  2224. net->ipv4.sysctl_tcp_max_reordering = 300;
  2225. net->ipv4.sysctl_tcp_dsack = 1;
  2226. net->ipv4.sysctl_tcp_app_win = 31;
  2227. net->ipv4.sysctl_tcp_adv_win_scale = 1;
  2228. net->ipv4.sysctl_tcp_frto = 2;
  2229. net->ipv4.sysctl_tcp_moderate_rcvbuf = 1;
  2230. /* This limits the percentage of the congestion window which we
  2231. * will allow a single TSO frame to consume. Building TSO frames
  2232. * which are too large can cause TCP streams to be bursty.
  2233. */
  2234. net->ipv4.sysctl_tcp_tso_win_divisor = 3;
  2235. /* Default TSQ limit of four TSO segments */
  2236. net->ipv4.sysctl_tcp_limit_output_bytes = 262144;
  2237. /* rfc5961 challenge ack rate limiting */
  2238. net->ipv4.sysctl_tcp_challenge_ack_limit = 1000;
  2239. net->ipv4.sysctl_tcp_min_tso_segs = 2;
  2240. net->ipv4.sysctl_tcp_min_rtt_wlen = 300;
  2241. net->ipv4.sysctl_tcp_autocorking = 1;
  2242. net->ipv4.sysctl_tcp_invalid_ratelimit = HZ/2;
  2243. net->ipv4.sysctl_tcp_pacing_ss_ratio = 200;
  2244. net->ipv4.sysctl_tcp_pacing_ca_ratio = 120;
  2245. if (net != &init_net) {
  2246. memcpy(net->ipv4.sysctl_tcp_rmem,
  2247. init_net.ipv4.sysctl_tcp_rmem,
  2248. sizeof(init_net.ipv4.sysctl_tcp_rmem));
  2249. memcpy(net->ipv4.sysctl_tcp_wmem,
  2250. init_net.ipv4.sysctl_tcp_wmem,
  2251. sizeof(init_net.ipv4.sysctl_tcp_wmem));
  2252. }
  2253. net->ipv4.sysctl_tcp_comp_sack_delay_ns = NSEC_PER_MSEC;
  2254. net->ipv4.sysctl_tcp_comp_sack_nr = 44;
  2255. net->ipv4.sysctl_tcp_fastopen = TFO_CLIENT_ENABLE;
  2256. spin_lock_init(&net->ipv4.tcp_fastopen_ctx_lock);
  2257. net->ipv4.sysctl_tcp_fastopen_blackhole_timeout = 60 * 60;
  2258. atomic_set(&net->ipv4.tfo_active_disable_times, 0);
  2259. /* Reno is always built in */
  2260. if (!net_eq(net, &init_net) &&
  2261. try_module_get(init_net.ipv4.tcp_congestion_control->owner))
  2262. net->ipv4.tcp_congestion_control = init_net.ipv4.tcp_congestion_control;
  2263. else
  2264. net->ipv4.tcp_congestion_control = &tcp_reno;
  2265. return 0;
  2266. fail:
  2267. tcp_sk_exit(net);
  2268. return res;
  2269. }
  2270. static void __net_exit tcp_sk_exit_batch(struct list_head *net_exit_list)
  2271. {
  2272. struct net *net;
  2273. inet_twsk_purge(&tcp_hashinfo, AF_INET);
  2274. list_for_each_entry(net, net_exit_list, exit_list)
  2275. tcp_fastopen_ctx_destroy(net);
  2276. }
  2277. static struct pernet_operations __net_initdata tcp_sk_ops = {
  2278. .init = tcp_sk_init,
  2279. .exit = tcp_sk_exit,
  2280. .exit_batch = tcp_sk_exit_batch,
  2281. };
  2282. void __init tcp_v4_init(void)
  2283. {
  2284. if (register_pernet_subsys(&tcp_sk_ops))
  2285. panic("Failed to create the TCP control socket.\n");
  2286. }