1/*
2 * linux/net/netfilter/xt_IDLETIMER.c
3 *
4 * Netfilter module to trigger a timer when packet matches.
5 * After timer expires a kevent will be sent.
6 *
7 * Copyright (C) 2004, 2010 Nokia Corporation
8 *
9 * Written by Timo Teras <ext-timo.teras@nokia.com>
10 *
11 * Converted to x_tables and reworked for upstream inclusion
12 * by Luciano Coelho <luciano.coelho@nokia.com>
13 *
14 * Contact: Luciano Coelho <luciano.coelho@nokia.com>
15 *
16 * This program is free software; you can redistribute it and/or
17 * modify it under the terms of the GNU General Public License
18 * version 2 as published by the Free Software Foundation.
19 *
20 * This program is distributed in the hope that it will be useful, but
21 * WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
23 * General Public License for more details.
24 *
25 * You should have received a copy of the GNU General Public License
26 * along with this program; if not, write to the Free Software
27 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
28 * 02110-1301 USA
29 */
30
31#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
32
33#include <linux/module.h>
34#include <linux/timer.h>
35#include <linux/list.h>
36#include <linux/mutex.h>
37#include <linux/netfilter.h>
38#include <linux/netfilter/x_tables.h>
39#include <linux/netfilter/xt_IDLETIMER.h>
40#include <linux/kdev_t.h>
41#include <linux/kobject.h>
42#include <linux/skbuff.h>
43#include <linux/workqueue.h>
44#include <linux/sysfs.h>
45#include <linux/rtc.h>
46#include <linux/time.h>
47#include <linux/math64.h>
48#include <linux/suspend.h>
49#include <linux/notifier.h>
50#include <net/net_namespace.h>
51#include <net/sock.h>
52
53struct idletimer_tg_attr {
54	struct attribute attr;
55	ssize_t	(*show)(struct kobject *kobj,
56			struct attribute *attr, char *buf);
57};
58
59struct idletimer_tg {
60	struct list_head entry;
61	struct timer_list timer;
62	struct work_struct work;
63
64	struct kobject *kobj;
65	struct idletimer_tg_attr attr;
66
67	struct timespec delayed_timer_trigger;
68	struct timespec last_modified_timer;
69	struct timespec last_suspend_time;
70	struct notifier_block pm_nb;
71
72	int timeout;
73	unsigned int refcnt;
74	bool work_pending;
75	bool send_nl_msg;
76	bool active;
77	uid_t uid;
78};
79
80static LIST_HEAD(idletimer_tg_list);
81static DEFINE_MUTEX(list_mutex);
82static DEFINE_SPINLOCK(timestamp_lock);
83
84static struct kobject *idletimer_tg_kobj;
85
86static bool check_for_delayed_trigger(struct idletimer_tg *timer,
87		struct timespec *ts)
88{
89	bool state;
90	struct timespec temp;
91	spin_lock_bh(&timestamp_lock);
92	timer->work_pending = false;
93	if ((ts->tv_sec - timer->last_modified_timer.tv_sec) > timer->timeout ||
94			timer->delayed_timer_trigger.tv_sec != 0) {
95		state = false;
96		temp.tv_sec = timer->timeout;
97		temp.tv_nsec = 0;
98		if (timer->delayed_timer_trigger.tv_sec != 0) {
99			temp = timespec_add(timer->delayed_timer_trigger, temp);
100			ts->tv_sec = temp.tv_sec;
101			ts->tv_nsec = temp.tv_nsec;
102			timer->delayed_timer_trigger.tv_sec = 0;
103			timer->work_pending = true;
104			schedule_work(&timer->work);
105		} else {
106			temp = timespec_add(timer->last_modified_timer, temp);
107			ts->tv_sec = temp.tv_sec;
108			ts->tv_nsec = temp.tv_nsec;
109		}
110	} else {
111		state = timer->active;
112	}
113	spin_unlock_bh(&timestamp_lock);
114	return state;
115}
116
117static void notify_netlink_uevent(const char *iface, struct idletimer_tg *timer)
118{
119	char iface_msg[NLMSG_MAX_SIZE];
120	char state_msg[NLMSG_MAX_SIZE];
121	char timestamp_msg[NLMSG_MAX_SIZE];
122	char uid_msg[NLMSG_MAX_SIZE];
123	char *envp[] = { iface_msg, state_msg, timestamp_msg, uid_msg, NULL };
124	int res;
125	struct timespec ts;
126	uint64_t time_ns;
127	bool state;
128
129	res = snprintf(iface_msg, NLMSG_MAX_SIZE, "INTERFACE=%s",
130		       iface);
131	if (NLMSG_MAX_SIZE <= res) {
132		pr_err("message too long (%d)", res);
133		return;
134	}
135
136	get_monotonic_boottime(&ts);
137	state = check_for_delayed_trigger(timer, &ts);
138	res = snprintf(state_msg, NLMSG_MAX_SIZE, "STATE=%s",
139			state ? "active" : "inactive");
140
141	if (NLMSG_MAX_SIZE <= res) {
142		pr_err("message too long (%d)", res);
143		return;
144	}
145
146	if (state) {
147		res = snprintf(uid_msg, NLMSG_MAX_SIZE, "UID=%u", timer->uid);
148		if (NLMSG_MAX_SIZE <= res)
149			pr_err("message too long (%d)", res);
150	} else {
151		res = snprintf(uid_msg, NLMSG_MAX_SIZE, "UID=");
152		if (NLMSG_MAX_SIZE <= res)
153			pr_err("message too long (%d)", res);
154	}
155
156	time_ns = timespec_to_ns(&ts);
157	res = snprintf(timestamp_msg, NLMSG_MAX_SIZE, "TIME_NS=%llu", time_ns);
158	if (NLMSG_MAX_SIZE <= res) {
159		timestamp_msg[0] = '\0';
160		pr_err("message too long (%d)", res);
161	}
162
163	pr_debug("putting nlmsg: <%s> <%s> <%s> <%s>\n", iface_msg, state_msg,
164		 timestamp_msg, uid_msg);
165	kobject_uevent_env(idletimer_tg_kobj, KOBJ_CHANGE, envp);
166	return;
167
168
169}
170
171static
172struct idletimer_tg *__idletimer_tg_find_by_label(const char *label)
173{
174	struct idletimer_tg *entry;
175
176	BUG_ON(!label);
177
178	list_for_each_entry(entry, &idletimer_tg_list, entry) {
179		if (!strcmp(label, entry->attr.attr.name))
180			return entry;
181	}
182
183	return NULL;
184}
185
186static ssize_t idletimer_tg_show(struct kobject *kobj, struct attribute *attr,
187				 char *buf)
188{
189	struct idletimer_tg *timer;
190	unsigned long expires = 0;
191	unsigned long now = jiffies;
192
193	mutex_lock(&list_mutex);
194
195	timer =	__idletimer_tg_find_by_label(attr->name);
196	if (timer)
197		expires = timer->timer.expires;
198
199	mutex_unlock(&list_mutex);
200
201	if (time_after(expires, now))
202		return sprintf(buf, "%u\n",
203			       jiffies_to_msecs(expires - now) / 1000);
204
205	if (timer->send_nl_msg)
206		return sprintf(buf, "0 %d\n",
207			jiffies_to_msecs(now - expires) / 1000);
208	else
209		return sprintf(buf, "0\n");
210}
211
212static void idletimer_tg_work(struct work_struct *work)
213{
214	struct idletimer_tg *timer = container_of(work, struct idletimer_tg,
215						  work);
216
217	sysfs_notify(idletimer_tg_kobj, NULL, timer->attr.attr.name);
218
219	if (timer->send_nl_msg)
220		notify_netlink_uevent(timer->attr.attr.name, timer);
221}
222
223static void idletimer_tg_expired(unsigned long data)
224{
225	struct idletimer_tg *timer = (struct idletimer_tg *) data;
226
227	pr_debug("timer %s expired\n", timer->attr.attr.name);
228	spin_lock_bh(&timestamp_lock);
229	timer->active = false;
230	timer->work_pending = true;
231	schedule_work(&timer->work);
232	spin_unlock_bh(&timestamp_lock);
233}
234
235static int idletimer_resume(struct notifier_block *notifier,
236		unsigned long pm_event, void *unused)
237{
238	struct timespec ts;
239	unsigned long time_diff, now = jiffies;
240	struct idletimer_tg *timer = container_of(notifier,
241			struct idletimer_tg, pm_nb);
242	if (!timer)
243		return NOTIFY_DONE;
244	switch (pm_event) {
245	case PM_SUSPEND_PREPARE:
246		get_monotonic_boottime(&timer->last_suspend_time);
247		break;
248	case PM_POST_SUSPEND:
249		spin_lock_bh(&timestamp_lock);
250		if (!timer->active) {
251			spin_unlock_bh(&timestamp_lock);
252			break;
253		}
254		/* since jiffies are not updated when suspended now represents
255		 * the time it would have suspended */
256		if (time_after(timer->timer.expires, now)) {
257			get_monotonic_boottime(&ts);
258			ts = timespec_sub(ts, timer->last_suspend_time);
259			time_diff = timespec_to_jiffies(&ts);
260			if (timer->timer.expires > (time_diff + now)) {
261				mod_timer_pending(&timer->timer,
262						(timer->timer.expires - time_diff));
263			} else {
264				del_timer(&timer->timer);
265				timer->timer.expires = 0;
266				timer->active = false;
267				timer->work_pending = true;
268				schedule_work(&timer->work);
269			}
270		}
271		spin_unlock_bh(&timestamp_lock);
272		break;
273	default:
274		break;
275	}
276	return NOTIFY_DONE;
277}
278
279static int idletimer_tg_create(struct idletimer_tg_info *info)
280{
281	int ret;
282
283	info->timer = kmalloc(sizeof(*info->timer), GFP_KERNEL);
284	if (!info->timer) {
285		ret = -ENOMEM;
286		goto out;
287	}
288
289	info->timer->attr.attr.name = kstrdup(info->label, GFP_KERNEL);
290	if (!info->timer->attr.attr.name) {
291		ret = -ENOMEM;
292		goto out_free_timer;
293	}
294	info->timer->attr.attr.mode = S_IRUGO;
295	info->timer->attr.show = idletimer_tg_show;
296
297	ret = sysfs_create_file(idletimer_tg_kobj, &info->timer->attr.attr);
298	if (ret < 0) {
299		pr_debug("couldn't add file to sysfs");
300		goto out_free_attr;
301	}
302
303	list_add(&info->timer->entry, &idletimer_tg_list);
304
305	setup_timer(&info->timer->timer, idletimer_tg_expired,
306		    (unsigned long) info->timer);
307	info->timer->refcnt = 1;
308	info->timer->send_nl_msg = (info->send_nl_msg == 0) ? false : true;
309	info->timer->active = true;
310	info->timer->timeout = info->timeout;
311
312	info->timer->delayed_timer_trigger.tv_sec = 0;
313	info->timer->delayed_timer_trigger.tv_nsec = 0;
314	info->timer->work_pending = false;
315	info->timer->uid = 0;
316	get_monotonic_boottime(&info->timer->last_modified_timer);
317
318	info->timer->pm_nb.notifier_call = idletimer_resume;
319	ret = register_pm_notifier(&info->timer->pm_nb);
320	if (ret)
321		printk(KERN_WARNING "[%s] Failed to register pm notifier %d\n",
322				__func__, ret);
323
324	mod_timer(&info->timer->timer,
325		  msecs_to_jiffies(info->timeout * 1000) + jiffies);
326
327	INIT_WORK(&info->timer->work, idletimer_tg_work);
328
329	return 0;
330
331out_free_attr:
332	kfree(info->timer->attr.attr.name);
333out_free_timer:
334	kfree(info->timer);
335out:
336	return ret;
337}
338
339static void reset_timer(const struct idletimer_tg_info *info,
340			struct sk_buff *skb)
341{
342	unsigned long now = jiffies;
343	struct idletimer_tg *timer = info->timer;
344	bool timer_prev;
345
346	spin_lock_bh(&timestamp_lock);
347	timer_prev = timer->active;
348	timer->active = true;
349	/* timer_prev is used to guard overflow problem in time_before*/
350	if (!timer_prev || time_before(timer->timer.expires, now)) {
351		pr_debug("Starting Checkentry timer (Expired, Jiffies): %lu, %lu\n",
352				timer->timer.expires, now);
353
354		/* Stores the uid resposible for waking up the radio */
355		if (skb && (skb->sk)) {
356			struct sock *sk = skb->sk;
357			read_lock_bh(&sk->sk_callback_lock);
358			if ((sk->sk_socket) && (sk->sk_socket->file) &&
359		    (sk->sk_socket->file->f_cred))
360				timer->uid = sk->sk_socket->file->f_cred->uid;
361			read_unlock_bh(&sk->sk_callback_lock);
362		}
363
364		/* checks if there is a pending inactive notification*/
365		if (timer->work_pending)
366			timer->delayed_timer_trigger = timer->last_modified_timer;
367		else {
368			timer->work_pending = true;
369			schedule_work(&timer->work);
370		}
371	}
372
373	get_monotonic_boottime(&timer->last_modified_timer);
374	mod_timer(&timer->timer,
375			msecs_to_jiffies(info->timeout * 1000) + now);
376	spin_unlock_bh(&timestamp_lock);
377}
378
379/*
380 * The actual xt_tables plugin.
381 */
382static unsigned int idletimer_tg_target(struct sk_buff *skb,
383					 const struct xt_action_param *par)
384{
385	const struct idletimer_tg_info *info = par->targinfo;
386	unsigned long now = jiffies;
387
388	pr_debug("resetting timer %s, timeout period %u\n",
389		 info->label, info->timeout);
390
391	BUG_ON(!info->timer);
392
393	info->timer->active = true;
394
395	if (time_before(info->timer->timer.expires, now)) {
396		schedule_work(&info->timer->work);
397		pr_debug("Starting timer %s (Expired, Jiffies): %lu, %lu\n",
398			 info->label, info->timer->timer.expires, now);
399	}
400
401	/* TODO: Avoid modifying timers on each packet */
402	reset_timer(info, skb);
403	return XT_CONTINUE;
404}
405
406static int idletimer_tg_checkentry(const struct xt_tgchk_param *par)
407{
408	struct idletimer_tg_info *info = par->targinfo;
409	int ret;
410
411	pr_debug("checkentry targinfo %s\n", info->label);
412
413	if (info->timeout == 0) {
414		pr_debug("timeout value is zero\n");
415		return -EINVAL;
416	}
417
418	if (info->label[0] == '\0' ||
419	    strnlen(info->label,
420		    MAX_IDLETIMER_LABEL_SIZE) == MAX_IDLETIMER_LABEL_SIZE) {
421		pr_debug("label is empty or not nul-terminated\n");
422		return -EINVAL;
423	}
424
425	mutex_lock(&list_mutex);
426
427	info->timer = __idletimer_tg_find_by_label(info->label);
428	if (info->timer) {
429		info->timer->refcnt++;
430		reset_timer(info, NULL);
431		pr_debug("increased refcnt of timer %s to %u\n",
432			 info->label, info->timer->refcnt);
433	} else {
434		ret = idletimer_tg_create(info);
435		if (ret < 0) {
436			pr_debug("failed to create timer\n");
437			mutex_unlock(&list_mutex);
438			return ret;
439		}
440	}
441
442	mutex_unlock(&list_mutex);
443
444	return 0;
445}
446
447static void idletimer_tg_destroy(const struct xt_tgdtor_param *par)
448{
449	const struct idletimer_tg_info *info = par->targinfo;
450
451	pr_debug("destroy targinfo %s\n", info->label);
452
453	mutex_lock(&list_mutex);
454
455	if (--info->timer->refcnt == 0) {
456		pr_debug("deleting timer %s\n", info->label);
457
458		list_del(&info->timer->entry);
459		del_timer_sync(&info->timer->timer);
460		sysfs_remove_file(idletimer_tg_kobj, &info->timer->attr.attr);
461		unregister_pm_notifier(&info->timer->pm_nb);
462		kfree(info->timer->attr.attr.name);
463		kfree(info->timer);
464	} else {
465		pr_debug("decreased refcnt of timer %s to %u\n",
466		info->label, info->timer->refcnt);
467	}
468
469	mutex_unlock(&list_mutex);
470}
471
472static struct xt_target idletimer_tg __read_mostly = {
473	.name		= "IDLETIMER",
474	.revision	= 1,
475	.family		= NFPROTO_UNSPEC,
476	.target		= idletimer_tg_target,
477	.targetsize     = sizeof(struct idletimer_tg_info),
478	.checkentry	= idletimer_tg_checkentry,
479	.destroy        = idletimer_tg_destroy,
480	.me		= THIS_MODULE,
481};
482
483static struct class *idletimer_tg_class;
484
485static struct device *idletimer_tg_device;
486
487static int __init idletimer_tg_init(void)
488{
489	int err;
490
491	idletimer_tg_class = class_create(THIS_MODULE, "xt_idletimer");
492	err = PTR_ERR(idletimer_tg_class);
493	if (IS_ERR(idletimer_tg_class)) {
494		pr_debug("couldn't register device class\n");
495		goto out;
496	}
497
498	idletimer_tg_device = device_create(idletimer_tg_class, NULL,
499					    MKDEV(0, 0), NULL, "timers");
500	err = PTR_ERR(idletimer_tg_device);
501	if (IS_ERR(idletimer_tg_device)) {
502		pr_debug("couldn't register system device\n");
503		goto out_class;
504	}
505
506	idletimer_tg_kobj = &idletimer_tg_device->kobj;
507
508	err =  xt_register_target(&idletimer_tg);
509	if (err < 0) {
510		pr_debug("couldn't register xt target\n");
511		goto out_dev;
512	}
513
514	return 0;
515out_dev:
516	device_destroy(idletimer_tg_class, MKDEV(0, 0));
517out_class:
518	class_destroy(idletimer_tg_class);
519out:
520	return err;
521}
522
523static void __exit idletimer_tg_exit(void)
524{
525	xt_unregister_target(&idletimer_tg);
526
527	device_destroy(idletimer_tg_class, MKDEV(0, 0));
528	class_destroy(idletimer_tg_class);
529}
530
531module_init(idletimer_tg_init);
532module_exit(idletimer_tg_exit);
533
534MODULE_AUTHOR("Timo Teras <ext-timo.teras@nokia.com>");
535MODULE_AUTHOR("Luciano Coelho <luciano.coelho@nokia.com>");
536MODULE_DESCRIPTION("Xtables: idle time monitor");
537MODULE_LICENSE("GPL v2");
538MODULE_ALIAS("ipt_IDLETIMER");
539MODULE_ALIAS("ip6t_IDLETIMER");
540MODULE_ALIAS("arpt_IDLETIMER");
541