blob: 01d0eb368bff543145703a2f385b5587f38a200b [file] [log] [blame]
Neels Hofmeyr7dde1f42020-05-11 19:43:20 +02001/*! \file gsm23236.c
2 * Utility function implementations related to 3GPP TS 23.236 */
3/*
4 * (C) 2020 sysmocom - s.f.m.c. GmbH <info@sysmocom.de>
5 * Author: Neels Hofmeyr <nhofmeyr@sysmocom.de>
6 * All Rights Reserved
7 *
8 * SPDX-License-Identifier: GPL-2.0+
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 *
24 */
25
26#include <errno.h>
27#include <stdlib.h>
28
29#include <osmocom/core/utils.h>
30#include <osmocom/gsm/gsm23236.h>
31
32/*! Validate that the given NRI is valid for a given nri_bitlen range.
33 * \param[in] nri_v NRI value to validate.
34 * \param[in] nri_bitlen Valid NRI range in nr of bits used; if nri_bitlen > OSMO_NRI_BITLEN_MAX, nri_v is only
35 * checked to not be marked invalid.
36 * \returns 0 if valid, <0 if the NRI is <0, >0 if the NRI surpasses the range.
37 */
38int osmo_nri_v_validate(int16_t nri_v, uint8_t nri_bitlen)
39{
40 if (nri_v < 0)
41 return -1;
42 if (nri_bitlen < OSMO_NRI_BITLEN_MIN)
43 return 1;
44 if (nri_bitlen < OSMO_NRI_BITLEN_MAX && (nri_v >> nri_bitlen))
45 return 1;
46 return 0;
47}
48
49/*! Match NRI value against a list NRI ranges. */
50static bool nri_v_matches_range(const struct osmo_nri_range *range, int16_t nri_v)
51{
52 return range && nri_v >= range->first && nri_v <= range->last;
53}
54
55/*! Return true if the ranges overlap, i.e. one or more NRI values appear in both ranges. */
56static bool nri_range_overlaps_range(const struct osmo_nri_range *a, const struct osmo_nri_range *b)
57{
58 return nri_v_matches_range(b, a->first) || nri_v_matches_range(b, a->last)
59 || nri_v_matches_range(a, b->first) || nri_v_matches_range(a, b->last);
60}
61
62/*! Return true if the ranges overlap or are directly adjacent to each other. */
63static bool nri_range_touches(const struct osmo_nri_range *a, const struct osmo_nri_range *b)
64{
65 /* The first > last check may seem redundant, but ensures integer overflow safety. */
66 return nri_range_overlaps_range(a, b)
67 || (a->first > b->last && a->first == b->last + 1)
68 || (b->first > a->last && b->first == a->last + 1);
69}
70
71/*! Grow target range to also span range 'add'. Only useful for touching ranges, since all values between the two ranges
72 * are also included. */
73static void nri_range_extend(struct osmo_nri_range *target, const struct osmo_nri_range *add)
74{
75 target->first = OSMO_MIN(target->first, add->first);
76 target->last = OSMO_MAX(target->last, add->last);
77}
78
79/*! Return true when the given NRI value appears in the list of NRI ranges.
80 * \param[in] nri_v NRI value to look for.
81 * \param[in] nri_ranges List NRI ranges.
82 * \returns true iff nri_v appears anywhere in nri_ranges.
83 */
84bool osmo_nri_v_matches_ranges(int16_t nri_v, const struct osmo_nri_ranges *nri_ranges)
85{
86 struct osmo_nri_range *range;
87 if (!nri_ranges)
88 return false;
89 llist_for_each_entry(range, &nri_ranges->entries, entry) {
90 if (nri_v_matches_range(range, nri_v))
91 return true;
92 }
93 return false;
94}
95
96/*! Modulo and shift the given NRI value so that it becomes a value present in a list of NRI ranges.
97 * Only range values within nri_bitlen are used.
98 * \param[inout] nri_v The NRI value to limit, e.g. random bits or an increment counter value.
99 * \param[in] nri_ranges List of NRI ranges indicating valid NRI values, where no entries may overlap in range values,
100 * and all entries must be valid (first <= last).
101 * \returns 0 on success, negative on error.
102 */
103int osmo_nri_v_limit_by_ranges(int16_t *nri_v, const struct osmo_nri_ranges *nri_ranges, uint32_t nri_bitlen)
104{
105 struct osmo_nri_range *range;
106 uint32_t total_values = 0;
107 int16_t v = *nri_v;
108 int16_t range_max = (((int16_t)1) << nri_bitlen) - 1;
109
110 if (v < 0 || !nri_ranges)
111 return -1;
112
113 /* Sum up total amount of range values */
114 llist_for_each_entry(range, &nri_ranges->entries, entry) {
115 if (osmo_nri_range_validate(range, 255))
116 return -1;
117 if (range->first > range_max)
118 continue;
119 total_values += OSMO_MIN(range_max, range->last) - range->first + 1;
120 }
121
122 /* Modulo the given NRI value by that, and pick that nth value from the given ranges.
123 * (nri_ranges is pretty much guaranteed to be sorted and range_max checks thus would no longer be needed, but
124 * just check them anyway.) */
125 v %= total_values;
126 llist_for_each_entry(range, &nri_ranges->entries, entry) {
127 uint32_t len;
128 if (range->first > range_max)
129 continue;
130 len = OSMO_MIN(range_max, range->last) - range->first + 1;
131 if (v < len) {
132 *nri_v = range->first + v;
133 return 0;
134 }
135 v -= len;
136 }
137
138 /* Nothing found -- there are no entires or my math is off. */
139 return -1;
140}
141
142/*! Retrieve the Network Resource Indicator bits from a TMSI or p-TMSI.
143 * Useful for MSC pooling as described by 3GPP TS 23.236.
144 * \param[out] nri_v Write the extracted NRI value to this location (if non-NULL). If 0 is returned, it is guaranteed
145 * that nri_v >= 0. On non-zero return code, nri_v == -1.
146 * \param[in] tmsi TMSI value containing NRI bits.
147 * \param[in] nri_bitlen Length of the NRI value in number of bits,
148 * OSMO_NRI_BITLEN_MIN <= nri_bitlen <= * OSMO_NRI_BITLEN_MAX.
149 * \return 0 on success, negative on error (i.e. if nri_bitlen is not in the valid range).
150 */
151int osmo_tmsi_nri_v_get(int16_t *nri_v, uint32_t tmsi, uint8_t nri_bitlen)
152{
153 uint8_t lowest_bit;
154 if (nri_v)
155 *nri_v = -1;
156 if (nri_bitlen < OSMO_NRI_BITLEN_MIN || nri_bitlen > OSMO_NRI_BITLEN_MAX)
157 return -1;
158 /* If not interested in the NRI value, exit here. */
159 if (!nri_v)
160 return 0;
161 /* According to 3GPP TS 23.236, the most significant bit of the NRI is always bit 23.
162 * (So this is not a temporary placeholder 23 we sometimes like to use, it is an actually specified 23!) */
163 lowest_bit = 23 - (nri_bitlen - 1);
164 /* ????xxxxxx??????? -> 0000000????xxxxxx tmsi >> lowest_bit
165 * -> xxxxxx & (bitmask that is nri_bitlen bits wide)
166 */
167 *nri_v = (tmsi >> lowest_bit) & ((((uint32_t)1) << nri_bitlen) - 1);
168 return 0;
169}
170
171/*! Write Network Resource Indicator bits into a TMSI or p-TMSI.
172 * Overwrite the NRI bits with a given NRI value in a TMSI or p-TMSI.
173 * Useful for MSC pooling as described by 3GPP TS 23.236.
174 * \param[inout] tmsi A base TMSI or p-TMSI to replace the NRI value in, result is written back to this location.
175 * \param[in] nri_v The NRI value to place in the tmsi.
176 * \param[in] nri_bitlen Length of the NRI value in number of bits,
177 * OSMO_NRI_BITLEN_MIN <= nri_bitlen <= * OSMO_NRI_BITLEN_MAX.
178 * \return 0 on success, negative on error (i.e. if nri_bitlen is not in the valid range or if tmsi is NULL).
179 */
180int osmo_tmsi_nri_v_set(uint32_t *tmsi, int16_t nri_v, uint8_t nri_bitlen)
181{
182 uint8_t lowest_bit;
183 uint32_t v_mask;
184 if (nri_bitlen < OSMO_NRI_BITLEN_MIN || nri_bitlen > OSMO_NRI_BITLEN_MAX)
185 return -1;
186 if (nri_v < 0)
187 return -1;
188 if (!tmsi)
189 return -1;
190 lowest_bit = 23 - (nri_bitlen - 1);
191 v_mask = ((((uint32_t)1) << nri_bitlen) - 1) << lowest_bit;
192 *tmsi = ((*tmsi) & ~v_mask) | ((((uint32_t)nri_v) << lowest_bit) & v_mask);
193 return 0;
194}
195
196/*! Apply osmo_nri_v_limit_by_ranges() in-place on the NRI value included in a TMSI.
197 * Extract the NRI value from the TMSI, limit that to be part of the ranges given in 'nri_ranges', and place the
198 * resulting NRI value back in the TMSI.
199 * \param[inout] tmsi TMSI value of which to modify the NRI bits, e.g. fresh randomized bits.
200 * \param[in] nri_ranges List of NRI ranges indicating valid NRI values, where no entries may overlap in range values,
201 * and all entries must be valid (first <= last).
202 * \param[in] nri_bitlen Valid NRI range in nr of bits used.
203 * \returns 0 on success, negative on error.
204 */
205int osmo_tmsi_nri_v_limit_by_ranges(uint32_t *tmsi, const struct osmo_nri_ranges *nri_ranges, uint8_t nri_bitlen)
206{
207 int rc;
208 int16_t nri_v;
209 rc = osmo_tmsi_nri_v_get(&nri_v, *tmsi, nri_bitlen);
210 if (rc)
211 return rc;
212 rc = osmo_nri_v_limit_by_ranges(&nri_v, nri_ranges, nri_bitlen);
213 if (rc)
214 return rc;
215 return osmo_tmsi_nri_v_set(tmsi, nri_v, nri_bitlen);
216}
217
218/*! Validate that the given NRI range is valid for a given nri_bitlen range.
219 * \param[in] nri_range NRI value range to validate.
220 * \param[in] nri_bitlen Valid NRI range in nr of bits used. If nri_bitlen > OSMO_NRI_BITLEN_MAX, the NRI range is only
221 * validated to be first <= last and non-negative, not checked to fit a bit length range,
222 * \returns 0 if valid, -1 or 1 if range->first is invalid, -2 or 2 if range->last is invalid, -3 if first > last.
223 */
224int osmo_nri_range_validate(const struct osmo_nri_range *range, uint8_t nri_bitlen)
225{
226 int rc;
227 rc = osmo_nri_v_validate(range->first, nri_bitlen);
228 if (rc)
229 return rc;
230 rc = osmo_nri_v_validate(range->last, nri_bitlen);
231 if (rc)
232 return 2 * rc;
233 if (range->first > range->last)
234 return -3;
235 return 0;
236}
237
238/*! Return true when the given NRI range has at least one NRI value that appears in a list of other NRI ranges.
239 * \param[in] range NRI range to look for.
240 * \param[in] nri_ranges List NRI ranges.
241 * \returns true iff any NRI value from 'range' appears anywhere in nri_ranges.
242 */
243bool osmo_nri_range_overlaps_ranges(const struct osmo_nri_range *range, const struct osmo_nri_ranges *nri_ranges)
244{
245 struct osmo_nri_range *i;
246 if (!nri_ranges)
247 return false;
248 llist_for_each_entry(i, &nri_ranges->entries, entry) {
249 if (nri_range_overlaps_range(i, range))
250 return true;
251 }
252 return false;
253}
254
255/*! Allocate an empty struct osmo_nri_ranges (list of struct osmo_nri_range).
256 * \param ctx Talloc context to allocate from.
257 * \return allocated empty list.
258 */
259struct osmo_nri_ranges *osmo_nri_ranges_alloc(void *ctx)
260{
261 struct osmo_nri_ranges *nri_ranges;
262 nri_ranges = talloc_zero(ctx, struct osmo_nri_ranges);
263 OSMO_ASSERT(nri_ranges);
264 INIT_LLIST_HEAD(&nri_ranges->entries);
265 return nri_ranges;
266}
267
268/*! Free a struct osmo_nri_ranges.
269 * \param nri_ranges The list to discard.
270 */
271void osmo_nri_ranges_free(struct osmo_nri_ranges *nri_ranges)
272{
273 if (nri_ranges)
274 talloc_free(nri_ranges);
275}
276
277/*! Insert a new struct osmo_nri_range in an osmo_nri_ranges list, so that it remains sorted by 'first' values. */
278static void nri_ranges_add_entry_sorted(struct osmo_nri_ranges *nri_ranges, struct osmo_nri_range *add)
279{
280 struct osmo_nri_range *r;
281 struct llist_head *at_pos;
282 OSMO_ASSERT(nri_ranges);
283 at_pos = nri_ranges->entries.prev;
284 llist_for_each_entry(r, &nri_ranges->entries, entry) {
285 if (r->first <= add->first)
286 continue;
287 at_pos = r->entry.prev;
288 break;
289 }
290 llist_add(&add->entry, at_pos);
291}
292
293/*! Add a range of NRI values to a list of nri_range structs.
294 * Intelligently add and/or combine the entries in a list of NRI ranges to also include the NRI range given in 'add'.
295 * The list remains sorted by 'first' values.
296 * \param[inout] nri_ranges List of talloc allocated struct osmo_nri_range entries to add the new range to.
297 * \param[in] add NRI range to add to 'nri_ranges'.
298 * \returns 0 on success, negative on error (if the range in 'add' is invalid).
299 */
300int osmo_nri_ranges_add(struct osmo_nri_ranges *nri_ranges, const struct osmo_nri_range *add)
301{
302 struct osmo_nri_range *range;
303 struct osmo_nri_range *range_next;
304 struct osmo_nri_range *target = NULL;
305
306 if (osmo_nri_range_validate(add, 255))
307 return -1;
308 if (!nri_ranges)
309 return -1;
310
311 /* Is there an entry overlapping this range? */
312 llist_for_each_entry(range, &nri_ranges->entries, entry) {
313 if (!nri_range_touches(range, add))
314 continue;
315 target = range;
316 }
317
318 if (!target) {
319 /* No overlaps with existing ranges, create a new one. */
320 target = talloc_zero(nri_ranges, struct osmo_nri_range);
321 OSMO_ASSERT(target);
322 *target = *add;
323 nri_ranges_add_entry_sorted(nri_ranges, target);
324 return 0;
325 }
326
327 /* Overlap found, join into existing entry */
328 nri_range_extend(target, add);
329
330 /* Remove redundant entries */
331 llist_for_each_entry_safe(range, range_next, &nri_ranges->entries, entry) {
332 if (range == target)
333 continue;
334 if (!nri_range_touches(target, range))
335 continue;
336 nri_range_extend(target, range);
337 llist_del(&range->entry);
338 talloc_free(range);
339 }
340 return 0;
341}
342
343/*! Remove a range of NRI values from a list of nri_range structs.
344 * Intelligently drop and/or cut or split the entries in a list of NRI ranges to no longer include the NRI range given
345 * in 'del'. Note that after this, the list may have more entries than before, if a range was split into two smaller
346 * ranges.
347 * \param[inout] nri_ranges List of talloc allocated struct osmo_nri_range entries to remove values from.
348 * \param[in] del NRI range to remove from 'nri_ranges'.
349 * \returns 0 on success, negative on error (if the range in 'del' is invalid).
350 */
351int osmo_nri_ranges_del(struct osmo_nri_ranges *nri_ranges, const struct osmo_nri_range *del)
352{
353 struct osmo_nri_range *range;
354 struct osmo_nri_range *range_next;
355
356 if (osmo_nri_range_validate(del, 255))
357 return -1;
358 if (!nri_ranges)
359 return -1;
360
361 llist_for_each_entry_safe(range, range_next, &nri_ranges->entries, entry) {
362 bool head;
363 bool tail;
364 if (!nri_range_overlaps_range(range, del))
365 continue;
366
367 head = nri_v_matches_range(range, del->first) && (del->first > range->first);
368 tail = nri_v_matches_range(range, del->last) && (del->last < range->last);
369
370 if (head && tail) {
371 /* Range cut in two */
372 struct osmo_nri_range *new_tail;
373
374 /* Add a new entry for the tail section */
375 new_tail = talloc_zero(nri_ranges, struct osmo_nri_range);
376 OSMO_ASSERT(new_tail);
377 *new_tail = (struct osmo_nri_range){
378 .first = del->last + 1,
379 .last = range->last,
380 };
381 llist_add(&new_tail->entry, &range->entry);
382
383 /* Existing entry becomes the head section */
384 range->last = del->first - 1;
385 } else if (head) {
386 /* Range reduced, a head remains */
387 range->last = del->first - 1;
388 } else if (tail) {
389 /* Range reduced, a tail remains */
390 range->first = del->last + 1;
391 } else {
392 /* nothing remains */
393 llist_del(&range->entry);
394 talloc_free(range);
395 }
396 }
397 return 0;
398}
399
400/*! Compose a human readable representation of a list of NRI ranges in a buffer, like "23..42,123..142".
401 * \param[out] buf Target buffer.
402 * \param[in] buflen sizeof(buf).
403 * \param[in] nri_ranges List NRI ranges.
404 * \returns strlen() of string that would be written if the buffer is large enough, like snprintf().
405 */
406int osmo_nri_ranges_to_str_buf(char *buf, size_t buflen, const struct osmo_nri_ranges *nri_ranges)
407{
408 struct osmo_nri_range *range;
409 struct osmo_strbuf sb = { .buf = buf, .len = buflen };
410 bool first = true;
411 if (!nri_ranges || llist_empty(&nri_ranges->entries)) {
412 OSMO_STRBUF_PRINTF(sb, "empty");
413 return sb.chars_needed;
414 }
415 llist_for_each_entry(range, &nri_ranges->entries, entry) {
416 OSMO_STRBUF_PRINTF(sb, "%s%d..%d", first ? "" : ",", range->first, range->last);
417 }
418 return sb.chars_needed;
419}
420
421/*! Compose a human readable representation of a list of NRI ranges in a talloc buffer, like "23..42,123..142".
422 * \param[in] ctx Talloc context.
423 * \param[in] nri_ranges List of NRI ranges.
424 * \returns a talloc allocated string.
425 */
426char *osmo_nri_ranges_to_str_c(void *ctx, const struct osmo_nri_ranges *nri_ranges)
427{
428 OSMO_NAME_C_IMPL(ctx, 16, "ERROR", osmo_nri_ranges_to_str_buf, nri_ranges);
429}
430
431/*! Parse a string to an NRI value, allowing both decimal and hexadecimal formats; useful for VTY config
432 * implementations.
433 * \param[out] dst Write the resulting NRI value to this location.
434 * \param[in] str Decimal "511" or hex "0x1ff" string to parse.
435 * \returns 0 on success, negative on error.
436 */
437static int osmo_nri_parse(int16_t *dst, const char *str)
438{
439 char *endp;
440 int64_t val;
441 int base = 10;
442
443 if (osmo_str_startswith(str, "0x")) {
444 str += 2;
445 base = 16;
446 }
447
448 if (!str || !str[0])
449 return -1;
450
451 errno = 0;
452 val = strtoull(str, &endp, base);
453 if (errno || *endp != '\0')
454 return -1;
455
456 if (val < 0 || val > INT16_MAX)
457 return -1;
458
459 *dst = val;
460 return 0;
461}
462
463/*! Parse string arguments to a struct osmo_nri_range; useful for VTY config implementations.
464 * Validate and parse 'first' and optional 'last' string arguments into struct osmo_nri_range values.
465 * The strings may be in decimal format ("511") or hexadecimal with leading "0x" ("0x1ff").
466 * If only one of 'first'/'last' is provided, the resulting range will have only that value (first == last).
467 * \param[out] nri_range Target for parsed values.
468 * \param[in] first_str Decimal or hex string, representing the first value in the range, or NULL if omitted.
469 * \param[in] last_str Decimal or hex string, representing the last value in the range, or NULL if omitted.
470 * \returns 0 on success, negative on error.
471 */
472static int osmo_nri_parse_range(struct osmo_nri_range *nri_range, const char *first_str, const char *last_str)
473{
474 if (!nri_range)
475 return -1;
476 if (!first_str) {
477 first_str = last_str;
478 last_str = NULL;
479 if (!first_str)
480 return -1;
481 }
482 if (osmo_nri_parse(&nri_range->first, first_str))
483 return -1;
484 nri_range->last = nri_range->first;
485 if (last_str) {
486 if (osmo_nri_parse(&nri_range->last, last_str))
487 return -1;
488 }
489 return 0;
490}
491
492/*! VTY implementation for adding an NRI range to a list of ranges.
493 * Parse one or, if present, two argv arguments, which must be numbers representing the first and last value to add to
494 * the list of NRI ranges, in decimal format ("511") or hexadecimal with leading "0x" ("0x1ff"). If the range values
495 * surpass the nri_bitlen, return a warning in 'message', but still add the values to the list.
496 * \param[out] message Returned string constant to alert the user with, or NULL if all is well.
497 * \param[out] added_range If not NULL, write the range parsing result to this location.
498 * \param[in] nri_ranges List NRI ranges to add to.
499 * \param[in] argc Argument count.
500 * \param[in] argv Argument list.
501 * \param[in] nri_bitlen Valid NRI range in nr of bits used.
502 * \returns 0 on success, -1 on error, 1 for a warning (if adding was successful but the added range surpasses
503 * nri_bitlen).
504 */
505int osmo_nri_ranges_vty_add(const char **message, struct osmo_nri_range *added_range,
506 struct osmo_nri_ranges *nri_ranges, int argc, const char **argv, uint8_t nri_bitlen)
507{
508 struct osmo_nri_range add_range;
509 if (osmo_nri_parse_range(&add_range, argv[0], argc > 1 ? argv[1] : NULL)) {
510 *message = "Error: cannot parse NRI range";
511 return -1;
512 }
513
514 if (added_range)
515 *added_range = add_range;
516
517 if (osmo_nri_ranges_add(nri_ranges, &add_range)) {
518 *message = "Error: failed to add NRI range";
519 return -1;
520 }
521
522 if (nri_bitlen <= OSMO_NRI_BITLEN_MAX && osmo_nri_range_validate(&add_range, nri_bitlen)) {
523 *message = "Warning: NRI range surpasses current NRI bitlen";
524 return 1;
525 }
526
527 *message = NULL;
528 return 0;
529}
530
531/*! VTY implementation for removing an NRI range from a list of ranges.
532 * Parse one or, if present, two argv arguments, which must be numbers representing the first and last value to remove
533 * from the list of NRI ranges, in decimal format ("511") or hexadecimal with leading "0x" ("0x1ff").
534 * \param[out] message Returned string constant to alert the user with, or NULL if all is well.
535 * \param[out] removed_range If not NULL, write the range parsing result to this location.
536 * \param[in] nri_ranges List of NRI ranges to remove from.
537 * \param[in] argc Argument count.
538 * \param[in] argv Argument list.
539 * \returns 0 on success, -1 on error, 1 for a warning.
540 */
541int osmo_nri_ranges_vty_del(const char **message, struct osmo_nri_range *removed_range,
542 struct osmo_nri_ranges *nri_ranges, int argc, const char **argv)
543{
544 struct osmo_nri_range del_range;
545 if (osmo_nri_parse_range(&del_range, argv[0], argc > 1 ? argv[1] : NULL)) {
546 *message = "Error: cannot parse NRI range";
547 return -1;
548 }
549
550 if (removed_range)
551 *removed_range = del_range;
552
553 if (osmo_nri_ranges_del(nri_ranges, &del_range)) {
554 *message = "Error: failed to remove NRI range";
555 return -1;
556 }
557
558 *message = NULL;
559 return 0;
560}