xref: /linux-6.15/net/strparser/strparser.c (revision 4e485d06)
1 /*
2  * Stream Parser
3  *
4  * Copyright (c) 2016 Tom Herbert <[email protected]>
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/module.h>
18 #include <linux/net.h>
19 #include <linux/netdevice.h>
20 #include <linux/poll.h>
21 #include <linux/rculist.h>
22 #include <linux/skbuff.h>
23 #include <linux/socket.h>
24 #include <linux/uaccess.h>
25 #include <linux/workqueue.h>
26 #include <net/strparser.h>
27 #include <net/netns/generic.h>
28 #include <net/sock.h>
29 
30 static struct workqueue_struct *strp_wq;
31 
32 struct _strp_msg {
33 	/* Internal cb structure. struct strp_msg must be first for passing
34 	 * to upper layer.
35 	 */
36 	struct strp_msg strp;
37 	int accum_len;
38 	int early_eaten;
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 
119 		stm = _strp_msg(head);
120 		if (unlikely(stm->early_eaten)) {
121 			/* Already some number of bytes on the receive sock
122 			 * data saved in skb_head, just indicate they
123 			 * are consumed.
124 			 */
125 			eaten = orig_len <= stm->early_eaten ?
126 				orig_len : stm->early_eaten;
127 			stm->early_eaten -= eaten;
128 
129 			return eaten;
130 		}
131 
132 		if (unlikely(orig_offset)) {
133 			/* Getting data with a non-zero offset when a message is
134 			 * in progress is not expected. If it does happen, we
135 			 * need to clone and pull since we can't deal with
136 			 * offsets in the skbs for a message expect in the head.
137 			 */
138 			orig_skb = skb_clone(orig_skb, GFP_ATOMIC);
139 			if (!orig_skb) {
140 				STRP_STATS_INCR(strp->stats.mem_fail);
141 				desc->error = -ENOMEM;
142 				return 0;
143 			}
144 			if (!pskb_pull(orig_skb, orig_offset)) {
145 				STRP_STATS_INCR(strp->stats.mem_fail);
146 				kfree_skb(orig_skb);
147 				desc->error = -ENOMEM;
148 				return 0;
149 			}
150 			cloned_orig = true;
151 			orig_offset = 0;
152 		}
153 
154 		if (!strp->skb_nextp) {
155 			/* We are going to append to the frags_list of head.
156 			 * Need to unshare the frag_list.
157 			 */
158 			if (skb_has_frag_list(head)) {
159 				err = skb_unclone(head, GFP_ATOMIC);
160 				if (err) {
161 					STRP_STATS_INCR(strp->stats.mem_fail);
162 					desc->error = err;
163 					return 0;
164 				}
165 			}
166 
167 			if (unlikely(skb_shinfo(head)->frag_list)) {
168 				/* We can't append to an sk_buff that already
169 				 * has a frag_list. We create a new head, point
170 				 * the frag_list of that to the old head, and
171 				 * then are able to use the old head->next for
172 				 * appending to the message.
173 				 */
174 				if (WARN_ON(head->next)) {
175 					desc->error = -EINVAL;
176 					return 0;
177 				}
178 
179 				skb = alloc_skb(0, GFP_ATOMIC);
180 				if (!skb) {
181 					STRP_STATS_INCR(strp->stats.mem_fail);
182 					desc->error = -ENOMEM;
183 					return 0;
184 				}
185 				skb->len = head->len;
186 				skb->data_len = head->len;
187 				skb->truesize = head->truesize;
188 				*_strp_msg(skb) = *_strp_msg(head);
189 				strp->skb_nextp = &head->next;
190 				skb_shinfo(skb)->frag_list = head;
191 				strp->skb_head = skb;
192 				head = skb;
193 			} else {
194 				strp->skb_nextp =
195 				    &skb_shinfo(head)->frag_list;
196 			}
197 		}
198 	}
199 
200 	while (eaten < orig_len) {
201 		/* Always clone since we will consume something */
202 		skb = skb_clone(orig_skb, GFP_ATOMIC);
203 		if (!skb) {
204 			STRP_STATS_INCR(strp->stats.mem_fail);
205 			desc->error = -ENOMEM;
206 			break;
207 		}
208 
209 		cand_len = orig_len - eaten;
210 
211 		head = strp->skb_head;
212 		if (!head) {
213 			head = skb;
214 			strp->skb_head = head;
215 			/* Will set skb_nextp on next packet if needed */
216 			strp->skb_nextp = NULL;
217 			stm = _strp_msg(head);
218 			memset(stm, 0, sizeof(*stm));
219 			stm->strp.offset = orig_offset + eaten;
220 		} else {
221 			/* Unclone if we are appending to an skb that we
222 			 * already share a frag_list with.
223 			 */
224 			if (skb_has_frag_list(skb)) {
225 				err = skb_unclone(skb, GFP_ATOMIC);
226 				if (err) {
227 					STRP_STATS_INCR(strp->stats.mem_fail);
228 					desc->error = err;
229 					break;
230 				}
231 			}
232 
233 			stm = _strp_msg(head);
234 			*strp->skb_nextp = skb;
235 			strp->skb_nextp = &skb->next;
236 			head->data_len += skb->len;
237 			head->len += skb->len;
238 			head->truesize += skb->truesize;
239 		}
240 
241 		if (!stm->strp.full_len) {
242 			ssize_t len;
243 
244 			len = (*strp->cb.parse_msg)(strp, head);
245 
246 			if (!len) {
247 				/* Need more header to determine length */
248 				if (!stm->accum_len) {
249 					/* Start RX timer for new message */
250 					strp_start_timer(strp, timeo);
251 				}
252 				stm->accum_len += cand_len;
253 				eaten += cand_len;
254 				STRP_STATS_INCR(strp->stats.need_more_hdr);
255 				WARN_ON(eaten != orig_len);
256 				break;
257 			} else if (len < 0) {
258 				if (len == -ESTRPIPE && stm->accum_len) {
259 					len = -ENODATA;
260 					strp->unrecov_intr = 1;
261 				} else {
262 					strp->interrupted = 1;
263 				}
264 				strp_parser_err(strp, len, desc);
265 				break;
266 			} else if (len > max_msg_size) {
267 				/* Message length exceeds maximum allowed */
268 				STRP_STATS_INCR(strp->stats.msg_too_big);
269 				strp_parser_err(strp, -EMSGSIZE, desc);
270 				break;
271 			} else if (len <= (ssize_t)head->len -
272 					  skb->len - stm->strp.offset) {
273 				/* Length must be into new skb (and also
274 				 * greater than zero)
275 				 */
276 				STRP_STATS_INCR(strp->stats.bad_hdr_len);
277 				strp_parser_err(strp, -EPROTO, desc);
278 				break;
279 			}
280 
281 			stm->strp.full_len = len;
282 		}
283 
284 		extra = (ssize_t)(stm->accum_len + cand_len) -
285 			stm->strp.full_len;
286 
287 		if (extra < 0) {
288 			/* Message not complete yet. */
289 			if (stm->strp.full_len - stm->accum_len >
290 			    strp_peek_len(strp)) {
291 				/* Don't have the whole message in the socket
292 				 * buffer. Set strp->need_bytes to wait for
293 				 * the rest of the message. Also, set "early
294 				 * eaten" since we've already buffered the skb
295 				 * but don't consume yet per strp_read_sock.
296 				 */
297 
298 				if (!stm->accum_len) {
299 					/* Start RX timer for new message */
300 					strp_start_timer(strp, timeo);
301 				}
302 
303 				stm->accum_len += cand_len;
304 				strp->need_bytes = stm->strp.full_len -
305 						       stm->accum_len;
306 				stm->early_eaten = cand_len;
307 				STRP_STATS_ADD(strp->stats.bytes, cand_len);
308 				desc->count = 0; /* Stop reading socket */
309 				break;
310 			}
311 			stm->accum_len += cand_len;
312 			eaten += cand_len;
313 			WARN_ON(eaten != orig_len);
314 			break;
315 		}
316 
317 		/* Positive extra indicates ore bytes than needed for the
318 		 * message
319 		 */
320 
321 		WARN_ON(extra > cand_len);
322 
323 		eaten += (cand_len - extra);
324 
325 		/* Hurray, we have a new message! */
326 		cancel_delayed_work(&strp->msg_timer_work);
327 		strp->skb_head = NULL;
328 		strp->need_bytes = 0;
329 		STRP_STATS_INCR(strp->stats.msgs);
330 
331 		/* Give skb to upper layer */
332 		strp->cb.rcv_msg(strp, head);
333 
334 		if (unlikely(strp->paused)) {
335 			/* Upper layer paused strp */
336 			break;
337 		}
338 	}
339 
340 	if (cloned_orig)
341 		kfree_skb(orig_skb);
342 
343 	STRP_STATS_ADD(strp->stats.bytes, eaten);
344 
345 	return eaten;
346 }
347 
348 int strp_process(struct strparser *strp, struct sk_buff *orig_skb,
349 		 unsigned int orig_offset, size_t orig_len,
350 		 size_t max_msg_size, long timeo)
351 {
352 	read_descriptor_t desc; /* Dummy arg to strp_recv */
353 
354 	desc.arg.data = strp;
355 
356 	return __strp_recv(&desc, orig_skb, orig_offset, orig_len,
357 			   max_msg_size, timeo);
358 }
359 EXPORT_SYMBOL_GPL(strp_process);
360 
361 static int strp_recv(read_descriptor_t *desc, struct sk_buff *orig_skb,
362 		     unsigned int orig_offset, size_t orig_len)
363 {
364 	struct strparser *strp = (struct strparser *)desc->arg.data;
365 
366 	return __strp_recv(desc, orig_skb, orig_offset, orig_len,
367 			   strp->sk->sk_rcvbuf, strp->sk->sk_rcvtimeo);
368 }
369 
370 static int default_read_sock_done(struct strparser *strp, int err)
371 {
372 	return err;
373 }
374 
375 /* Called with lock held on lower socket */
376 static int strp_read_sock(struct strparser *strp)
377 {
378 	struct socket *sock = strp->sk->sk_socket;
379 	read_descriptor_t desc;
380 
381 	if (unlikely(!sock || !sock->ops || !sock->ops->read_sock))
382 		return -EBUSY;
383 
384 	desc.arg.data = strp;
385 	desc.error = 0;
386 	desc.count = 1; /* give more than one skb per call */
387 
388 	/* sk should be locked here, so okay to do read_sock */
389 	sock->ops->read_sock(strp->sk, &desc, strp_recv);
390 
391 	desc.error = strp->cb.read_sock_done(strp, desc.error);
392 
393 	return desc.error;
394 }
395 
396 /* Lower sock lock held */
397 void strp_data_ready(struct strparser *strp)
398 {
399 	if (unlikely(strp->stopped) || strp->paused)
400 		return;
401 
402 	/* This check is needed to synchronize with do_strp_work.
403 	 * do_strp_work acquires a process lock (lock_sock) whereas
404 	 * the lock held here is bh_lock_sock. The two locks can be
405 	 * held by different threads at the same time, but bh_lock_sock
406 	 * allows a thread in BH context to safely check if the process
407 	 * lock is held. In this case, if the lock is held, queue work.
408 	 */
409 	if (sock_owned_by_user_nocheck(strp->sk)) {
410 		queue_work(strp_wq, &strp->work);
411 		return;
412 	}
413 
414 	if (strp->need_bytes) {
415 		if (strp_peek_len(strp) < strp->need_bytes)
416 			return;
417 	}
418 
419 	if (strp_read_sock(strp) == -ENOMEM)
420 		queue_work(strp_wq, &strp->work);
421 }
422 EXPORT_SYMBOL_GPL(strp_data_ready);
423 
424 static void do_strp_work(struct strparser *strp)
425 {
426 	read_descriptor_t rd_desc;
427 
428 	/* We need the read lock to synchronize with strp_data_ready. We
429 	 * need the socket lock for calling strp_read_sock.
430 	 */
431 	strp->cb.lock(strp);
432 
433 	if (unlikely(strp->stopped))
434 		goto out;
435 
436 	if (strp->paused)
437 		goto out;
438 
439 	rd_desc.arg.data = strp;
440 
441 	if (strp_read_sock(strp) == -ENOMEM)
442 		queue_work(strp_wq, &strp->work);
443 
444 out:
445 	strp->cb.unlock(strp);
446 }
447 
448 static void strp_work(struct work_struct *w)
449 {
450 	do_strp_work(container_of(w, struct strparser, work));
451 }
452 
453 static void strp_msg_timeout(struct work_struct *w)
454 {
455 	struct strparser *strp = container_of(w, struct strparser,
456 					      msg_timer_work.work);
457 
458 	/* Message assembly timed out */
459 	STRP_STATS_INCR(strp->stats.msg_timeouts);
460 	strp->cb.lock(strp);
461 	strp->cb.abort_parser(strp, -ETIMEDOUT);
462 	strp->cb.unlock(strp);
463 }
464 
465 static void strp_sock_lock(struct strparser *strp)
466 {
467 	lock_sock(strp->sk);
468 }
469 
470 static void strp_sock_unlock(struct strparser *strp)
471 {
472 	release_sock(strp->sk);
473 }
474 
475 int strp_init(struct strparser *strp, struct sock *sk,
476 	      const struct strp_callbacks *cb)
477 {
478 
479 	if (!cb || !cb->rcv_msg || !cb->parse_msg)
480 		return -EINVAL;
481 
482 	/* The sk (sock) arg determines the mode of the stream parser.
483 	 *
484 	 * If the sock is set then the strparser is in receive callback mode.
485 	 * The upper layer calls strp_data_ready to kick receive processing
486 	 * and strparser calls the read_sock function on the socket to
487 	 * get packets.
488 	 *
489 	 * If the sock is not set then the strparser is in general mode.
490 	 * The upper layer calls strp_process for each skb to be parsed.
491 	 */
492 
493 	if (!sk) {
494 		if (!cb->lock || !cb->unlock)
495 			return -EINVAL;
496 	}
497 
498 	memset(strp, 0, sizeof(*strp));
499 
500 	strp->sk = sk;
501 
502 	strp->cb.lock = cb->lock ? : strp_sock_lock;
503 	strp->cb.unlock = cb->unlock ? : strp_sock_unlock;
504 	strp->cb.rcv_msg = cb->rcv_msg;
505 	strp->cb.parse_msg = cb->parse_msg;
506 	strp->cb.read_sock_done = cb->read_sock_done ? : default_read_sock_done;
507 	strp->cb.abort_parser = cb->abort_parser ? : strp_abort_strp;
508 
509 	INIT_DELAYED_WORK(&strp->msg_timer_work, strp_msg_timeout);
510 	INIT_WORK(&strp->work, strp_work);
511 
512 	return 0;
513 }
514 EXPORT_SYMBOL_GPL(strp_init);
515 
516 /* Sock process lock held (lock_sock) */
517 void __strp_unpause(struct strparser *strp)
518 {
519 	strp->paused = 0;
520 
521 	if (strp->need_bytes) {
522 		if (strp_peek_len(strp) < strp->need_bytes)
523 			return;
524 	}
525 	strp_read_sock(strp);
526 }
527 EXPORT_SYMBOL_GPL(__strp_unpause);
528 
529 void strp_unpause(struct strparser *strp)
530 {
531 	strp->paused = 0;
532 
533 	/* Sync setting paused with RX work */
534 	smp_mb();
535 
536 	queue_work(strp_wq, &strp->work);
537 }
538 EXPORT_SYMBOL_GPL(strp_unpause);
539 
540 /* strp must already be stopped so that strp_recv will no longer be called.
541  * Note that strp_done is not called with the lower socket held.
542  */
543 void strp_done(struct strparser *strp)
544 {
545 	WARN_ON(!strp->stopped);
546 
547 	cancel_delayed_work_sync(&strp->msg_timer_work);
548 	cancel_work_sync(&strp->work);
549 
550 	if (strp->skb_head) {
551 		kfree_skb(strp->skb_head);
552 		strp->skb_head = NULL;
553 	}
554 }
555 EXPORT_SYMBOL_GPL(strp_done);
556 
557 void strp_stop(struct strparser *strp)
558 {
559 	strp->stopped = 1;
560 }
561 EXPORT_SYMBOL_GPL(strp_stop);
562 
563 void strp_check_rcv(struct strparser *strp)
564 {
565 	queue_work(strp_wq, &strp->work);
566 }
567 EXPORT_SYMBOL_GPL(strp_check_rcv);
568 
569 static int __init strp_mod_init(void)
570 {
571 	strp_wq = create_singlethread_workqueue("kstrp");
572 
573 	return 0;
574 }
575 
576 static void __exit strp_mod_exit(void)
577 {
578 	destroy_workqueue(strp_wq);
579 }
580 module_init(strp_mod_init);
581 module_exit(strp_mod_exit);
582 MODULE_LICENSE("GPL");
583