xref: /linux/net/strparser/strparser.c (revision a6cdeeb16bff89c8486324f53577db058cbe81ba)
1 /*
2  * Stream Parser
3  *
4  * Copyright (c) 2016 Tom Herbert <tom@herbertland.com>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2
8  * as published by the Free Software Foundation.
9  */
10 
11 #include <linux/bpf.h>
12 #include <linux/errno.h>
13 #include <linux/errqueue.h>
14 #include <linux/file.h>
15 #include <linux/in.h>
16 #include <linux/kernel.h>
17 #include <linux/export.h>
18 #include <linux/init.h>
19 #include <linux/net.h>
20 #include <linux/netdevice.h>
21 #include <linux/poll.h>
22 #include <linux/rculist.h>
23 #include <linux/skbuff.h>
24 #include <linux/socket.h>
25 #include <linux/uaccess.h>
26 #include <linux/workqueue.h>
27 #include <net/strparser.h>
28 #include <net/netns/generic.h>
29 #include <net/sock.h>
30 
31 static struct workqueue_struct *strp_wq;
32 
33 struct _strp_msg {
34 	/* Internal cb structure. struct strp_msg must be first for passing
35 	 * to upper layer.
36 	 */
37 	struct strp_msg strp;
38 	int accum_len;
39 };
40 
41 static inline struct _strp_msg *_strp_msg(struct sk_buff *skb)
42 {
43 	return (struct _strp_msg *)((void *)skb->cb +
44 		offsetof(struct qdisc_skb_cb, data));
45 }
46 
47 /* Lower lock held */
48 static void strp_abort_strp(struct strparser *strp, int err)
49 {
50 	/* Unrecoverable error in receive */
51 
52 	cancel_delayed_work(&strp->msg_timer_work);
53 
54 	if (strp->stopped)
55 		return;
56 
57 	strp->stopped = 1;
58 
59 	if (strp->sk) {
60 		struct sock *sk = strp->sk;
61 
62 		/* Report an error on the lower socket */
63 		sk->sk_err = -err;
64 		sk->sk_error_report(sk);
65 	}
66 }
67 
68 static void strp_start_timer(struct strparser *strp, long timeo)
69 {
70 	if (timeo && timeo != LONG_MAX)
71 		mod_delayed_work(strp_wq, &strp->msg_timer_work, timeo);
72 }
73 
74 /* Lower lock held */
75 static void strp_parser_err(struct strparser *strp, int err,
76 			    read_descriptor_t *desc)
77 {
78 	desc->error = err;
79 	kfree_skb(strp->skb_head);
80 	strp->skb_head = NULL;
81 	strp->cb.abort_parser(strp, err);
82 }
83 
84 static inline int strp_peek_len(struct strparser *strp)
85 {
86 	if (strp->sk) {
87 		struct socket *sock = strp->sk->sk_socket;
88 
89 		return sock->ops->peek_len(sock);
90 	}
91 
92 	/* If we don't have an associated socket there's nothing to peek.
93 	 * Return int max to avoid stopping the strparser.
94 	 */
95 
96 	return INT_MAX;
97 }
98 
99 /* Lower socket lock held */
100 static int __strp_recv(read_descriptor_t *desc, struct sk_buff *orig_skb,
101 		       unsigned int orig_offset, size_t orig_len,
102 		       size_t max_msg_size, long timeo)
103 {
104 	struct strparser *strp = (struct strparser *)desc->arg.data;
105 	struct _strp_msg *stm;
106 	struct sk_buff *head, *skb;
107 	size_t eaten = 0, cand_len;
108 	ssize_t extra;
109 	int err;
110 	bool cloned_orig = false;
111 
112 	if (strp->paused)
113 		return 0;
114 
115 	head = strp->skb_head;
116 	if (head) {
117 		/* Message already in progress */
118 		if (unlikely(orig_offset)) {
119 			/* Getting data with a non-zero offset when a message is
120 			 * in progress is not expected. If it does happen, we
121 			 * need to clone and pull since we can't deal with
122 			 * offsets in the skbs for a message expect in the head.
123 			 */
124 			orig_skb = skb_clone(orig_skb, GFP_ATOMIC);
125 			if (!orig_skb) {
126 				STRP_STATS_INCR(strp->stats.mem_fail);
127 				desc->error = -ENOMEM;
128 				return 0;
129 			}
130 			if (!pskb_pull(orig_skb, orig_offset)) {
131 				STRP_STATS_INCR(strp->stats.mem_fail);
132 				kfree_skb(orig_skb);
133 				desc->error = -ENOMEM;
134 				return 0;
135 			}
136 			cloned_orig = true;
137 			orig_offset = 0;
138 		}
139 
140 		if (!strp->skb_nextp) {
141 			/* We are going to append to the frags_list of head.
142 			 * Need to unshare the frag_list.
143 			 */
144 			err = skb_unclone(head, GFP_ATOMIC);
145 			if (err) {
146 				STRP_STATS_INCR(strp->stats.mem_fail);
147 				desc->error = err;
148 				return 0;
149 			}
150 
151 			if (unlikely(skb_shinfo(head)->frag_list)) {
152 				/* We can't append to an sk_buff that already
153 				 * has a frag_list. We create a new head, point
154 				 * the frag_list of that to the old head, and
155 				 * then are able to use the old head->next for
156 				 * appending to the message.
157 				 */
158 				if (WARN_ON(head->next)) {
159 					desc->error = -EINVAL;
160 					return 0;
161 				}
162 
163 				skb = alloc_skb_for_msg(head);
164 				if (!skb) {
165 					STRP_STATS_INCR(strp->stats.mem_fail);
166 					desc->error = -ENOMEM;
167 					return 0;
168 				}
169 
170 				strp->skb_nextp = &head->next;
171 				strp->skb_head = skb;
172 				head = skb;
173 			} else {
174 				strp->skb_nextp =
175 				    &skb_shinfo(head)->frag_list;
176 			}
177 		}
178 	}
179 
180 	while (eaten < orig_len) {
181 		/* Always clone since we will consume something */
182 		skb = skb_clone(orig_skb, GFP_ATOMIC);
183 		if (!skb) {
184 			STRP_STATS_INCR(strp->stats.mem_fail);
185 			desc->error = -ENOMEM;
186 			break;
187 		}
188 
189 		cand_len = orig_len - eaten;
190 
191 		head = strp->skb_head;
192 		if (!head) {
193 			head = skb;
194 			strp->skb_head = head;
195 			/* Will set skb_nextp on next packet if needed */
196 			strp->skb_nextp = NULL;
197 			stm = _strp_msg(head);
198 			memset(stm, 0, sizeof(*stm));
199 			stm->strp.offset = orig_offset + eaten;
200 		} else {
201 			/* Unclone if we are appending to an skb that we
202 			 * already share a frag_list with.
203 			 */
204 			if (skb_has_frag_list(skb)) {
205 				err = skb_unclone(skb, GFP_ATOMIC);
206 				if (err) {
207 					STRP_STATS_INCR(strp->stats.mem_fail);
208 					desc->error = err;
209 					break;
210 				}
211 			}
212 
213 			stm = _strp_msg(head);
214 			*strp->skb_nextp = skb;
215 			strp->skb_nextp = &skb->next;
216 			head->data_len += skb->len;
217 			head->len += skb->len;
218 			head->truesize += skb->truesize;
219 		}
220 
221 		if (!stm->strp.full_len) {
222 			ssize_t len;
223 
224 			len = (*strp->cb.parse_msg)(strp, head);
225 
226 			if (!len) {
227 				/* Need more header to determine length */
228 				if (!stm->accum_len) {
229 					/* Start RX timer for new message */
230 					strp_start_timer(strp, timeo);
231 				}
232 				stm->accum_len += cand_len;
233 				eaten += cand_len;
234 				STRP_STATS_INCR(strp->stats.need_more_hdr);
235 				WARN_ON(eaten != orig_len);
236 				break;
237 			} else if (len < 0) {
238 				if (len == -ESTRPIPE && stm->accum_len) {
239 					len = -ENODATA;
240 					strp->unrecov_intr = 1;
241 				} else {
242 					strp->interrupted = 1;
243 				}
244 				strp_parser_err(strp, len, desc);
245 				break;
246 			} else if (len > max_msg_size) {
247 				/* Message length exceeds maximum allowed */
248 				STRP_STATS_INCR(strp->stats.msg_too_big);
249 				strp_parser_err(strp, -EMSGSIZE, desc);
250 				break;
251 			} else if (len <= (ssize_t)head->len -
252 					  skb->len - stm->strp.offset) {
253 				/* Length must be into new skb (and also
254 				 * greater than zero)
255 				 */
256 				STRP_STATS_INCR(strp->stats.bad_hdr_len);
257 				strp_parser_err(strp, -EPROTO, desc);
258 				break;
259 			}
260 
261 			stm->strp.full_len = len;
262 		}
263 
264 		extra = (ssize_t)(stm->accum_len + cand_len) -
265 			stm->strp.full_len;
266 
267 		if (extra < 0) {
268 			/* Message not complete yet. */
269 			if (stm->strp.full_len - stm->accum_len >
270 			    strp_peek_len(strp)) {
271 				/* Don't have the whole message in the socket
272 				 * buffer. Set strp->need_bytes to wait for
273 				 * the rest of the message. Also, set "early
274 				 * eaten" since we've already buffered the skb
275 				 * but don't consume yet per strp_read_sock.
276 				 */
277 
278 				if (!stm->accum_len) {
279 					/* Start RX timer for new message */
280 					strp_start_timer(strp, timeo);
281 				}
282 
283 				stm->accum_len += cand_len;
284 				eaten += cand_len;
285 				strp->need_bytes = stm->strp.full_len -
286 						       stm->accum_len;
287 				STRP_STATS_ADD(strp->stats.bytes, cand_len);
288 				desc->count = 0; /* Stop reading socket */
289 				break;
290 			}
291 			stm->accum_len += cand_len;
292 			eaten += cand_len;
293 			WARN_ON(eaten != orig_len);
294 			break;
295 		}
296 
297 		/* Positive extra indicates more bytes than needed for the
298 		 * message
299 		 */
300 
301 		WARN_ON(extra > cand_len);
302 
303 		eaten += (cand_len - extra);
304 
305 		/* Hurray, we have a new message! */
306 		cancel_delayed_work(&strp->msg_timer_work);
307 		strp->skb_head = NULL;
308 		strp->need_bytes = 0;
309 		STRP_STATS_INCR(strp->stats.msgs);
310 
311 		/* Give skb to upper layer */
312 		strp->cb.rcv_msg(strp, head);
313 
314 		if (unlikely(strp->paused)) {
315 			/* Upper layer paused strp */
316 			break;
317 		}
318 	}
319 
320 	if (cloned_orig)
321 		kfree_skb(orig_skb);
322 
323 	STRP_STATS_ADD(strp->stats.bytes, eaten);
324 
325 	return eaten;
326 }
327 
328 int strp_process(struct strparser *strp, struct sk_buff *orig_skb,
329 		 unsigned int orig_offset, size_t orig_len,
330 		 size_t max_msg_size, long timeo)
331 {
332 	read_descriptor_t desc; /* Dummy arg to strp_recv */
333 
334 	desc.arg.data = strp;
335 
336 	return __strp_recv(&desc, orig_skb, orig_offset, orig_len,
337 			   max_msg_size, timeo);
338 }
339 EXPORT_SYMBOL_GPL(strp_process);
340 
341 static int strp_recv(read_descriptor_t *desc, struct sk_buff *orig_skb,
342 		     unsigned int orig_offset, size_t orig_len)
343 {
344 	struct strparser *strp = (struct strparser *)desc->arg.data;
345 
346 	return __strp_recv(desc, orig_skb, orig_offset, orig_len,
347 			   strp->sk->sk_rcvbuf, strp->sk->sk_rcvtimeo);
348 }
349 
350 static int default_read_sock_done(struct strparser *strp, int err)
351 {
352 	return err;
353 }
354 
355 /* Called with lock held on lower socket */
356 static int strp_read_sock(struct strparser *strp)
357 {
358 	struct socket *sock = strp->sk->sk_socket;
359 	read_descriptor_t desc;
360 
361 	if (unlikely(!sock || !sock->ops || !sock->ops->read_sock))
362 		return -EBUSY;
363 
364 	desc.arg.data = strp;
365 	desc.error = 0;
366 	desc.count = 1; /* give more than one skb per call */
367 
368 	/* sk should be locked here, so okay to do read_sock */
369 	sock->ops->read_sock(strp->sk, &desc, strp_recv);
370 
371 	desc.error = strp->cb.read_sock_done(strp, desc.error);
372 
373 	return desc.error;
374 }
375 
376 /* Lower sock lock held */
377 void strp_data_ready(struct strparser *strp)
378 {
379 	if (unlikely(strp->stopped) || strp->paused)
380 		return;
381 
382 	/* This check is needed to synchronize with do_strp_work.
383 	 * do_strp_work acquires a process lock (lock_sock) whereas
384 	 * the lock held here is bh_lock_sock. The two locks can be
385 	 * held by different threads at the same time, but bh_lock_sock
386 	 * allows a thread in BH context to safely check if the process
387 	 * lock is held. In this case, if the lock is held, queue work.
388 	 */
389 	if (sock_owned_by_user_nocheck(strp->sk)) {
390 		queue_work(strp_wq, &strp->work);
391 		return;
392 	}
393 
394 	if (strp->need_bytes) {
395 		if (strp_peek_len(strp) < strp->need_bytes)
396 			return;
397 	}
398 
399 	if (strp_read_sock(strp) == -ENOMEM)
400 		queue_work(strp_wq, &strp->work);
401 }
402 EXPORT_SYMBOL_GPL(strp_data_ready);
403 
404 static void do_strp_work(struct strparser *strp)
405 {
406 	/* We need the read lock to synchronize with strp_data_ready. We
407 	 * need the socket lock for calling strp_read_sock.
408 	 */
409 	strp->cb.lock(strp);
410 
411 	if (unlikely(strp->stopped))
412 		goto out;
413 
414 	if (strp->paused)
415 		goto out;
416 
417 	if (strp_read_sock(strp) == -ENOMEM)
418 		queue_work(strp_wq, &strp->work);
419 
420 out:
421 	strp->cb.unlock(strp);
422 }
423 
424 static void strp_work(struct work_struct *w)
425 {
426 	do_strp_work(container_of(w, struct strparser, work));
427 }
428 
429 static void strp_msg_timeout(struct work_struct *w)
430 {
431 	struct strparser *strp = container_of(w, struct strparser,
432 					      msg_timer_work.work);
433 
434 	/* Message assembly timed out */
435 	STRP_STATS_INCR(strp->stats.msg_timeouts);
436 	strp->cb.lock(strp);
437 	strp->cb.abort_parser(strp, -ETIMEDOUT);
438 	strp->cb.unlock(strp);
439 }
440 
441 static void strp_sock_lock(struct strparser *strp)
442 {
443 	lock_sock(strp->sk);
444 }
445 
446 static void strp_sock_unlock(struct strparser *strp)
447 {
448 	release_sock(strp->sk);
449 }
450 
451 int strp_init(struct strparser *strp, struct sock *sk,
452 	      const struct strp_callbacks *cb)
453 {
454 
455 	if (!cb || !cb->rcv_msg || !cb->parse_msg)
456 		return -EINVAL;
457 
458 	/* The sk (sock) arg determines the mode of the stream parser.
459 	 *
460 	 * If the sock is set then the strparser is in receive callback mode.
461 	 * The upper layer calls strp_data_ready to kick receive processing
462 	 * and strparser calls the read_sock function on the socket to
463 	 * get packets.
464 	 *
465 	 * If the sock is not set then the strparser is in general mode.
466 	 * The upper layer calls strp_process for each skb to be parsed.
467 	 */
468 
469 	if (!sk) {
470 		if (!cb->lock || !cb->unlock)
471 			return -EINVAL;
472 	}
473 
474 	memset(strp, 0, sizeof(*strp));
475 
476 	strp->sk = sk;
477 
478 	strp->cb.lock = cb->lock ? : strp_sock_lock;
479 	strp->cb.unlock = cb->unlock ? : strp_sock_unlock;
480 	strp->cb.rcv_msg = cb->rcv_msg;
481 	strp->cb.parse_msg = cb->parse_msg;
482 	strp->cb.read_sock_done = cb->read_sock_done ? : default_read_sock_done;
483 	strp->cb.abort_parser = cb->abort_parser ? : strp_abort_strp;
484 
485 	INIT_DELAYED_WORK(&strp->msg_timer_work, strp_msg_timeout);
486 	INIT_WORK(&strp->work, strp_work);
487 
488 	return 0;
489 }
490 EXPORT_SYMBOL_GPL(strp_init);
491 
492 /* Sock process lock held (lock_sock) */
493 void __strp_unpause(struct strparser *strp)
494 {
495 	strp->paused = 0;
496 
497 	if (strp->need_bytes) {
498 		if (strp_peek_len(strp) < strp->need_bytes)
499 			return;
500 	}
501 	strp_read_sock(strp);
502 }
503 EXPORT_SYMBOL_GPL(__strp_unpause);
504 
505 void strp_unpause(struct strparser *strp)
506 {
507 	strp->paused = 0;
508 
509 	/* Sync setting paused with RX work */
510 	smp_mb();
511 
512 	queue_work(strp_wq, &strp->work);
513 }
514 EXPORT_SYMBOL_GPL(strp_unpause);
515 
516 /* strp must already be stopped so that strp_recv will no longer be called.
517  * Note that strp_done is not called with the lower socket held.
518  */
519 void strp_done(struct strparser *strp)
520 {
521 	WARN_ON(!strp->stopped);
522 
523 	cancel_delayed_work_sync(&strp->msg_timer_work);
524 	cancel_work_sync(&strp->work);
525 
526 	if (strp->skb_head) {
527 		kfree_skb(strp->skb_head);
528 		strp->skb_head = NULL;
529 	}
530 }
531 EXPORT_SYMBOL_GPL(strp_done);
532 
533 void strp_stop(struct strparser *strp)
534 {
535 	strp->stopped = 1;
536 }
537 EXPORT_SYMBOL_GPL(strp_stop);
538 
539 void strp_check_rcv(struct strparser *strp)
540 {
541 	queue_work(strp_wq, &strp->work);
542 }
543 EXPORT_SYMBOL_GPL(strp_check_rcv);
544 
545 static int __init strp_dev_init(void)
546 {
547 	strp_wq = create_singlethread_workqueue("kstrp");
548 	if (unlikely(!strp_wq))
549 		return -ENOMEM;
550 
551 	return 0;
552 }
553 device_initcall(strp_dev_init);
554