1/*
2 * tcp_diag.c	Module for monitoring TCP sockets.
3 *
4 * Version:	$Id: tcp_diag.c,v 1.1.1.1 2008/10/15 03:27:33 james26_jang Exp $
5 *
6 * Authors:	Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
7 *
8 *	This program is free software; you can redistribute it and/or
9 *      modify it under the terms of the GNU General Public License
10 *      as published by the Free Software Foundation; either version
11 *      2 of the License, or (at your option) any later version.
12 */
13
14#include <linux/config.h>
15#include <linux/module.h>
16#include <linux/types.h>
17#include <linux/fcntl.h>
18#include <linux/random.h>
19#include <linux/cache.h>
20#include <linux/init.h>
21
22#include <net/icmp.h>
23#include <net/tcp.h>
24#include <net/ipv6.h>
25#include <net/inet_common.h>
26
27#include <linux/inet.h>
28#include <linux/stddef.h>
29
30#include <linux/tcp_diag.h>
31
32static struct sock *tcpnl;
33
34
35#define TCPDIAG_PUT(skb, attrtype, attrlen) \
36({ int rtalen = RTA_LENGTH(attrlen);        \
37   struct rtattr *rta;                      \
38   if (skb_tailroom(skb) < RTA_ALIGN(rtalen)) goto nlmsg_failure; \
39   rta = (void*)__skb_put(skb, RTA_ALIGN(rtalen)); \
40   rta->rta_type = attrtype;                \
41   rta->rta_len = rtalen;                   \
42   RTA_DATA(rta); })
43
44static int tcpdiag_fill(struct sk_buff *skb, struct sock *sk,
45			int ext, u32 pid, u32 seq)
46{
47	struct tcp_opt *tp = &sk->tp_pinfo.af_tcp;
48	struct tcpdiagmsg *r;
49	struct nlmsghdr  *nlh;
50	struct tcp_info  *info = NULL;
51	struct tcpdiag_meminfo  *minfo = NULL;
52	unsigned char	 *b = skb->tail;
53
54	nlh = NLMSG_PUT(skb, pid, seq, TCPDIAG_GETSOCK, sizeof(*r));
55	r = NLMSG_DATA(nlh);
56	if (sk->state != TCP_TIME_WAIT) {
57		if (ext & (1<<(TCPDIAG_MEMINFO-1)))
58			minfo = TCPDIAG_PUT(skb, TCPDIAG_MEMINFO, sizeof(*minfo));
59		if (ext & (1<<(TCPDIAG_INFO-1)))
60			info = TCPDIAG_PUT(skb, TCPDIAG_INFO, sizeof(*info));
61	}
62	r->tcpdiag_family = sk->family;
63	r->tcpdiag_state = sk->state;
64	r->tcpdiag_timer = 0;
65	r->tcpdiag_retrans = 0;
66
67	r->id.tcpdiag_sport = sk->sport;
68	r->id.tcpdiag_dport = sk->dport;
69	r->id.tcpdiag_src[0] = sk->rcv_saddr;
70	r->id.tcpdiag_dst[0] = sk->daddr;
71	r->id.tcpdiag_if = sk->bound_dev_if;
72	r->id.tcpdiag_cookie[0] = (u32)(unsigned long)sk;
73	r->id.tcpdiag_cookie[1] = (u32)(((unsigned long)sk >> 31) >> 1);
74
75	if (r->tcpdiag_state == TCP_TIME_WAIT) {
76		struct tcp_tw_bucket *tw = (struct tcp_tw_bucket*)sk;
77		long tmo = tw->ttd - jiffies;
78		if (tmo < 0)
79			tmo = 0;
80
81		r->tcpdiag_state = tw->substate;
82		r->tcpdiag_timer = 3;
83		r->tcpdiag_expires = (tmo*1000+HZ-1)/HZ;
84		r->tcpdiag_rqueue = 0;
85		r->tcpdiag_wqueue = 0;
86		r->tcpdiag_uid = 0;
87		r->tcpdiag_inode = 0;
88#ifdef CONFIG_IPV6
89		if (r->tcpdiag_family == AF_INET6) {
90			memcpy(r->id.tcpdiag_src, &tw->v6_rcv_saddr, 16);
91			memcpy(r->id.tcpdiag_dst, &tw->v6_daddr, 16);
92		}
93#endif
94		nlh->nlmsg_len = skb->tail - b;
95		return skb->len;
96	}
97
98#ifdef CONFIG_IPV6
99	if (r->tcpdiag_family == AF_INET6) {
100		memcpy(r->id.tcpdiag_src, &sk->net_pinfo.af_inet6.rcv_saddr, 16);
101		memcpy(r->id.tcpdiag_dst, &sk->net_pinfo.af_inet6.daddr, 16);
102	}
103#endif
104
105#define EXPIRES_IN_MS(tmo)  ((tmo-jiffies)*1000+HZ-1)/HZ
106
107	if (tp->pending == TCP_TIME_RETRANS) {
108		r->tcpdiag_timer = 1;
109		r->tcpdiag_retrans = tp->retransmits;
110		r->tcpdiag_expires = EXPIRES_IN_MS(tp->timeout);
111	} else if (tp->pending == TCP_TIME_PROBE0) {
112		r->tcpdiag_timer = 4;
113		r->tcpdiag_retrans = tp->probes_out;
114		r->tcpdiag_expires = EXPIRES_IN_MS(tp->timeout);
115	} else if (timer_pending(&sk->timer)) {
116		r->tcpdiag_timer = 2;
117		r->tcpdiag_retrans = tp->probes_out;
118		r->tcpdiag_expires = EXPIRES_IN_MS(sk->timer.expires);
119	} else {
120		r->tcpdiag_timer = 0;
121		r->tcpdiag_expires = 0;
122	}
123#undef EXPIRES_IN_MS
124
125	r->tcpdiag_rqueue = tp->rcv_nxt - tp->copied_seq;
126	r->tcpdiag_wqueue = tp->write_seq - tp->snd_una;
127	r->tcpdiag_uid = sock_i_uid(sk);
128	r->tcpdiag_inode = sock_i_ino(sk);
129
130	if (minfo) {
131		minfo->tcpdiag_rmem = atomic_read(&sk->rmem_alloc);
132		minfo->tcpdiag_wmem = sk->wmem_queued;
133		minfo->tcpdiag_fmem = sk->forward_alloc;
134		minfo->tcpdiag_tmem = atomic_read(&sk->wmem_alloc);
135	}
136
137	if (info) {
138		u32 now = tcp_time_stamp;
139
140		info->tcpi_state = sk->state;
141		info->tcpi_ca_state = tp->ca_state;
142		info->tcpi_retransmits = tp->retransmits;
143		info->tcpi_probes = tp->probes_out;
144		info->tcpi_backoff = tp->backoff;
145		info->tcpi_options = 0;
146		if (tp->tstamp_ok)
147			info->tcpi_options |= TCPI_OPT_TIMESTAMPS;
148		if (tp->sack_ok)
149			info->tcpi_options |= TCPI_OPT_SACK;
150		if (tp->wscale_ok) {
151			info->tcpi_options |= TCPI_OPT_WSCALE;
152			info->tcpi_snd_wscale = tp->snd_wscale;
153			info->tcpi_rcv_wscale = tp->rcv_wscale;
154		} else {
155			info->tcpi_snd_wscale = 0;
156			info->tcpi_rcv_wscale = 0;
157		}
158#ifdef CONFIG_INET_ECN
159		if (tp->ecn_flags&TCP_ECN_OK)
160			info->tcpi_options |= TCPI_OPT_ECN;
161#endif
162
163		info->tcpi_rto = (1000000*tp->rto)/HZ;
164		info->tcpi_ato = (1000000*tp->ack.ato)/HZ;
165		info->tcpi_snd_mss = tp->mss_cache;
166		info->tcpi_rcv_mss = tp->ack.rcv_mss;
167
168		info->tcpi_unacked = tp->packets_out;
169		info->tcpi_sacked = tp->sacked_out;
170		info->tcpi_lost = tp->lost_out;
171		info->tcpi_retrans = tp->retrans_out;
172		info->tcpi_fackets = tp->fackets_out;
173
174		info->tcpi_last_data_sent = ((now - tp->lsndtime)*1000)/HZ;
175		info->tcpi_last_ack_sent = 0;
176		info->tcpi_last_data_recv = ((now - tp->ack.lrcvtime)*1000)/HZ;
177		info->tcpi_last_ack_recv = ((now - tp->rcv_tstamp)*1000)/HZ;
178
179		info->tcpi_pmtu = tp->pmtu_cookie;
180		info->tcpi_rcv_ssthresh = tp->rcv_ssthresh;
181		info->tcpi_rtt = ((1000000*tp->srtt)/HZ)>>3;
182		info->tcpi_rttvar = ((1000000*tp->mdev)/HZ)>>2;
183		info->tcpi_snd_ssthresh = tp->snd_ssthresh;
184		info->tcpi_snd_cwnd = tp->snd_cwnd;
185		info->tcpi_advmss = tp->advmss;
186		info->tcpi_reordering = tp->reordering;
187	}
188
189	nlh->nlmsg_len = skb->tail - b;
190	return skb->len;
191
192nlmsg_failure:
193	skb_trim(skb, b - skb->data);
194	return -1;
195}
196
197extern struct sock *tcp_v4_lookup(u32 saddr, u16 sport, u32 daddr, u16 dport, int dif);
198#ifdef CONFIG_IPV6
199extern struct sock *tcp_v6_lookup(struct in6_addr *saddr, u16 sport,
200				  struct in6_addr *daddr, u16 dport,
201				  int dif);
202#endif
203
204static int tcpdiag_get_exact(struct sk_buff *in_skb, struct nlmsghdr *nlh)
205{
206	int err;
207	struct sock *sk;
208	struct tcpdiagreq *req = NLMSG_DATA(nlh);
209	struct sk_buff *rep;
210
211	if (req->tcpdiag_family == AF_INET) {
212		sk = tcp_v4_lookup(req->id.tcpdiag_dst[0], req->id.tcpdiag_dport,
213				   req->id.tcpdiag_src[0], req->id.tcpdiag_sport,
214				   req->id.tcpdiag_if);
215	}
216#ifdef CONFIG_IPV6
217	else if (req->tcpdiag_family == AF_INET6) {
218		sk = tcp_v6_lookup((struct in6_addr*)req->id.tcpdiag_dst, req->id.tcpdiag_dport,
219				   (struct in6_addr*)req->id.tcpdiag_src, req->id.tcpdiag_sport,
220				   req->id.tcpdiag_if);
221	}
222#endif
223	else {
224		return -EINVAL;
225	}
226
227	if (sk == NULL)
228		return -ENOENT;
229
230	err = -ESTALE;
231	if ((req->id.tcpdiag_cookie[0] != TCPDIAG_NOCOOKIE ||
232	     req->id.tcpdiag_cookie[1] != TCPDIAG_NOCOOKIE) &&
233	    ((u32)(unsigned long)sk != req->id.tcpdiag_cookie[0] ||
234	     (u32)((((unsigned long)sk) >> 31) >> 1) != req->id.tcpdiag_cookie[1]))
235		goto out;
236
237	err = -ENOMEM;
238	rep = alloc_skb(NLMSG_SPACE(sizeof(struct tcpdiagmsg)+
239				    sizeof(struct tcpdiag_meminfo)+
240				    sizeof(struct tcp_info)+64), GFP_KERNEL);
241	if (!rep)
242		goto out;
243
244	if (tcpdiag_fill(rep, sk, req->tcpdiag_ext,
245			 NETLINK_CB(in_skb).pid,
246			 nlh->nlmsg_seq) <= 0)
247		BUG();
248
249	err = netlink_unicast(tcpnl, rep, NETLINK_CB(in_skb).pid, MSG_DONTWAIT);
250	if (err > 0)
251		err = 0;
252
253out:
254	if (sk) {
255		if (sk->state == TCP_TIME_WAIT)
256			tcp_tw_put((struct tcp_tw_bucket*)sk);
257		else
258			sock_put(sk);
259	}
260	return err;
261}
262
263int bitstring_match(u32 *a1, u32 *a2, int bits)
264{
265	int words = bits >> 5;
266
267	bits &= 0x1f;
268
269	if (words) {
270		if (memcmp(a1, a2, words << 2))
271			return 0;
272	}
273	if (bits) {
274		__u32 w1, w2;
275		__u32 mask;
276
277		w1 = a1[words];
278		w2 = a2[words];
279
280		mask = htonl((0xffffffff) << (32 - bits));
281
282		if ((w1 ^ w2) & mask)
283			return 0;
284	}
285
286	return 1;
287}
288
289
290int tcpdiag_bc_run(char *bc, int len, struct sock *sk)
291{
292	while (len > 0) {
293		int yes = 1;
294		struct tcpdiag_bc_op *op = (struct tcpdiag_bc_op*)bc;
295
296		switch (op->code) {
297		case TCPDIAG_BC_NOP:
298			break;
299		case TCPDIAG_BC_JMP:
300			yes = 0;
301			break;
302		case TCPDIAG_BC_S_GE:
303			yes = (sk->num >= op[1].no);
304			break;
305		case TCPDIAG_BC_S_LE:
306			yes = (sk->num <= op[1].no);
307			break;
308		case TCPDIAG_BC_D_GE:
309			yes = (ntohs(sk->dport) >= op[1].no);
310			break;
311		case TCPDIAG_BC_D_LE:
312			yes = (ntohs(sk->dport) <= op[1].no);
313			break;
314		case TCPDIAG_BC_AUTO:
315			yes = !(sk->userlocks&SOCK_BINDPORT_LOCK);
316			break;
317		case TCPDIAG_BC_S_COND:
318		case TCPDIAG_BC_D_COND:
319		{
320			struct tcpdiag_hostcond *cond = (struct tcpdiag_hostcond*)(op+1);
321			u32 *addr;
322
323			if (cond->port != -1 &&
324			    cond->port != (op->code == TCPDIAG_BC_S_COND ? sk->num : ntohs(sk->dport))) {
325				yes = 0;
326				break;
327			}
328
329			if (cond->prefix_len == 0)
330				break;
331
332#ifdef CONFIG_IPV6
333			if (sk->family == AF_INET6) {
334				if (op->code == TCPDIAG_BC_S_COND)
335					addr = (u32*)&sk->net_pinfo.af_inet6.rcv_saddr;
336				else
337					addr = (u32*)&sk->net_pinfo.af_inet6.daddr;
338			} else
339#endif
340			{
341				if (op->code == TCPDIAG_BC_S_COND)
342					addr = &sk->rcv_saddr;
343				else
344					addr = &sk->daddr;
345			}
346
347			if (bitstring_match(addr, cond->addr, cond->prefix_len))
348				break;
349			if (sk->family == AF_INET6 && cond->family == AF_INET) {
350				if (addr[0] == 0 && addr[1] == 0 &&
351				    addr[2] == htonl(0xffff) &&
352				    bitstring_match(addr+3, cond->addr, cond->prefix_len))
353					break;
354			}
355			yes = 0;
356			break;
357		}
358		}
359
360		if (yes) {
361			len -= op->yes;
362			bc += op->yes;
363		} else {
364			len -= op->no;
365			bc += op->no;
366		}
367	}
368	return (len == 0);
369}
370
371int valid_cc(char *bc, int len, int cc)
372{
373	while (len >= 0) {
374		struct tcpdiag_bc_op *op = (struct tcpdiag_bc_op*)bc;
375
376		if (cc > len)
377			return 0;
378		if (cc == len)
379			return 1;
380		if (op->yes < 4)
381			return 0;
382		len -= op->yes;
383		bc  += op->yes;
384	}
385	return 0;
386}
387
388int tcpdiag_bc_audit(char *bytecode, int bytecode_len)
389{
390	char *bc = bytecode;
391	int  len = bytecode_len;
392
393	while (len > 0) {
394		struct tcpdiag_bc_op *op = (struct tcpdiag_bc_op*)bc;
395
396//printk("BC: %d %d %d {%d} / %d\n", op->code, op->yes, op->no, op[1].no, len);
397		switch (op->code) {
398		case TCPDIAG_BC_AUTO:
399		case TCPDIAG_BC_S_COND:
400		case TCPDIAG_BC_D_COND:
401		case TCPDIAG_BC_S_GE:
402		case TCPDIAG_BC_S_LE:
403		case TCPDIAG_BC_D_GE:
404		case TCPDIAG_BC_D_LE:
405			if (op->yes < 4 || op->yes > len+4)
406				return -EINVAL;
407		case TCPDIAG_BC_JMP:
408			if (op->no < 4 || op->no > len+4)
409				return -EINVAL;
410			if (op->no < len &&
411			    !valid_cc(bytecode, bytecode_len, len-op->no))
412				return -EINVAL;
413			break;
414		case TCPDIAG_BC_NOP:
415			if (op->yes < 4 || op->yes > len+4)
416				return -EINVAL;
417			break;
418		default:
419			return -EINVAL;
420		}
421		bc += op->yes;
422		len -= op->yes;
423	}
424	return len == 0 ? 0 : -EINVAL;
425}
426
427
428int tcpdiag_dump(struct sk_buff *skb, struct netlink_callback *cb)
429{
430	int i, num;
431	int s_i, s_num;
432	struct tcpdiagreq *r = NLMSG_DATA(cb->nlh);
433	struct rtattr *bc = NULL;
434
435	if (cb->nlh->nlmsg_len > 4+NLMSG_SPACE(sizeof(struct tcpdiagreq)))
436		bc = (struct rtattr*)(r+1);
437
438	s_i = cb->args[1];
439	s_num = num = cb->args[2];
440
441	if (cb->args[0] == 0) {
442		if (!(r->tcpdiag_states&(TCPF_LISTEN|TCPF_SYN_RECV)))
443			goto skip_listen_ht;
444		tcp_listen_lock();
445		for (i = s_i; i < TCP_LHTABLE_SIZE; i++) {
446			struct sock *sk = tcp_listening_hash[i];
447
448			if (i > s_i)
449				s_num = 0;
450
451			for (sk = tcp_listening_hash[i], num = 0;
452			     sk != NULL;
453			     sk = sk->next, num++) {
454				if (num < s_num)
455					continue;
456				if (!(r->tcpdiag_states&TCPF_LISTEN) ||
457				    r->id.tcpdiag_dport)
458					continue;
459				if (r->id.tcpdiag_sport != sk->sport && r->id.tcpdiag_sport)
460					continue;
461				if (bc && !tcpdiag_bc_run(RTA_DATA(bc), RTA_PAYLOAD(bc), sk))
462					continue;
463				if (tcpdiag_fill(skb, sk, r->tcpdiag_ext,
464						 NETLINK_CB(cb->skb).pid,
465						 cb->nlh->nlmsg_seq) <= 0) {
466					tcp_listen_unlock();
467					goto done;
468				}
469			}
470		}
471		tcp_listen_unlock();
472skip_listen_ht:
473		cb->args[0] = 1;
474		s_i = num = s_num = 0;
475	}
476
477	if (!(r->tcpdiag_states&~(TCPF_LISTEN|TCPF_SYN_RECV)))
478		return skb->len;
479
480	for (i = s_i; i < tcp_ehash_size; i++) {
481		struct tcp_ehash_bucket *head = &tcp_ehash[i];
482		struct sock *sk;
483
484		if (i > s_i)
485			s_num = 0;
486
487		read_lock_bh(&head->lock);
488
489		for (sk = head->chain, num = 0;
490		     sk != NULL;
491		     sk = sk->next, num++) {
492			if (num < s_num)
493				continue;
494			if (!(r->tcpdiag_states&(1<<sk->state)))
495				continue;
496			if (r->id.tcpdiag_sport != sk->sport && r->id.tcpdiag_sport)
497				continue;
498			if (r->id.tcpdiag_dport != sk->dport && r->id.tcpdiag_dport)
499				continue;
500			if (bc && !tcpdiag_bc_run(RTA_DATA(bc), RTA_PAYLOAD(bc), sk))
501				continue;
502			if (tcpdiag_fill(skb, sk, r->tcpdiag_ext,
503					 NETLINK_CB(cb->skb).pid,
504					 cb->nlh->nlmsg_seq) <= 0) {
505				read_unlock_bh(&head->lock);
506				goto done;
507			}
508		}
509
510		if (r->tcpdiag_states&TCPF_TIME_WAIT) {
511			for (sk = tcp_ehash[i+tcp_ehash_size].chain;
512			     sk != NULL;
513			     sk = sk->next, num++) {
514				if (num < s_num)
515					continue;
516				if (!(r->tcpdiag_states&(1<<sk->zapped)))
517					continue;
518				if (r->id.tcpdiag_sport != sk->sport && r->id.tcpdiag_sport)
519					continue;
520				if (r->id.tcpdiag_dport != sk->dport && r->id.tcpdiag_dport)
521					continue;
522				if (bc && !tcpdiag_bc_run(RTA_DATA(bc), RTA_PAYLOAD(bc), sk))
523					continue;
524				if (tcpdiag_fill(skb, sk, r->tcpdiag_ext,
525						 NETLINK_CB(cb->skb).pid,
526						 cb->nlh->nlmsg_seq) <= 0) {
527					read_unlock_bh(&head->lock);
528					goto done;
529				}
530			}
531		}
532		read_unlock_bh(&head->lock);
533	}
534
535done:
536	cb->args[1] = i;
537	cb->args[2] = num;
538	return skb->len;
539}
540
541static int tcpdiag_dump_done(struct netlink_callback *cb)
542{
543	return 0;
544}
545
546
547static __inline__ int
548tcpdiag_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh)
549{
550	if (!(nlh->nlmsg_flags&NLM_F_REQUEST))
551		return 0;
552
553	if (nlh->nlmsg_type != TCPDIAG_GETSOCK)
554		goto err_inval;
555
556	if (NLMSG_LENGTH(sizeof(struct tcpdiagreq)) > skb->len)
557		goto err_inval;
558
559	if (nlh->nlmsg_flags&NLM_F_DUMP) {
560		if (nlh->nlmsg_len > 4 + NLMSG_SPACE(sizeof(struct tcpdiagreq))) {
561			struct rtattr *rta = (struct rtattr*)(NLMSG_DATA(nlh) + sizeof(struct tcpdiagreq));
562			if (rta->rta_type != TCPDIAG_REQ_BYTECODE ||
563			    rta->rta_len < 8 ||
564			    rta->rta_len > nlh->nlmsg_len - NLMSG_SPACE(sizeof(struct tcpdiagreq)))
565				goto err_inval;
566			if (tcpdiag_bc_audit(RTA_DATA(rta), RTA_PAYLOAD(rta)))
567				goto err_inval;
568		}
569		return netlink_dump_start(tcpnl, skb, nlh,
570					  tcpdiag_dump,
571					  tcpdiag_dump_done);
572	} else {
573		return tcpdiag_get_exact(skb, nlh);
574	}
575
576err_inval:
577	return -EINVAL;
578}
579
580
581extern __inline__ void tcpdiag_rcv_skb(struct sk_buff *skb)
582{
583	int err;
584	struct nlmsghdr * nlh;
585
586	if (skb->len >= NLMSG_SPACE(0)) {
587		nlh = (struct nlmsghdr *)skb->data;
588		if (nlh->nlmsg_len < sizeof(*nlh) || skb->len < nlh->nlmsg_len)
589			return;
590		err = tcpdiag_rcv_msg(skb, nlh);
591		if (err)
592			netlink_ack(skb, nlh, err);
593	}
594}
595
596static void tcpdiag_rcv(struct sock *sk, int len)
597{
598	struct sk_buff *skb;
599
600	while ((skb = skb_dequeue(&sk->receive_queue)) != NULL) {
601		tcpdiag_rcv_skb(skb);
602		kfree_skb(skb);
603	}
604}
605
606void __init tcpdiag_init(void)
607{
608	tcpnl = netlink_kernel_create(NETLINK_TCPDIAG, tcpdiag_rcv);
609	if (tcpnl == NULL)
610		panic("tcpdiag_init: Cannot create netlink socket.");
611}
612