1 /*
2  * Copyright (c) 2018 Intel Corporation
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/logging/log.h>
8 LOG_MODULE_REGISTER(net_coap, CONFIG_COAP_LOG_LEVEL);
9 
10 #include <stdlib.h>
11 #include <stddef.h>
12 #include <string.h>
13 #include <stdbool.h>
14 #include <errno.h>
15 #include <zephyr/random/random.h>
16 #include <zephyr/sys/atomic.h>
17 #include <zephyr/sys/util.h>
18 
19 #include <zephyr/types.h>
20 #include <zephyr/sys/byteorder.h>
21 #include <zephyr/sys/math_extras.h>
22 
23 #include <zephyr/net/net_ip.h>
24 #include <zephyr/net/net_core.h>
25 #include <zephyr/net/coap.h>
26 #include <zephyr/net/coap_mgmt.h>
27 
28 #define COAP_PATH_ELEM_DELIM '/'
29 #define COAP_PATH_ELEM_QUERY '?'
30 #define COAP_PATH_ELEM_AMP   '&'
31 
32 /* Values as per RFC 7252, section-3.1.
33  *
34  * Option Delta/Length: 4-bit unsigned integer. A value between 0 and
35  * 12 indicates the Option Delta/Length.  Three values are reserved for
36  * special constructs:
37  * 13: An 8-bit unsigned integer precedes the Option Value and indicates
38  *     the Option Delta/Length minus 13.
39  * 14: A 16-bit unsigned integer in network byte order precedes the
40  *     Option Value and indicates the Option Delta/Length minus 269.
41  * 15: Reserved for future use.
42  */
43 #define COAP_OPTION_NO_EXT 12 /* Option's Delta/Length without extended data */
44 #define COAP_OPTION_EXT_13 13
45 #define COAP_OPTION_EXT_14 14
46 #define COAP_OPTION_EXT_15 15
47 #define COAP_OPTION_EXT_269 269
48 
49 /* CoAP Payload Marker */
50 #define COAP_MARKER		0xFF
51 
52 #define BASIC_HEADER_SIZE	4
53 
54 #define COAP_OBSERVE_FIRST_OFFSET 2
55 
56 /* The CoAP message ID that is incremented each time coap_next_id() is called. */
57 static uint16_t message_id;
58 
59 static struct coap_transmission_parameters coap_transmission_params = {
60 	.max_retransmission = CONFIG_COAP_MAX_RETRANSMIT,
61 	.ack_timeout = CONFIG_COAP_INIT_ACK_TIMEOUT_MS,
62 #if defined(CONFIG_COAP_RANDOMIZE_ACK_TIMEOUT)
63 	.ack_random_percent = CONFIG_COAP_ACK_RANDOM_PERCENT,
64 #endif /* defined(CONFIG_COAP_RANDOMIZE_ACK_TIMEOUT) */
65 	.coap_backoff_percent = CONFIG_COAP_BACKOFF_PERCENT
66 };
67 
68 static int insert_option(struct coap_packet *cpkt, uint16_t code, const uint8_t *value,
69 			 uint16_t len);
70 
encode_u8(struct coap_packet * cpkt,uint16_t offset,uint8_t data)71 static inline void encode_u8(struct coap_packet *cpkt, uint16_t offset, uint8_t data)
72 {
73 	cpkt->data[offset] = data;
74 	++cpkt->offset;
75 }
76 
encode_be16(struct coap_packet * cpkt,uint16_t offset,uint16_t data)77 static inline void encode_be16(struct coap_packet *cpkt, uint16_t offset, uint16_t data)
78 {
79 	cpkt->data[offset] = data >> 8;
80 	cpkt->data[offset + 1] = (uint8_t)data;
81 	cpkt->offset += 2;
82 }
83 
encode_buffer(struct coap_packet * cpkt,uint16_t offset,const uint8_t * data,uint16_t len)84 static inline void encode_buffer(struct coap_packet *cpkt, uint16_t offset, const uint8_t *data,
85 				 uint16_t len)
86 {
87 	memcpy(cpkt->data + offset, data, len);
88 	cpkt->offset += len;
89 }
90 
enough_space(struct coap_packet * cpkt,const uint16_t bytes_to_add)91 static bool enough_space(struct coap_packet *cpkt, const uint16_t bytes_to_add)
92 {
93 	return (cpkt != NULL) && (cpkt->max_len - cpkt->offset >= bytes_to_add);
94 }
95 
append_u8(struct coap_packet * cpkt,uint8_t data)96 static inline bool append_u8(struct coap_packet *cpkt, uint8_t data)
97 {
98 	if (!enough_space(cpkt, 1)) {
99 		return false;
100 	}
101 
102 	encode_u8(cpkt, cpkt->offset, data);
103 
104 	return true;
105 }
106 
insert_u8(struct coap_packet * cpkt,uint8_t data,uint16_t offset)107 static inline bool insert_u8(struct coap_packet *cpkt, uint8_t data, uint16_t offset)
108 {
109 	if (!enough_space(cpkt, 1)) {
110 		return false;
111 	}
112 
113 	memmove(&cpkt->data[offset + 1], &cpkt->data[offset], cpkt->offset - offset);
114 
115 	encode_u8(cpkt, offset, data);
116 
117 	return true;
118 }
119 
append_be16(struct coap_packet * cpkt,uint16_t data)120 static inline bool append_be16(struct coap_packet *cpkt, uint16_t data)
121 {
122 	if (!enough_space(cpkt, 2)) {
123 		return false;
124 	}
125 
126 	encode_be16(cpkt, cpkt->offset, data);
127 
128 	return true;
129 }
130 
insert_be16(struct coap_packet * cpkt,uint16_t data,size_t offset)131 static inline bool insert_be16(struct coap_packet *cpkt, uint16_t data, size_t offset)
132 {
133 	if (!enough_space(cpkt, 2)) {
134 		return false;
135 	}
136 
137 	memmove(&cpkt->data[offset + 2], &cpkt->data[offset], cpkt->offset - offset);
138 
139 	encode_be16(cpkt, cpkt->offset, data);
140 
141 	return true;
142 }
143 
append(struct coap_packet * cpkt,const uint8_t * data,uint16_t len)144 static inline bool append(struct coap_packet *cpkt, const uint8_t *data, uint16_t len)
145 {
146 	if (data == NULL || !enough_space(cpkt, len)) {
147 		return false;
148 	}
149 
150 	encode_buffer(cpkt, cpkt->offset, data, len);
151 
152 	return true;
153 }
154 
insert(struct coap_packet * cpkt,const uint8_t * data,uint16_t len,size_t offset)155 static inline bool insert(struct coap_packet *cpkt, const uint8_t *data, uint16_t len,
156 			  size_t offset)
157 {
158 	if (data == NULL || !enough_space(cpkt, len)) {
159 		return false;
160 	}
161 
162 	memmove(&cpkt->data[offset + len], &cpkt->data[offset], cpkt->offset - offset);
163 
164 	encode_buffer(cpkt, offset, data, len);
165 
166 	return true;
167 }
168 
coap_packet_init(struct coap_packet * cpkt,uint8_t * data,uint16_t max_len,uint8_t ver,uint8_t type,uint8_t token_len,const uint8_t * token,uint8_t code,uint16_t id)169 int coap_packet_init(struct coap_packet *cpkt, uint8_t *data, uint16_t max_len,
170 		     uint8_t ver, uint8_t type, uint8_t token_len,
171 		     const uint8_t *token, uint8_t code, uint16_t id)
172 {
173 	uint8_t hdr;
174 	bool res;
175 
176 	if (!cpkt || !data || !max_len) {
177 		return -EINVAL;
178 	}
179 
180 	memset(cpkt, 0, sizeof(*cpkt));
181 
182 	cpkt->data = data;
183 	cpkt->offset = 0U;
184 	cpkt->max_len = max_len;
185 	cpkt->delta = 0U;
186 
187 	hdr = (ver & 0x3) << 6;
188 	hdr |= (type & 0x3) << 4;
189 	hdr |= token_len & 0xF;
190 
191 	res = append_u8(cpkt, hdr);
192 	if (!res) {
193 		return -EINVAL;
194 	}
195 
196 	res = append_u8(cpkt, code);
197 	if (!res) {
198 		return -EINVAL;
199 	}
200 
201 	res = append_be16(cpkt, id);
202 	if (!res) {
203 		return -EINVAL;
204 	}
205 
206 	if (token && token_len) {
207 		res = append(cpkt, token, token_len);
208 		if (!res) {
209 			return -EINVAL;
210 		}
211 	}
212 
213 	/* Header length : (version + type + tkl) + code + id + [token] */
214 	cpkt->hdr_len = 1 + 1 + 2 + token_len;
215 
216 	return 0;
217 }
218 
coap_ack_init(struct coap_packet * cpkt,const struct coap_packet * req,uint8_t * data,uint16_t max_len,uint8_t code)219 int coap_ack_init(struct coap_packet *cpkt, const struct coap_packet *req,
220 		  uint8_t *data, uint16_t max_len, uint8_t code)
221 {
222 	uint16_t id;
223 	uint8_t ver;
224 	uint8_t tkl;
225 	uint8_t token[COAP_TOKEN_MAX_LEN];
226 
227 	ver = coap_header_get_version(req);
228 	id = coap_header_get_id(req);
229 	tkl = code ? coap_header_get_token(req, token) : 0;
230 
231 	return coap_packet_init(cpkt, data, max_len, ver, COAP_TYPE_ACK, tkl,
232 				token, code, id);
233 }
234 
coap_rst_init(struct coap_packet * cpkt,const struct coap_packet * req,uint8_t * data,uint16_t max_len)235 int coap_rst_init(struct coap_packet *cpkt, const struct coap_packet *req,
236 		  uint8_t *data, uint16_t max_len)
237 {
238 	uint16_t id;
239 	uint8_t ver;
240 
241 	ver = coap_header_get_version(req);
242 	id = coap_header_get_id(req);
243 
244 	return coap_packet_init(cpkt, data, max_len, ver, COAP_TYPE_RESET, 0,
245 				NULL, 0, id);
246 }
247 
option_header_set_delta(uint8_t * opt,uint8_t delta)248 static void option_header_set_delta(uint8_t *opt, uint8_t delta)
249 {
250 	*opt = (delta & 0xF) << 4;
251 }
252 
option_header_set_len(uint8_t * opt,uint8_t len)253 static void option_header_set_len(uint8_t *opt, uint8_t len)
254 {
255 	*opt |= (len & 0xF);
256 }
257 
encode_extended_option(uint16_t num,uint8_t * opt,uint16_t * ext)258 static uint8_t encode_extended_option(uint16_t num, uint8_t *opt, uint16_t *ext)
259 {
260 	if (num < COAP_OPTION_EXT_13) {
261 		*opt = num;
262 		*ext = 0U;
263 
264 		return 0;
265 	} else if (num < COAP_OPTION_EXT_269) {
266 		*opt = COAP_OPTION_EXT_13;
267 		*ext = num - COAP_OPTION_EXT_13;
268 
269 		return 1;
270 	}
271 
272 	*opt = COAP_OPTION_EXT_14;
273 	*ext = num - COAP_OPTION_EXT_269;
274 
275 	return 2;
276 }
277 
278 /* Insert an option at position `offset`. This is not adjusting the code delta of the
279  * option that follows the inserted one!
280  */
encode_option(struct coap_packet * cpkt,uint16_t code,const uint8_t * value,uint16_t len,size_t offset)281 static int encode_option(struct coap_packet *cpkt, uint16_t code, const uint8_t *value,
282 			 uint16_t len, size_t offset)
283 {
284 	uint16_t delta_ext; /* Extended delta */
285 	uint16_t len_ext; /* Extended length */
286 	uint8_t opt; /* delta | len */
287 	uint8_t opt_delta;
288 	uint8_t opt_len;
289 	uint8_t delta_size;
290 	uint8_t len_size;
291 	bool res;
292 
293 	delta_size = encode_extended_option(code, &opt_delta, &delta_ext);
294 	len_size = encode_extended_option(len, &opt_len, &len_ext);
295 
296 	option_header_set_delta(&opt, opt_delta);
297 	option_header_set_len(&opt, opt_len);
298 
299 	res = insert_u8(cpkt, opt, offset);
300 	++offset;
301 	if (!res) {
302 		return -EINVAL;
303 	}
304 
305 	if (delta_size == 1U) {
306 		res = insert_u8(cpkt, (uint8_t)delta_ext, offset);
307 		++offset;
308 		if (!res) {
309 			return -EINVAL;
310 		}
311 	} else if (delta_size == 2U) {
312 		res = insert_be16(cpkt, delta_ext, offset);
313 		offset += 2;
314 		if (!res) {
315 			return -EINVAL;
316 		}
317 	}
318 
319 	if (len_size == 1U) {
320 		res = insert_u8(cpkt, (uint8_t)len_ext, offset);
321 		++offset;
322 		if (!res) {
323 			return -EINVAL;
324 		}
325 	} else if (len_size == 2U) {
326 		res = insert_be16(cpkt, len_ext, offset);
327 		offset += 2;
328 		if (!res) {
329 			return -EINVAL;
330 		}
331 	}
332 
333 	if (len && value) {
334 		res = insert(cpkt, value, len, offset);
335 		/* no need to update local offset */
336 		if (!res) {
337 			return -EINVAL;
338 		}
339 	}
340 
341 	return  (1 + delta_size + len_size + len);
342 }
343 
coap_packet_append_option(struct coap_packet * cpkt,uint16_t code,const uint8_t * value,uint16_t len)344 int coap_packet_append_option(struct coap_packet *cpkt, uint16_t code,
345 			      const uint8_t *value, uint16_t len)
346 {
347 	int r;
348 
349 	if (!cpkt) {
350 		return -EINVAL;
351 	}
352 
353 	if (len && !value) {
354 		return -EINVAL;
355 	}
356 
357 	if (code < cpkt->delta) {
358 		NET_DBG("Option is not added in ascending order");
359 		return insert_option(cpkt, code, value, len);
360 	}
361 
362 	/* Calculate delta, if this option is not the first one */
363 	if (cpkt->opt_len) {
364 		code = (code == cpkt->delta) ? 0 : code - cpkt->delta;
365 	}
366 
367 	r = encode_option(cpkt, code, value, len, cpkt->hdr_len + cpkt->opt_len);
368 	if (r < 0) {
369 		return -EINVAL;
370 	}
371 
372 	cpkt->opt_len += r;
373 	cpkt->delta += code;
374 
375 	return 0;
376 }
377 
coap_append_option_int(struct coap_packet * cpkt,uint16_t code,unsigned int val)378 int coap_append_option_int(struct coap_packet *cpkt, uint16_t code,
379 			   unsigned int val)
380 {
381 	uint8_t data[4], len;
382 
383 	if (val == 0U) {
384 		data[0] = 0U;
385 		len = 0U;
386 	} else if (val < 0xFF) {
387 		data[0] = (uint8_t) val;
388 		len = 1U;
389 	} else if (val < 0xFFFF) {
390 		sys_put_be16(val, data);
391 		len = 2U;
392 	} else if (val < 0xFFFFFF) {
393 		sys_put_be16(val, &data[1]);
394 		data[0] = val >> 16;
395 		len = 3U;
396 	} else {
397 		sys_put_be32(val, data);
398 		len = 4U;
399 	}
400 
401 	return coap_packet_append_option(cpkt, code, data, len);
402 }
403 
coap_option_value_to_int(const struct coap_option * option)404 unsigned int coap_option_value_to_int(const struct coap_option *option)
405 {
406 	switch (option->len) {
407 	case 0:
408 		return 0;
409 	case 1:
410 		return option->value[0];
411 	case 2:
412 		return (option->value[1] << 0) | (option->value[0] << 8);
413 	case 3:
414 		return (option->value[2] << 0) | (option->value[1] << 8) |
415 			(option->value[0] << 16);
416 	case 4:
417 		return (option->value[3] << 0) | (option->value[2] << 8) |
418 			(option->value[1] << 16) | (option->value[0] << 24);
419 	default:
420 		return 0;
421 	}
422 
423 	return 0;
424 }
425 
coap_packet_append_payload_marker(struct coap_packet * cpkt)426 int coap_packet_append_payload_marker(struct coap_packet *cpkt)
427 {
428 	return append_u8(cpkt, COAP_MARKER) ? 0 : -EINVAL;
429 }
430 
coap_packet_append_payload(struct coap_packet * cpkt,const uint8_t * payload,uint16_t payload_len)431 int coap_packet_append_payload(struct coap_packet *cpkt, const uint8_t *payload,
432 			       uint16_t payload_len)
433 {
434 	return append(cpkt, payload, payload_len) ? 0 : -EINVAL;
435 }
436 
coap_next_token(void)437 uint8_t *coap_next_token(void)
438 {
439 	static uint8_t token[COAP_TOKEN_MAX_LEN];
440 
441 	sys_rand_get(token, COAP_TOKEN_MAX_LEN);
442 
443 	return token;
444 }
445 
option_header_get_delta(uint8_t opt)446 static uint8_t option_header_get_delta(uint8_t opt)
447 {
448 	return (opt & 0xF0) >> 4;
449 }
450 
option_header_get_len(uint8_t opt)451 static uint8_t option_header_get_len(uint8_t opt)
452 {
453 	return opt & 0x0F;
454 }
455 
read_u8(uint8_t * data,uint16_t offset,uint16_t * pos,uint16_t max_len,uint8_t * value)456 static int read_u8(uint8_t *data, uint16_t offset, uint16_t *pos,
457 		   uint16_t max_len, uint8_t *value)
458 {
459 	if (max_len - offset < 1) {
460 		return -EINVAL;
461 	}
462 
463 	*value = data[offset++];
464 	*pos = offset;
465 
466 	return max_len - offset;
467 }
468 
read_be16(uint8_t * data,uint16_t offset,uint16_t * pos,uint16_t max_len,uint16_t * value)469 static int read_be16(uint8_t *data, uint16_t offset, uint16_t *pos,
470 		     uint16_t max_len, uint16_t *value)
471 {
472 	if (max_len - offset < 2) {
473 		return -EINVAL;
474 	}
475 
476 	*value = data[offset++] << 8;
477 	*value |= data[offset++];
478 	*pos = offset;
479 
480 	return max_len - offset;
481 }
482 
read(uint8_t * data,uint16_t offset,uint16_t * pos,uint16_t max_len,uint16_t len,uint8_t * value)483 static int read(uint8_t *data, uint16_t offset, uint16_t *pos,
484 		uint16_t max_len, uint16_t len, uint8_t *value)
485 {
486 	if (max_len - offset < len) {
487 		return -EINVAL;
488 	}
489 
490 	memcpy(value, data + offset, len);
491 	offset += len;
492 	*pos = offset;
493 
494 	return max_len - offset;
495 }
496 
decode_delta(uint8_t * data,uint16_t offset,uint16_t * pos,uint16_t max_len,uint16_t opt,uint16_t * opt_ext,uint16_t * hdr_len)497 static int decode_delta(uint8_t *data, uint16_t offset, uint16_t *pos, uint16_t max_len,
498 			uint16_t opt, uint16_t *opt_ext, uint16_t *hdr_len)
499 {
500 	int ret = 0;
501 
502 	if (opt == COAP_OPTION_EXT_13) {
503 		uint8_t val;
504 
505 		*hdr_len = 1U;
506 
507 		ret = read_u8(data, offset, pos, max_len, &val);
508 		if (ret < 0) {
509 			return -EINVAL;
510 		}
511 
512 		opt = val + COAP_OPTION_EXT_13;
513 	} else if (opt == COAP_OPTION_EXT_14) {
514 		uint16_t val;
515 
516 		*hdr_len = 2U;
517 
518 		ret = read_be16(data, offset, pos, max_len, &val);
519 		if (ret < 0) {
520 			return -EINVAL;
521 		}
522 
523 		opt = val + COAP_OPTION_EXT_269;
524 	} else if (opt == COAP_OPTION_EXT_15) {
525 		return -EINVAL;
526 	}
527 
528 	*opt_ext = opt;
529 
530 	return ret;
531 }
532 
parse_option(uint8_t * data,uint16_t offset,uint16_t * pos,uint16_t max_len,uint16_t * opt_delta,uint16_t * opt_len,struct coap_option * option)533 static int parse_option(uint8_t *data, uint16_t offset, uint16_t *pos,
534 			uint16_t max_len, uint16_t *opt_delta, uint16_t *opt_len,
535 			struct coap_option *option)
536 {
537 	uint16_t hdr_len;
538 	uint16_t delta;
539 	uint16_t len;
540 	uint8_t opt;
541 	int r;
542 
543 	r = read_u8(data, offset, pos, max_len, &opt);
544 	if (r < 0) {
545 		return r;
546 	}
547 
548 	/* This indicates that options have ended */
549 	if (opt == COAP_MARKER) {
550 		/* packet w/ marker but no payload is malformed */
551 		return r > 0 ? 0 : -EINVAL;
552 	}
553 
554 	*opt_len += 1U;
555 
556 	delta = option_header_get_delta(opt);
557 	len = option_header_get_len(opt);
558 
559 	/* r == 0 means no more data to read from fragment, but delta
560 	 * field shows that packet should contain more data, it must
561 	 * be a malformed packet.
562 	 */
563 	if (r == 0 && delta > COAP_OPTION_NO_EXT) {
564 		return -EINVAL;
565 	}
566 
567 	if (delta > COAP_OPTION_NO_EXT) {
568 		/* In case 'delta' doesn't fit the option fixed header. */
569 		r = decode_delta(data, *pos, pos, max_len,
570 				 delta, &delta, &hdr_len);
571 		if ((r < 0) || (r == 0 && len > COAP_OPTION_NO_EXT)) {
572 			return -EINVAL;
573 		}
574 
575 		if (u16_add_overflow(*opt_len, hdr_len, opt_len)) {
576 			return -EINVAL;
577 		}
578 	}
579 
580 	if (len > COAP_OPTION_NO_EXT) {
581 		/* In case 'len' doesn't fit the option fixed header. */
582 		r = decode_delta(data, *pos, pos, max_len,
583 				 len, &len, &hdr_len);
584 		if (r < 0) {
585 			return -EINVAL;
586 		}
587 
588 		if (u16_add_overflow(*opt_len, hdr_len, opt_len)) {
589 			return -EINVAL;
590 		}
591 	}
592 
593 	if (u16_add_overflow(*opt_delta, delta, opt_delta) ||
594 	    u16_add_overflow(*opt_len, len, opt_len)) {
595 		return -EINVAL;
596 	}
597 
598 	if (r == 0 && len != 0U) {
599 		/* r == 0 means no more data to read from fragment, but len
600 		 * field shows that packet should contain more data, it must
601 		 * be a malformed packet.
602 		 */
603 		return -EINVAL;
604 	}
605 
606 	if (option) {
607 		/*
608 		 * Make sure the option data will fit into the value field of
609 		 * coap_option.
610 		 * NOTE: To expand the size of the value field set:
611 		 * CONFIG_COAP_EXTENDED_OPTIONS_LEN=y
612 		 * CONFIG_COAP_EXTENDED_OPTIONS_LEN_VALUE=<size>
613 		 */
614 		if (len > sizeof(option->value)) {
615 			NET_ERR("%u is > sizeof(coap_option->value)(%zu)!",
616 				len, sizeof(option->value));
617 			return -EINVAL;
618 		}
619 
620 		option->delta = *opt_delta;
621 		option->len = len;
622 		r = read(data, *pos, pos, max_len, len, &option->value[0]);
623 		if (r < 0) {
624 			return -EINVAL;
625 		}
626 	} else {
627 		if (u16_add_overflow(*pos, len, pos)) {
628 			return -EINVAL;
629 		}
630 
631 		r = max_len - *pos;
632 	}
633 
634 	return r;
635 }
636 
637 /* Remove the raw data of an option. Also adjusting offsets.
638  * But not adjusting code delta of the option after the removed one.
639  */
remove_option_data(struct coap_packet * cpkt,const uint16_t to_offset,const uint16_t from_offset)640 static void remove_option_data(struct coap_packet *cpkt,
641 			       const uint16_t to_offset,
642 			       const uint16_t from_offset)
643 {
644 	const uint16_t move_size = from_offset - to_offset;
645 
646 	memmove(cpkt->data + to_offset, cpkt->data + from_offset, cpkt->offset - from_offset);
647 	cpkt->opt_len -= move_size;
648 	cpkt->offset -= move_size;
649 }
650 
651 /* Remove an option (that is not the last one).
652  * Also adjusting the code delta of the option following the removed one.
653  */
remove_middle_option(struct coap_packet * cpkt,uint16_t offset,uint16_t opt_delta,const uint16_t previous_offset,const uint16_t previous_code)654 static int remove_middle_option(struct coap_packet *cpkt,
655 				uint16_t offset,
656 				uint16_t opt_delta,
657 				const uint16_t previous_offset,
658 				const uint16_t previous_code)
659 {
660 	int r;
661 	struct coap_option option;
662 	uint16_t opt_len = 0;
663 
664 	/* get the option after the removed one */
665 	r = parse_option(cpkt->data, offset, &offset, cpkt->hdr_len + cpkt->opt_len,
666 			 &opt_delta, &opt_len, &option);
667 	if (r < 0) {
668 		return -EILSEQ;
669 	}
670 
671 	/* clear requested option and the one after (delta changed) */
672 	remove_option_data(cpkt, previous_offset, offset);
673 
674 	/* reinsert option that comes after the removed option (with adjusted delta) */
675 	r = encode_option(cpkt, option.delta - previous_code, option.value, option.len,
676 			  previous_offset);
677 	if (r < 0) {
678 		return -EINVAL;
679 	}
680 	cpkt->opt_len += r;
681 
682 	return 0;
683 }
coap_packet_remove_option(struct coap_packet * cpkt,uint16_t code)684 int coap_packet_remove_option(struct coap_packet *cpkt, uint16_t code)
685 {
686 	uint16_t offset = 0;
687 	uint16_t opt_delta = 0;
688 	uint16_t opt_len = 0;
689 	uint16_t previous_offset = 0;
690 	uint16_t previous_code = 0;
691 	struct coap_option option;
692 	int r;
693 
694 	if (!cpkt) {
695 		return -EINVAL;
696 	}
697 
698 	if (cpkt->opt_len == 0) {
699 		return 0;
700 	}
701 
702 	if (code > cpkt->delta) {
703 		return 0;
704 	}
705 
706 	offset = cpkt->hdr_len;
707 	previous_offset = cpkt->hdr_len;
708 
709 	/* Find the requested option */
710 	while (offset < cpkt->hdr_len + cpkt->opt_len) {
711 		r = parse_option(cpkt->data, offset, &offset, cpkt->hdr_len + cpkt->opt_len,
712 				 &opt_delta, &opt_len, &option);
713 		if (r < 0) {
714 			return -EILSEQ;
715 		}
716 
717 		if (opt_delta == code) {
718 			break;
719 		}
720 
721 		if (opt_delta > code) {
722 			return 0;
723 		}
724 
725 		previous_code = opt_delta;
726 		previous_offset = offset;
727 	}
728 
729 	/* Check if the found option is the last option */
730 	if (cpkt->opt_len > opt_len) {
731 		/* not last option */
732 		r = remove_middle_option(cpkt, offset, opt_delta, previous_offset, previous_code);
733 		if (r < 0) {
734 			return r;
735 		}
736 	} else {
737 		/* last option */
738 		remove_option_data(cpkt, previous_offset, cpkt->hdr_len + cpkt->opt_len);
739 		cpkt->delta = previous_code;
740 	}
741 
742 	return 0;
743 }
744 
coap_packet_parse(struct coap_packet * cpkt,uint8_t * data,uint16_t len,struct coap_option * options,uint8_t opt_num)745 int coap_packet_parse(struct coap_packet *cpkt, uint8_t *data, uint16_t len,
746 		      struct coap_option *options, uint8_t opt_num)
747 {
748 	uint16_t opt_len;
749 	uint16_t offset;
750 	uint16_t delta;
751 	uint8_t num;
752 	uint8_t tkl;
753 	int ret;
754 
755 	if (!cpkt || !data) {
756 		return -EINVAL;
757 	}
758 
759 	if (len < BASIC_HEADER_SIZE) {
760 		return -EINVAL;
761 	}
762 
763 	if (options) {
764 		memset(options, 0, opt_num * sizeof(struct coap_option));
765 	}
766 
767 	cpkt->data = data;
768 	cpkt->offset = len;
769 	cpkt->max_len = len;
770 	cpkt->opt_len = 0U;
771 	cpkt->hdr_len = 0U;
772 	cpkt->delta = 0U;
773 
774 	/* Token lengths 9-15 are reserved. */
775 	tkl = cpkt->data[0] & 0x0f;
776 	if (tkl > 8) {
777 		return -EBADMSG;
778 	}
779 
780 	cpkt->hdr_len = BASIC_HEADER_SIZE + tkl;
781 	if (cpkt->hdr_len > len) {
782 		return -EBADMSG;
783 	}
784 
785 	if (cpkt->hdr_len == len) {
786 		return 0;
787 	}
788 
789 	offset = cpkt->hdr_len;
790 	opt_len = 0U;
791 	delta = 0U;
792 	num = 0U;
793 
794 	while (1) {
795 		struct coap_option *option;
796 
797 		option = num < opt_num ? &options[num++] : NULL;
798 		ret = parse_option(cpkt->data, offset, &offset, cpkt->max_len,
799 				   &delta, &opt_len, option);
800 		if (ret < 0) {
801 			return -EILSEQ;
802 		} else if (ret == 0) {
803 			break;
804 		}
805 	}
806 
807 	cpkt->opt_len = opt_len;
808 	cpkt->delta = delta;
809 
810 	return 0;
811 }
812 
coap_packet_set_path(struct coap_packet * cpkt,const char * path)813 int coap_packet_set_path(struct coap_packet *cpkt, const char *path)
814 {
815 	int ret = 0;
816 	int path_start, path_end;
817 	int path_length;
818 	bool contains_query = false;
819 	int i;
820 
821 	path_start = 0;
822 	path_end = 0;
823 	path_length = strlen(path);
824 	for (i = 0; i < path_length; i++) {
825 		path_end = i;
826 		if (path[i] == COAP_PATH_ELEM_DELIM) {
827 			/* Guard for preceding delimiters */
828 			if (path_start < path_end) {
829 				ret = coap_packet_append_option(cpkt, COAP_OPTION_URI_PATH,
830 								path + path_start,
831 								path_end - path_start);
832 				if (ret < 0) {
833 					LOG_ERR("Failed to append path to CoAP message");
834 					goto out;
835 				}
836 			}
837 			/* Check if there is a new path after delimiter,
838 			 * if not, point to the end of string to not add
839 			 * new option after this
840 			 */
841 			if (path_length > i + 1) {
842 				path_start = i + 1;
843 			} else {
844 				path_start = path_length;
845 			}
846 		} else if (path[i] == COAP_PATH_ELEM_QUERY) {
847 			/* Guard for preceding delimiters */
848 			if (path_start < path_end) {
849 				ret = coap_packet_append_option(cpkt, COAP_OPTION_URI_PATH,
850 								path + path_start,
851 								path_end - path_start);
852 				if (ret < 0) {
853 					LOG_ERR("Failed to append path to CoAP message");
854 					goto out;
855 				}
856 			}
857 			/* Rest of the path is query */
858 			contains_query = true;
859 			if (path_length > i + 1) {
860 				path_start = i + 1;
861 			} else {
862 				path_start = path_length;
863 			}
864 			break;
865 		}
866 	}
867 
868 	if (contains_query) {
869 		for (i = path_start; i < path_length; i++) {
870 			path_end = i;
871 			if (path[i] == COAP_PATH_ELEM_AMP || path[i] == COAP_PATH_ELEM_QUERY) {
872 				/* Guard for preceding delimiters */
873 				if (path_start < path_end) {
874 					ret = coap_packet_append_option(cpkt, COAP_OPTION_URI_QUERY,
875 									path + path_start,
876 									path_end - path_start);
877 					if (ret < 0) {
878 						LOG_ERR("Failed to append path to CoAP message");
879 						goto out;
880 					}
881 				}
882 				/* Check if there is a new query option after delimiter,
883 				 * if not, point to the end of string to not add
884 				 * new option after this
885 				 */
886 				if (path_length > i + 1) {
887 					path_start = i + 1;
888 				} else {
889 					path_start = path_length;
890 				}
891 			}
892 		}
893 	}
894 
895 	if (path_start < path_length) {
896 		if (contains_query) {
897 			ret = coap_packet_append_option(cpkt, COAP_OPTION_URI_QUERY,
898 							path + path_start,
899 							path_end - path_start + 1);
900 		} else {
901 			ret = coap_packet_append_option(cpkt, COAP_OPTION_URI_PATH,
902 							path + path_start,
903 							path_end - path_start + 1);
904 		}
905 		if (ret < 0) {
906 			LOG_ERR("Failed to append path to CoAP message");
907 			goto out;
908 		}
909 	}
910 
911 out:
912 	return ret;
913 }
914 
coap_find_options(const struct coap_packet * cpkt,uint16_t code,struct coap_option * options,uint16_t veclen)915 int coap_find_options(const struct coap_packet *cpkt, uint16_t code,
916 		      struct coap_option *options, uint16_t veclen)
917 {
918 	uint16_t opt_len;
919 	uint16_t offset;
920 	uint16_t delta;
921 	uint8_t num;
922 	int r;
923 
924 	/* Check if there are options to parse */
925 	if (cpkt->hdr_len == cpkt->max_len) {
926 		return 0;
927 	}
928 
929 	offset = cpkt->hdr_len;
930 	opt_len = 0U;
931 	delta = 0U;
932 	num = 0U;
933 
934 	while (delta <= code && num < veclen) {
935 		r = parse_option(cpkt->data, offset, &offset,
936 				 cpkt->max_len, &delta, &opt_len,
937 				 &options[num]);
938 		if (r < 0) {
939 			return -EINVAL;
940 		}
941 
942 		if (code == options[num].delta) {
943 			num++;
944 		}
945 
946 		if (r == 0) {
947 			break;
948 		}
949 	}
950 
951 	return num;
952 }
953 
coap_header_get_version(const struct coap_packet * cpkt)954 uint8_t coap_header_get_version(const struct coap_packet *cpkt)
955 {
956 	if (!cpkt || !cpkt->data) {
957 		return 0;
958 	}
959 
960 	return (cpkt->data[0] & 0xC0) >> 6;
961 }
962 
coap_header_get_type(const struct coap_packet * cpkt)963 uint8_t coap_header_get_type(const struct coap_packet *cpkt)
964 {
965 	if (!cpkt || !cpkt->data) {
966 		return 0;
967 	}
968 
969 	return (cpkt->data[0] & 0x30) >> 4;
970 }
971 
__coap_header_get_code(const struct coap_packet * cpkt)972 static uint8_t __coap_header_get_code(const struct coap_packet *cpkt)
973 {
974 	if (!cpkt || !cpkt->data) {
975 		return 0;
976 	}
977 
978 	return cpkt->data[1];
979 }
980 
coap_header_set_code(const struct coap_packet * cpkt,uint8_t code)981 int coap_header_set_code(const struct coap_packet *cpkt, uint8_t code)
982 {
983 	if (!cpkt || !cpkt->data) {
984 		return -EINVAL;
985 	}
986 
987 	cpkt->data[1] = code;
988 	return 0;
989 }
990 
coap_header_get_token(const struct coap_packet * cpkt,uint8_t * token)991 uint8_t coap_header_get_token(const struct coap_packet *cpkt, uint8_t *token)
992 {
993 	uint8_t tkl;
994 
995 	if (!cpkt || !cpkt->data) {
996 		return 0;
997 	}
998 
999 	tkl = cpkt->data[0] & 0x0f;
1000 	if (tkl > COAP_TOKEN_MAX_LEN) {
1001 		return 0;
1002 	}
1003 
1004 	if (tkl) {
1005 		memcpy(token, cpkt->data + BASIC_HEADER_SIZE, tkl);
1006 	}
1007 
1008 	return tkl;
1009 }
1010 
coap_header_get_code(const struct coap_packet * cpkt)1011 uint8_t coap_header_get_code(const struct coap_packet *cpkt)
1012 {
1013 	uint8_t code = __coap_header_get_code(cpkt);
1014 
1015 	switch (code) {
1016 	/* Methods are encoded in the code field too */
1017 	case COAP_METHOD_GET:
1018 	case COAP_METHOD_POST:
1019 	case COAP_METHOD_PUT:
1020 	case COAP_METHOD_DELETE:
1021 	case COAP_METHOD_FETCH:
1022 	case COAP_METHOD_PATCH:
1023 	case COAP_METHOD_IPATCH:
1024 
1025 	/* All the defined response codes */
1026 	case COAP_RESPONSE_CODE_OK:
1027 	case COAP_RESPONSE_CODE_CREATED:
1028 	case COAP_RESPONSE_CODE_DELETED:
1029 	case COAP_RESPONSE_CODE_VALID:
1030 	case COAP_RESPONSE_CODE_CHANGED:
1031 	case COAP_RESPONSE_CODE_CONTENT:
1032 	case COAP_RESPONSE_CODE_CONTINUE:
1033 	case COAP_RESPONSE_CODE_BAD_REQUEST:
1034 	case COAP_RESPONSE_CODE_UNAUTHORIZED:
1035 	case COAP_RESPONSE_CODE_BAD_OPTION:
1036 	case COAP_RESPONSE_CODE_FORBIDDEN:
1037 	case COAP_RESPONSE_CODE_NOT_FOUND:
1038 	case COAP_RESPONSE_CODE_NOT_ALLOWED:
1039 	case COAP_RESPONSE_CODE_NOT_ACCEPTABLE:
1040 	case COAP_RESPONSE_CODE_INCOMPLETE:
1041 	case COAP_RESPONSE_CODE_CONFLICT:
1042 	case COAP_RESPONSE_CODE_PRECONDITION_FAILED:
1043 	case COAP_RESPONSE_CODE_REQUEST_TOO_LARGE:
1044 	case COAP_RESPONSE_CODE_UNSUPPORTED_CONTENT_FORMAT:
1045 	case COAP_RESPONSE_CODE_UNPROCESSABLE_ENTITY:
1046 	case COAP_RESPONSE_CODE_TOO_MANY_REQUESTS:
1047 	case COAP_RESPONSE_CODE_INTERNAL_ERROR:
1048 	case COAP_RESPONSE_CODE_NOT_IMPLEMENTED:
1049 	case COAP_RESPONSE_CODE_BAD_GATEWAY:
1050 	case COAP_RESPONSE_CODE_SERVICE_UNAVAILABLE:
1051 	case COAP_RESPONSE_CODE_GATEWAY_TIMEOUT:
1052 	case COAP_RESPONSE_CODE_PROXYING_NOT_SUPPORTED:
1053 	case COAP_CODE_EMPTY:
1054 		return code;
1055 	default:
1056 		return COAP_CODE_EMPTY;
1057 	}
1058 }
1059 
coap_header_get_id(const struct coap_packet * cpkt)1060 uint16_t coap_header_get_id(const struct coap_packet *cpkt)
1061 {
1062 	if (!cpkt || !cpkt->data) {
1063 		return 0;
1064 	}
1065 
1066 	return (cpkt->data[2] << 8) | cpkt->data[3];
1067 }
1068 
coap_packet_get_payload(const struct coap_packet * cpkt,uint16_t * len)1069 const uint8_t *coap_packet_get_payload(const struct coap_packet *cpkt, uint16_t *len)
1070 {
1071 	int payload_len;
1072 
1073 	if (!cpkt || !len) {
1074 		return NULL;
1075 	}
1076 
1077 	payload_len = cpkt->offset - cpkt->hdr_len - cpkt->opt_len;
1078 	if (payload_len > 1) {
1079 		*len = payload_len - 1;	/* subtract payload marker length */
1080 	} else {
1081 		*len = 0U;
1082 	}
1083 
1084 	return *len == 0 ? NULL :
1085 		cpkt->data + cpkt->hdr_len + cpkt->opt_len + 1;
1086 }
1087 
coap_uri_path_match(const char * const * path,struct coap_option * options,uint8_t opt_num)1088 bool coap_uri_path_match(const char * const *path,
1089 			 struct coap_option *options,
1090 			 uint8_t opt_num)
1091 {
1092 	uint8_t i;
1093 	uint8_t j = 0U;
1094 
1095 	for (i = 0U; i < opt_num && path[j]; i++) {
1096 		if (options[i].delta != COAP_OPTION_URI_PATH) {
1097 			continue;
1098 		}
1099 
1100 		if (IS_ENABLED(CONFIG_COAP_URI_WILDCARD) && strlen(path[j]) == 1) {
1101 			if (*path[j] == '+') {
1102 				/* Single-level wildcard */
1103 				j++;
1104 				continue;
1105 			} else if (*path[j] == '#') {
1106 				/* Multi-level wildcard */
1107 				return true;
1108 			}
1109 		}
1110 
1111 		if (options[i].len != strlen(path[j])) {
1112 			return false;
1113 		}
1114 
1115 		if (memcmp(options[i].value, path[j], options[i].len)) {
1116 			return false;
1117 		}
1118 
1119 		j++;
1120 	}
1121 
1122 	if (path[j]) {
1123 		return false;
1124 	}
1125 
1126 	for (; i < opt_num; i++) {
1127 		if (options[i].delta == COAP_OPTION_URI_PATH) {
1128 			return false;
1129 		}
1130 	}
1131 
1132 	return true;
1133 }
1134 
method_from_code(const struct coap_resource * resource,uint8_t code,coap_method_t * method)1135 static int method_from_code(const struct coap_resource *resource,
1136 			    uint8_t code, coap_method_t *method)
1137 {
1138 	switch (code) {
1139 	case COAP_METHOD_GET:
1140 		*method = resource->get;
1141 		return 0;
1142 	case COAP_METHOD_POST:
1143 		*method = resource->post;
1144 		return 0;
1145 	case COAP_METHOD_PUT:
1146 		*method = resource->put;
1147 		return 0;
1148 	case COAP_METHOD_DELETE:
1149 		*method = resource->del;
1150 		return 0;
1151 	case COAP_METHOD_FETCH:
1152 		*method = resource->fetch;
1153 		return 0;
1154 	case COAP_METHOD_PATCH:
1155 		*method = resource->patch;
1156 		return 0;
1157 	case COAP_METHOD_IPATCH:
1158 		*method = resource->ipatch;
1159 		return 0;
1160 	default:
1161 		return -EINVAL;
1162 	}
1163 }
1164 
1165 
is_empty_message(const struct coap_packet * cpkt)1166 static inline bool is_empty_message(const struct coap_packet *cpkt)
1167 {
1168 	return __coap_header_get_code(cpkt) == COAP_CODE_EMPTY;
1169 }
1170 
coap_packet_is_request(const struct coap_packet * cpkt)1171 bool coap_packet_is_request(const struct coap_packet *cpkt)
1172 {
1173 	uint8_t code = coap_header_get_code(cpkt);
1174 
1175 	return !(code & ~COAP_REQUEST_MASK);
1176 }
1177 
coap_handle_request_len(struct coap_packet * cpkt,struct coap_resource * resources,size_t resources_len,struct coap_option * options,uint8_t opt_num,struct sockaddr * addr,socklen_t addr_len)1178 int coap_handle_request_len(struct coap_packet *cpkt,
1179 			    struct coap_resource *resources,
1180 			    size_t resources_len,
1181 			    struct coap_option *options,
1182 			    uint8_t opt_num,
1183 			    struct sockaddr *addr, socklen_t addr_len)
1184 {
1185 	if (!coap_packet_is_request(cpkt)) {
1186 		return 0;
1187 	}
1188 
1189 	/* FIXME: deal with hierarchical resources */
1190 	for (size_t i = 0; i < resources_len; i++) {
1191 		coap_method_t method;
1192 		uint8_t code;
1193 
1194 		if (!coap_uri_path_match(resources[i].path, options, opt_num)) {
1195 			continue;
1196 		}
1197 
1198 		code = coap_header_get_code(cpkt);
1199 		if (method_from_code(&resources[i], code, &method) < 0) {
1200 			return -ENOTSUP;
1201 		}
1202 
1203 		if (!method) {
1204 			return -EPERM;
1205 		}
1206 
1207 		return method(&resources[i], cpkt, addr, addr_len);
1208 	}
1209 
1210 	return -ENOENT;
1211 }
1212 
coap_handle_request(struct coap_packet * cpkt,struct coap_resource * resources,struct coap_option * options,uint8_t opt_num,struct sockaddr * addr,socklen_t addr_len)1213 int coap_handle_request(struct coap_packet *cpkt,
1214 			struct coap_resource *resources,
1215 			struct coap_option *options,
1216 			uint8_t opt_num,
1217 			struct sockaddr *addr, socklen_t addr_len)
1218 {
1219 	size_t resources_len = 0;
1220 	struct coap_resource *resource;
1221 
1222 	for (resource = resources; resource && resource->path; resource++) {
1223 		resources_len++;
1224 	}
1225 
1226 	return coap_handle_request_len(cpkt, resources, resources_len, options, opt_num, addr,
1227 				       addr_len);
1228 }
1229 
coap_block_transfer_init(struct coap_block_context * ctx,enum coap_block_size block_size,size_t total_size)1230 int coap_block_transfer_init(struct coap_block_context *ctx,
1231 			      enum coap_block_size block_size,
1232 			      size_t total_size)
1233 {
1234 	ctx->block_size = block_size;
1235 	ctx->total_size = total_size;
1236 	ctx->current = 0;
1237 
1238 	return 0;
1239 }
1240 
1241 #define GET_BLOCK_SIZE(v) (((v) & 0x7))
1242 #define GET_MORE(v) (!!((v) & 0x08))
1243 #define GET_NUM(v) ((v) >> 4)
1244 
1245 #define SET_BLOCK_SIZE(v, b) (v |= ((b) & 0x07))
1246 #define SET_MORE(v, m) ((v) |= (m) ? 0x08 : 0x00)
1247 #define SET_NUM(v, n) ((v) |= ((n) << 4))
1248 
coap_append_descriptive_block_option(struct coap_packet * cpkt,struct coap_block_context * ctx)1249 int coap_append_descriptive_block_option(struct coap_packet *cpkt, struct coap_block_context *ctx)
1250 {
1251 	if (coap_packet_is_request(cpkt)) {
1252 		return coap_append_block1_option(cpkt, ctx);
1253 	} else {
1254 		return coap_append_block2_option(cpkt, ctx);
1255 	}
1256 }
1257 
coap_has_descriptive_block_option(struct coap_packet * cpkt)1258 bool coap_has_descriptive_block_option(struct coap_packet *cpkt)
1259 {
1260 	if (coap_packet_is_request(cpkt)) {
1261 		return coap_get_option_int(cpkt, COAP_OPTION_BLOCK1) >= 0;
1262 	} else {
1263 		return coap_get_option_int(cpkt, COAP_OPTION_BLOCK2) >= 0;
1264 	}
1265 }
1266 
coap_remove_descriptive_block_option(struct coap_packet * cpkt)1267 int coap_remove_descriptive_block_option(struct coap_packet *cpkt)
1268 {
1269 	if (coap_packet_is_request(cpkt)) {
1270 		return coap_packet_remove_option(cpkt, COAP_OPTION_BLOCK1);
1271 	} else {
1272 		return coap_packet_remove_option(cpkt, COAP_OPTION_BLOCK2);
1273 	}
1274 }
1275 
coap_block_has_more(struct coap_packet * cpkt)1276 bool coap_block_has_more(struct coap_packet *cpkt)
1277 {
1278 	bool more = false;
1279 	int opt;
1280 
1281 	if (coap_packet_is_request(cpkt)) {
1282 		opt = coap_get_option_int(cpkt, COAP_OPTION_BLOCK1);
1283 	} else {
1284 		opt = coap_get_option_int(cpkt, COAP_OPTION_BLOCK2);
1285 	}
1286 	if (opt >= 0) {
1287 		more = GET_MORE(opt);
1288 	}
1289 	return more;
1290 }
1291 
coap_append_block1_option(struct coap_packet * cpkt,struct coap_block_context * ctx)1292 int coap_append_block1_option(struct coap_packet *cpkt,
1293 			      struct coap_block_context *ctx)
1294 {
1295 	uint16_t bytes = coap_block_size_to_bytes(ctx->block_size);
1296 	unsigned int val = 0U;
1297 	int r;
1298 
1299 	if (coap_packet_is_request(cpkt)) {
1300 		SET_BLOCK_SIZE(val, ctx->block_size);
1301 		SET_MORE(val, ctx->current + bytes < ctx->total_size);
1302 		SET_NUM(val, ctx->current / bytes);
1303 	} else {
1304 		SET_BLOCK_SIZE(val, ctx->block_size);
1305 		SET_NUM(val, ctx->current / bytes);
1306 	}
1307 
1308 	r = coap_append_option_int(cpkt, COAP_OPTION_BLOCK1, val);
1309 
1310 	return r;
1311 }
1312 
coap_append_block2_option(struct coap_packet * cpkt,struct coap_block_context * ctx)1313 int coap_append_block2_option(struct coap_packet *cpkt,
1314 			      struct coap_block_context *ctx)
1315 {
1316 	int r, val = 0;
1317 	uint16_t bytes = coap_block_size_to_bytes(ctx->block_size);
1318 
1319 	if (coap_packet_is_request(cpkt)) {
1320 		SET_BLOCK_SIZE(val, ctx->block_size);
1321 		SET_NUM(val, ctx->current / bytes);
1322 	} else {
1323 		SET_BLOCK_SIZE(val, ctx->block_size);
1324 		SET_MORE(val, ctx->current + bytes < ctx->total_size);
1325 		SET_NUM(val, ctx->current / bytes);
1326 	}
1327 
1328 	r = coap_append_option_int(cpkt, COAP_OPTION_BLOCK2, val);
1329 
1330 	return r;
1331 }
1332 
coap_append_size1_option(struct coap_packet * cpkt,struct coap_block_context * ctx)1333 int coap_append_size1_option(struct coap_packet *cpkt,
1334 			     struct coap_block_context *ctx)
1335 {
1336 	return coap_append_option_int(cpkt, COAP_OPTION_SIZE1, ctx->total_size);
1337 }
1338 
coap_append_size2_option(struct coap_packet * cpkt,struct coap_block_context * ctx)1339 int coap_append_size2_option(struct coap_packet *cpkt,
1340 			     struct coap_block_context *ctx)
1341 {
1342 	return coap_append_option_int(cpkt, COAP_OPTION_SIZE2, ctx->total_size);
1343 }
1344 
coap_get_option_int(const struct coap_packet * cpkt,uint16_t code)1345 int coap_get_option_int(const struct coap_packet *cpkt, uint16_t code)
1346 {
1347 	struct coap_option option = {};
1348 	unsigned int val;
1349 	int count = 1;
1350 
1351 	count = coap_find_options(cpkt, code, &option, count);
1352 	if (count <= 0) {
1353 		return -ENOENT;
1354 	}
1355 
1356 	val = coap_option_value_to_int(&option);
1357 
1358 	return val;
1359 }
1360 
coap_get_block1_option(const struct coap_packet * cpkt,bool * has_more,uint32_t * block_number)1361 int coap_get_block1_option(const struct coap_packet *cpkt, bool *has_more, uint32_t *block_number)
1362 {
1363 	int ret = coap_get_option_int(cpkt, COAP_OPTION_BLOCK1);
1364 
1365 	if (ret < 0) {
1366 		return ret;
1367 	}
1368 
1369 	*has_more = GET_MORE(ret);
1370 	*block_number = GET_NUM(ret);
1371 	ret = 1 << (GET_BLOCK_SIZE(ret) + 4);
1372 	return ret;
1373 }
1374 
coap_get_block2_option(const struct coap_packet * cpkt,bool * has_more,uint32_t * block_number)1375 int coap_get_block2_option(const struct coap_packet *cpkt, bool *has_more,
1376 			   uint32_t *block_number)
1377 {
1378 	int ret = coap_get_option_int(cpkt, COAP_OPTION_BLOCK2);
1379 
1380 	if (ret < 0) {
1381 		return ret;
1382 	}
1383 
1384 	*has_more = GET_MORE(ret);
1385 	*block_number = GET_NUM(ret);
1386 	ret = 1 << (GET_BLOCK_SIZE(ret) + 4);
1387 	return ret;
1388 }
1389 
insert_option(struct coap_packet * cpkt,uint16_t code,const uint8_t * value,uint16_t len)1390 int insert_option(struct coap_packet *cpkt, uint16_t code, const uint8_t *value, uint16_t len)
1391 {
1392 	uint16_t offset = cpkt->hdr_len;
1393 	uint16_t opt_delta = 0;
1394 	uint16_t opt_len = 0;
1395 	uint16_t last_opt = 0;
1396 	uint16_t last_offset = cpkt->hdr_len;
1397 	struct coap_option option;
1398 	int r;
1399 
1400 	while (offset < cpkt->hdr_len + cpkt->opt_len) {
1401 		r = parse_option(cpkt->data, offset, &offset, cpkt->hdr_len + cpkt->opt_len,
1402 				 &opt_delta, &opt_len, &option);
1403 		if (r < 0) {
1404 			return -EILSEQ;
1405 		}
1406 
1407 		if (opt_delta > code) {
1408 			break;
1409 		}
1410 
1411 		last_opt = opt_delta;
1412 		last_offset = offset;
1413 	}
1414 
1415 	const uint16_t option_size = offset - last_offset;
1416 	/* clear option after new option (delta changed) */
1417 	memmove(cpkt->data + last_offset, cpkt->data + offset, cpkt->offset - offset);
1418 	cpkt->opt_len -= option_size;
1419 	cpkt->offset -= option_size;
1420 
1421 	/* add the new option */
1422 	const uint16_t new_option_delta = code - last_opt;
1423 
1424 	r = encode_option(cpkt, new_option_delta, value, len, last_offset);
1425 	if (r < 0) {
1426 		return -EINVAL;
1427 	}
1428 	cpkt->opt_len += r;
1429 
1430 	/* reinsert option that comes after the new option (with adjusted delta) */
1431 	r = encode_option(cpkt, option.delta - code, option.value, option.len, last_offset + r);
1432 	if (r < 0) {
1433 		return -EINVAL;
1434 	}
1435 	cpkt->opt_len += r;
1436 
1437 	return 0;
1438 }
1439 
update_descriptive_block(struct coap_block_context * ctx,int block,int size)1440 static int update_descriptive_block(struct coap_block_context *ctx,
1441 				    int block, int size)
1442 {
1443 	size_t new_current = GET_NUM(block) << (GET_BLOCK_SIZE(block) + 4);
1444 
1445 	if (block == -ENOENT) {
1446 		return 0;
1447 	}
1448 
1449 	if (size && ctx->total_size && ctx->total_size != size) {
1450 		return -EINVAL;
1451 	}
1452 
1453 	if (ctx->current > 0 && GET_BLOCK_SIZE(block) > ctx->block_size) {
1454 		return -EINVAL;
1455 	}
1456 
1457 	if (ctx->total_size && new_current > ctx->total_size) {
1458 		return -EINVAL;
1459 	}
1460 
1461 	if (size) {
1462 		ctx->total_size = size;
1463 	}
1464 	ctx->current = new_current;
1465 	ctx->block_size = MIN(GET_BLOCK_SIZE(block), ctx->block_size);
1466 
1467 	return 0;
1468 }
1469 
update_control_block1(struct coap_block_context * ctx,int block,int size)1470 static int update_control_block1(struct coap_block_context *ctx,
1471 				     int block, int size)
1472 {
1473 	size_t new_current = GET_NUM(block) << (GET_BLOCK_SIZE(block) + 4);
1474 
1475 	if (block == -ENOENT) {
1476 		return 0;
1477 	}
1478 
1479 	if (new_current != ctx->current) {
1480 		return -EINVAL;
1481 	}
1482 
1483 	if (GET_BLOCK_SIZE(block) > ctx->block_size) {
1484 		return -EINVAL;
1485 	}
1486 
1487 	ctx->block_size = GET_BLOCK_SIZE(block);
1488 
1489 	if (size >= 0) {
1490 		ctx->total_size = size;
1491 	}
1492 
1493 	return 0;
1494 }
1495 
update_control_block2(struct coap_block_context * ctx,int block,int size)1496 static int update_control_block2(struct coap_block_context *ctx,
1497 				 int block, int size)
1498 {
1499 	size_t new_current = GET_NUM(block) << (GET_BLOCK_SIZE(block) + 4);
1500 
1501 	if (block == -ENOENT) {
1502 		return 0;
1503 	}
1504 
1505 	if (GET_MORE(block)) {
1506 		return -EINVAL;
1507 	}
1508 
1509 	if (GET_NUM(block) > 0 && GET_BLOCK_SIZE(block) != ctx->block_size) {
1510 		return -EINVAL;
1511 	}
1512 
1513 	ctx->current = new_current;
1514 	ctx->block_size = MIN(GET_BLOCK_SIZE(block), ctx->block_size);
1515 
1516 	return 0;
1517 }
1518 
coap_update_from_block(const struct coap_packet * cpkt,struct coap_block_context * ctx)1519 int coap_update_from_block(const struct coap_packet *cpkt,
1520 			   struct coap_block_context *ctx)
1521 {
1522 	int r, block1, block2, size1, size2;
1523 
1524 	block1 = coap_get_option_int(cpkt, COAP_OPTION_BLOCK1);
1525 	block2 = coap_get_option_int(cpkt, COAP_OPTION_BLOCK2);
1526 	size1 = coap_get_option_int(cpkt, COAP_OPTION_SIZE1);
1527 	size2 = coap_get_option_int(cpkt, COAP_OPTION_SIZE2);
1528 
1529 	if (coap_packet_is_request(cpkt)) {
1530 		r = update_control_block2(ctx, block2, size2);
1531 		if (r) {
1532 			return r;
1533 		}
1534 
1535 		return update_descriptive_block(ctx, block1, size1 == -ENOENT ? 0 : size1);
1536 	}
1537 
1538 	r = update_control_block1(ctx, block1, size1);
1539 	if (r) {
1540 		return r;
1541 	}
1542 
1543 	return update_descriptive_block(ctx, block2, size2 == -ENOENT ? 0 : size2);
1544 }
1545 
coap_next_block_for_option(const struct coap_packet * cpkt,struct coap_block_context * ctx,enum coap_option_num option)1546 int coap_next_block_for_option(const struct coap_packet *cpkt,
1547 			       struct coap_block_context *ctx,
1548 			       enum coap_option_num option)
1549 {
1550 	int block;
1551 	uint16_t block_len;
1552 
1553 	if (option != COAP_OPTION_BLOCK1 && option != COAP_OPTION_BLOCK2) {
1554 		return -EINVAL;
1555 	}
1556 
1557 	block = coap_get_option_int(cpkt, option);
1558 
1559 	if (block < 0) {
1560 		return block;
1561 	}
1562 
1563 	coap_packet_get_payload(cpkt, &block_len);
1564 	/* Check that the package does not exceed the expected size ONLY */
1565 	if ((ctx->total_size > 0) &&
1566 	    (ctx->total_size < (ctx->current + block_len))) {
1567 		return -EMSGSIZE;
1568 	}
1569 	ctx->current += block_len;
1570 
1571 	if (!GET_MORE(block)) {
1572 		return 0;
1573 	}
1574 
1575 	return (int)ctx->current;
1576 }
1577 
coap_next_block(const struct coap_packet * cpkt,struct coap_block_context * ctx)1578 size_t coap_next_block(const struct coap_packet *cpkt,
1579 		       struct coap_block_context *ctx)
1580 {
1581 	enum coap_option_num option;
1582 	int ret;
1583 
1584 	option = coap_packet_is_request(cpkt) ? COAP_OPTION_BLOCK1 : COAP_OPTION_BLOCK2;
1585 	ret = coap_next_block_for_option(cpkt, ctx, option);
1586 
1587 	return MAX(ret, 0);
1588 }
1589 
coap_pending_init(struct coap_pending * pending,const struct coap_packet * request,const struct sockaddr * addr,const struct coap_transmission_parameters * params)1590 int coap_pending_init(struct coap_pending *pending,
1591 		      const struct coap_packet *request,
1592 		      const struct sockaddr *addr,
1593 		      const struct coap_transmission_parameters *params)
1594 {
1595 	memset(pending, 0, sizeof(*pending));
1596 
1597 	pending->id = coap_header_get_id(request);
1598 
1599 	memcpy(&pending->addr, addr, sizeof(*addr));
1600 
1601 	if (params) {
1602 		pending->params = *params;
1603 	} else {
1604 		pending->params = coap_transmission_params;
1605 	}
1606 
1607 	pending->data = request->data;
1608 	pending->len = request->offset;
1609 	pending->t0 = k_uptime_get();
1610 	pending->retries = pending->params.max_retransmission;
1611 
1612 	return 0;
1613 }
1614 
coap_pending_next_unused(struct coap_pending * pendings,size_t len)1615 struct coap_pending *coap_pending_next_unused(
1616 	struct coap_pending *pendings, size_t len)
1617 {
1618 	struct coap_pending *p;
1619 	size_t i;
1620 
1621 	for (i = 0, p = pendings; i < len; i++, p++) {
1622 		if (p->data == 0) {
1623 			return p;
1624 		}
1625 	}
1626 
1627 	return NULL;
1628 }
1629 
coap_reply_next_unused(struct coap_reply * replies,size_t len)1630 struct coap_reply *coap_reply_next_unused(
1631 	struct coap_reply *replies, size_t len)
1632 {
1633 	struct coap_reply *r;
1634 	size_t i;
1635 
1636 	for (i = 0, r = replies; i < len; i++, r++) {
1637 		if (!r->reply) {
1638 			return r;
1639 		}
1640 	}
1641 
1642 	return NULL;
1643 }
1644 
is_addr_unspecified(const struct sockaddr * addr)1645 static inline bool is_addr_unspecified(const struct sockaddr *addr)
1646 {
1647 	if (addr->sa_family == AF_UNSPEC) {
1648 		return true;
1649 	}
1650 
1651 	if (addr->sa_family == AF_INET6) {
1652 		return net_ipv6_is_addr_unspecified(
1653 			&(net_sin6(addr)->sin6_addr));
1654 	} else if (addr->sa_family == AF_INET) {
1655 		return net_sin(addr)->sin_addr.s4_addr32[0] == 0U;
1656 	}
1657 
1658 	return false;
1659 }
1660 
coap_observer_next_unused(struct coap_observer * observers,size_t len)1661 struct coap_observer *coap_observer_next_unused(
1662 	struct coap_observer *observers, size_t len)
1663 {
1664 	struct coap_observer *o;
1665 	size_t i;
1666 
1667 	for (i = 0, o = observers; i < len; i++, o++) {
1668 		if (is_addr_unspecified(&o->addr)) {
1669 			return o;
1670 		}
1671 	}
1672 
1673 	return NULL;
1674 }
1675 
coap_pending_received(const struct coap_packet * response,struct coap_pending * pendings,size_t len)1676 struct coap_pending *coap_pending_received(
1677 	const struct coap_packet *response,
1678 	struct coap_pending *pendings, size_t len)
1679 {
1680 	struct coap_pending *p;
1681 	uint16_t resp_id = coap_header_get_id(response);
1682 	size_t i;
1683 
1684 	for (i = 0, p = pendings; i < len; i++, p++) {
1685 		if (!p->timeout) {
1686 			continue;
1687 		}
1688 
1689 		if (resp_id != p->id) {
1690 			continue;
1691 		}
1692 
1693 		return p;
1694 	}
1695 
1696 	return NULL;
1697 }
1698 
coap_pending_next_to_expire(struct coap_pending * pendings,size_t len)1699 struct coap_pending *coap_pending_next_to_expire(
1700 	struct coap_pending *pendings, size_t len)
1701 {
1702 	struct coap_pending *p, *found = NULL;
1703 	size_t i;
1704 	int64_t expiry, min_expiry = INT64_MAX;
1705 
1706 	for (i = 0, p = pendings; i < len; i++, p++) {
1707 		if (!p->timeout) {
1708 			continue;
1709 		}
1710 
1711 		expiry = p->t0 + p->timeout;
1712 
1713 		if (expiry < min_expiry) {
1714 			min_expiry = expiry;
1715 			found = p;
1716 		}
1717 	}
1718 
1719 	return found;
1720 }
1721 
init_ack_timeout(const struct coap_transmission_parameters * params)1722 static uint32_t init_ack_timeout(const struct coap_transmission_parameters *params)
1723 {
1724 #if defined(CONFIG_COAP_RANDOMIZE_ACK_TIMEOUT)
1725 	const uint16_t random_percent = params->ack_random_percent ? params->ack_random_percent
1726 								   : CONFIG_COAP_ACK_RANDOM_PERCENT;
1727 	const uint32_t max_ack = params->ack_timeout * random_percent / 100U;
1728 	const uint32_t min_ack = params->ack_timeout;
1729 
1730 	/* Randomly generated initial ACK timeout
1731 	 * ACK_TIMEOUT < INIT_ACK_TIMEOUT < ACK_TIMEOUT * ACK_RANDOM_FACTOR
1732 	 * Ref: https://tools.ietf.org/html/rfc7252#section-4.8
1733 	 */
1734 	return min_ack + (sys_rand32_get() % (max_ack - min_ack));
1735 #else
1736 	return params->ack_timeout;
1737 #endif /* defined(CONFIG_COAP_RANDOMIZE_ACK_TIMEOUT) */
1738 }
1739 
coap_pending_cycle(struct coap_pending * pending)1740 bool coap_pending_cycle(struct coap_pending *pending)
1741 {
1742 	if (pending->timeout == 0) {
1743 		/* Initial transmission. */
1744 		pending->timeout = init_ack_timeout(&pending->params);
1745 		return true;
1746 	}
1747 
1748 	if (pending->retries == 0) {
1749 		return false;
1750 	}
1751 
1752 	pending->t0 += pending->timeout;
1753 	pending->timeout = pending->timeout * pending->params.coap_backoff_percent / 100;
1754 	pending->retries--;
1755 
1756 	return true;
1757 }
1758 
coap_pending_clear(struct coap_pending * pending)1759 void coap_pending_clear(struct coap_pending *pending)
1760 {
1761 	pending->timeout = 0;
1762 	pending->data = NULL;
1763 }
1764 
coap_pendings_clear(struct coap_pending * pendings,size_t len)1765 void coap_pendings_clear(struct coap_pending *pendings, size_t len)
1766 {
1767 	struct coap_pending *p;
1768 	size_t i;
1769 
1770 	for (i = 0, p = pendings; i < len; i++, p++) {
1771 		coap_pending_clear(p);
1772 	}
1773 }
1774 
coap_pendings_count(struct coap_pending * pendings,size_t len)1775 size_t coap_pendings_count(struct coap_pending *pendings, size_t len)
1776 {
1777 	struct coap_pending *p = pendings;
1778 	size_t c = 0;
1779 
1780 	for (size_t i = 0; i < len && p; i++, p++) {
1781 		if (p->timeout) {
1782 			c++;
1783 		}
1784 	}
1785 	return c;
1786 }
1787 
1788 /* Reordering according to RFC7641 section 3.4 but without timestamp comparison */
1789 IF_DISABLED(CONFIG_ZTEST, (static inline))
coap_age_is_newer(int v1,int v2)1790 bool coap_age_is_newer(int v1, int v2)
1791 {
1792 	return (v1 < v2 && v2 - v1 < (1 << 23))
1793 	    || (v1 > v2 && v1 - v2 > (1 << 23));
1794 }
1795 
coap_observer_increment_age(struct coap_resource * resource)1796 static inline void coap_observer_increment_age(struct coap_resource *resource)
1797 {
1798 	resource->age++;
1799 	if (resource->age > COAP_OBSERVE_MAX_AGE) {
1800 		resource->age = COAP_OBSERVE_FIRST_OFFSET;
1801 	}
1802 }
1803 
coap_response_received(const struct coap_packet * response,const struct sockaddr * from,struct coap_reply * replies,size_t len)1804 struct coap_reply *coap_response_received(
1805 	const struct coap_packet *response,
1806 	const struct sockaddr *from,
1807 	struct coap_reply *replies, size_t len)
1808 {
1809 	struct coap_reply *r;
1810 	uint8_t token[COAP_TOKEN_MAX_LEN];
1811 	uint16_t id;
1812 	uint8_t tkl;
1813 	size_t i;
1814 
1815 	if (!is_empty_message(response) && coap_packet_is_request(response)) {
1816 		/* Request can't be response */
1817 		return NULL;
1818 	}
1819 
1820 	id = coap_header_get_id(response);
1821 	tkl = coap_header_get_token(response, token);
1822 
1823 	for (i = 0, r = replies; i < len; i++, r++) {
1824 		int age;
1825 
1826 		if ((r->id == 0U) && (r->tkl == 0U)) {
1827 			continue;
1828 		}
1829 
1830 		/* Piggybacked must match id when token is empty */
1831 		if ((r->id != id) && (tkl == 0U)) {
1832 			continue;
1833 		}
1834 
1835 		if (tkl > 0 && memcmp(r->token, token, tkl)) {
1836 			continue;
1837 		}
1838 
1839 		age = coap_get_option_int(response, COAP_OPTION_OBSERVE);
1840 		/* handle observed requests only if received in order */
1841 		if (age == -ENOENT || coap_age_is_newer(r->age, age)) {
1842 			r->age = age;
1843 			if (coap_header_get_code(response) != COAP_RESPONSE_CODE_CONTINUE) {
1844 				r->reply(response, r, from);
1845 			}
1846 		}
1847 
1848 		return r;
1849 	}
1850 
1851 	return NULL;
1852 }
1853 
coap_reply_init(struct coap_reply * reply,const struct coap_packet * request)1854 void coap_reply_init(struct coap_reply *reply,
1855 		     const struct coap_packet *request)
1856 {
1857 	uint8_t token[COAP_TOKEN_MAX_LEN];
1858 	uint8_t tkl;
1859 
1860 	reply->id = coap_header_get_id(request);
1861 	tkl = coap_header_get_token(request, token);
1862 
1863 	if (tkl > 0) {
1864 		memcpy(reply->token, token, tkl);
1865 	}
1866 
1867 	reply->tkl = tkl;
1868 
1869 	/* Any initial observe response should be accepted */
1870 	reply->age = -1;
1871 }
1872 
coap_reply_clear(struct coap_reply * reply)1873 void coap_reply_clear(struct coap_reply *reply)
1874 {
1875 	(void)memset(reply, 0, sizeof(*reply));
1876 }
1877 
coap_replies_clear(struct coap_reply * replies,size_t len)1878 void coap_replies_clear(struct coap_reply *replies, size_t len)
1879 {
1880 	struct coap_reply *r;
1881 	size_t i;
1882 
1883 	for (i = 0, r = replies; i < len; i++, r++) {
1884 		coap_reply_clear(r);
1885 	}
1886 }
1887 
coap_resource_notify(struct coap_resource * resource)1888 int coap_resource_notify(struct coap_resource *resource)
1889 {
1890 	struct coap_observer *o;
1891 
1892 	if (!resource->notify) {
1893 		return -ENOENT;
1894 	}
1895 
1896 	if (sys_slist_is_empty(&resource->observers)) {
1897 		return 0;
1898 	}
1899 
1900 	coap_observer_increment_age(resource);
1901 
1902 	SYS_SLIST_FOR_EACH_CONTAINER(&resource->observers, o, list) {
1903 		resource->notify(resource, o);
1904 	}
1905 
1906 	return 0;
1907 }
1908 
coap_request_is_observe(const struct coap_packet * request)1909 bool coap_request_is_observe(const struct coap_packet *request)
1910 {
1911 	return coap_get_option_int(request, COAP_OPTION_OBSERVE) == 0;
1912 }
1913 
coap_observer_init(struct coap_observer * observer,const struct coap_packet * request,const struct sockaddr * addr)1914 void coap_observer_init(struct coap_observer *observer,
1915 			const struct coap_packet *request,
1916 			const struct sockaddr *addr)
1917 {
1918 	observer->tkl = coap_header_get_token(request, observer->token);
1919 
1920 	net_ipaddr_copy(&observer->addr, addr);
1921 }
1922 
coap_observer_raise_event(struct coap_resource * resource,struct coap_observer * observer,uint32_t mgmt_event)1923 static inline void coap_observer_raise_event(struct coap_resource *resource,
1924 					     struct coap_observer *observer,
1925 					     uint32_t mgmt_event)
1926 {
1927 #ifdef CONFIG_NET_MGMT_EVENT_INFO
1928 	const struct net_event_coap_observer net_event = {
1929 		.resource = resource,
1930 		.observer = observer,
1931 	};
1932 
1933 	net_mgmt_event_notify_with_info(mgmt_event, NULL, (void *)&net_event, sizeof(net_event));
1934 #else
1935 	ARG_UNUSED(resource);
1936 	ARG_UNUSED(observer);
1937 
1938 	net_mgmt_event_notify(mgmt_event, NULL);
1939 #endif
1940 }
1941 
coap_register_observer(struct coap_resource * resource,struct coap_observer * observer)1942 bool coap_register_observer(struct coap_resource *resource,
1943 			    struct coap_observer *observer)
1944 {
1945 	bool first;
1946 
1947 	sys_slist_append(&resource->observers, &observer->list);
1948 
1949 	first = resource->age == 0;
1950 	if (first) {
1951 		resource->age = COAP_OBSERVE_FIRST_OFFSET;
1952 	}
1953 
1954 	coap_observer_raise_event(resource, observer, NET_EVENT_COAP_OBSERVER_ADDED);
1955 
1956 	return first;
1957 }
1958 
coap_remove_observer(struct coap_resource * resource,struct coap_observer * observer)1959 bool coap_remove_observer(struct coap_resource *resource,
1960 			  struct coap_observer *observer)
1961 {
1962 	if (!sys_slist_find_and_remove(&resource->observers, &observer->list)) {
1963 		return false;
1964 	}
1965 
1966 	coap_observer_raise_event(resource, observer, NET_EVENT_COAP_OBSERVER_REMOVED);
1967 
1968 	return true;
1969 }
1970 
sockaddr_equal(const struct sockaddr * a,const struct sockaddr * b)1971 static bool sockaddr_equal(const struct sockaddr *a,
1972 			   const struct sockaddr *b)
1973 {
1974 	/* FIXME: Should we consider ipv6-mapped ipv4 addresses as equal to
1975 	 * ipv4 addresses?
1976 	 */
1977 	if (a->sa_family != b->sa_family) {
1978 		return false;
1979 	}
1980 
1981 	if (a->sa_family == AF_INET) {
1982 		const struct sockaddr_in *a4 = net_sin(a);
1983 		const struct sockaddr_in *b4 = net_sin(b);
1984 
1985 		if (a4->sin_port != b4->sin_port) {
1986 			return false;
1987 		}
1988 
1989 		return net_ipv4_addr_cmp(&a4->sin_addr, &b4->sin_addr);
1990 	}
1991 
1992 	if (b->sa_family == AF_INET6) {
1993 		const struct sockaddr_in6 *a6 = net_sin6(a);
1994 		const struct sockaddr_in6 *b6 = net_sin6(b);
1995 
1996 		if (a6->sin6_port != b6->sin6_port) {
1997 			return false;
1998 		}
1999 
2000 		return net_ipv6_addr_cmp(&a6->sin6_addr, &b6->sin6_addr);
2001 	}
2002 
2003 	/* Invalid address family */
2004 	return false;
2005 }
2006 
coap_find_observer(struct coap_observer * observers,size_t len,const struct sockaddr * addr,const uint8_t * token,uint8_t token_len)2007 struct coap_observer *coap_find_observer(
2008 	struct coap_observer *observers, size_t len,
2009 	const struct sockaddr *addr,
2010 	const uint8_t *token, uint8_t token_len)
2011 {
2012 	if (token_len == 0U || token_len > COAP_TOKEN_MAX_LEN) {
2013 		return NULL;
2014 	}
2015 
2016 	for (size_t i = 0; i < len; i++) {
2017 		struct coap_observer *o = &observers[i];
2018 
2019 		if (o->tkl == token_len &&
2020 		    memcmp(o->token, token, token_len) == 0 &&
2021 		    sockaddr_equal(&o->addr, addr)) {
2022 			return o;
2023 		}
2024 	}
2025 
2026 	return NULL;
2027 }
2028 
coap_find_observer_by_addr(struct coap_observer * observers,size_t len,const struct sockaddr * addr)2029 struct coap_observer *coap_find_observer_by_addr(
2030 	struct coap_observer *observers, size_t len,
2031 	const struct sockaddr *addr)
2032 {
2033 	size_t i;
2034 
2035 	for (i = 0; i < len; i++) {
2036 		struct coap_observer *o = &observers[i];
2037 
2038 		if (sockaddr_equal(&o->addr, addr)) {
2039 			return o;
2040 		}
2041 	}
2042 
2043 	return NULL;
2044 }
2045 
coap_find_observer_by_token(struct coap_observer * observers,size_t len,const uint8_t * token,uint8_t token_len)2046 struct coap_observer *coap_find_observer_by_token(
2047 	struct coap_observer *observers, size_t len,
2048 	const uint8_t *token, uint8_t token_len)
2049 {
2050 	if (token_len == 0U || token_len > COAP_TOKEN_MAX_LEN) {
2051 		return NULL;
2052 	}
2053 
2054 	for (size_t i = 0; i < len; i++) {
2055 		struct coap_observer *o = &observers[i];
2056 
2057 		if (o->tkl == token_len && memcmp(o->token, token, token_len) == 0) {
2058 			return o;
2059 		}
2060 	}
2061 
2062 	return NULL;
2063 }
2064 
2065 /**
2066  * @brief Internal initialization function for CoAP library.
2067  *
2068  * Called by the network layer init procedure. Seeds the CoAP @message_id with a
2069  * random number in accordance with recommendations in CoAP specification.
2070  *
2071  * @note This function is not exposed in a public header, as it's for internal
2072  * use and should therefore not be exposed to applications.
2073  */
net_coap_init(void)2074 void net_coap_init(void)
2075 {
2076 	/* Initialize message_id to a random number */
2077 	message_id = (uint16_t)sys_rand32_get();
2078 }
2079 
coap_next_id(void)2080 uint16_t coap_next_id(void)
2081 {
2082 	return message_id++;
2083 }
2084 
coap_get_transmission_parameters(void)2085 struct coap_transmission_parameters coap_get_transmission_parameters(void)
2086 {
2087 	return coap_transmission_params;
2088 }
2089 
coap_set_transmission_parameters(const struct coap_transmission_parameters * params)2090 void coap_set_transmission_parameters(const struct coap_transmission_parameters *params)
2091 {
2092 	coap_transmission_params = *params;
2093 }
2094