Whamcloud - gitweb
LU-56 libcfs: move range expression parser to libcfs
[fs/lustre-release.git] / libcfs / libcfs / libcfs_string.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
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 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2012, Whamcloud, Inc.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * String manipulation functions.
37  *
38  * libcfs/libcfs/libcfs_string.c
39  *
40  * Author: Nathan Rutman <nathan.rutman@sun.com>
41  */
42
43 #ifndef EXPORT_SYMTAB
44 # define EXPORT_SYMTAB
45 #endif
46
47 #include <libcfs/libcfs.h>
48
49 /* non-0 = don't match */
50 static int cfs_strncasecmp(const char *s1, const char *s2, size_t n)
51 {
52         if (s1 == NULL || s2 == NULL)
53                 return 1;
54
55         if (n == 0)
56                 return 0;
57
58         while (n-- != 0 && tolower(*s1) == tolower(*s2)) {
59                 if (n == 0 || *s1 == '\0' || *s2 == '\0')
60                         break;
61                 s1++;
62                 s2++;
63         }
64
65         return tolower(*(unsigned char *)s1) - tolower(*(unsigned char *)s2);
66 }
67
68 /* Convert a text string to a bitmask */
69 int cfs_str2mask(const char *str, const char *(*bit2str)(int bit),
70                  int *oldmask, int minmask, int allmask)
71 {
72         const char *debugstr;
73         char op = 0;
74         int newmask = minmask, i, len, found = 0;
75         ENTRY;
76
77         /* <str> must be a list of tokens separated by whitespace
78          * and optionally an operator ('+' or '-').  If an operator
79          * appears first in <str>, '*oldmask' is used as the starting point
80          * (relative), otherwise minmask is used (absolute).  An operator
81          * applies to all following tokens up to the next operator. */
82         while (*str != 0) {
83                 while (isspace(*str))
84                         str++;
85                 if (*str == 0)
86                         break;
87                 if (*str == '+' || *str == '-') {
88                         op = *str++;
89                         if (!found)
90                                 /* only if first token is relative */
91                                 newmask = *oldmask;
92                         while (isspace(*str))
93                                 str++;
94                         if (*str == 0)          /* trailing op */
95                                 return -EINVAL;
96                 }
97
98                 /* find token length */
99                 for (len = 0; str[len] != 0 && !isspace(str[len]) &&
100                       str[len] != '+' && str[len] != '-'; len++);
101
102                 /* match token */
103                 found = 0;
104                 for (i = 0; i < 32; i++) {
105                         debugstr = bit2str(i);
106                         if (debugstr != NULL &&
107                             strlen(debugstr) == len &&
108                             cfs_strncasecmp(str, debugstr, len) == 0) {
109                                 if (op == '-')
110                                         newmask &= ~(1 << i);
111                                 else
112                                         newmask |= (1 << i);
113                                 found = 1;
114                                 break;
115                         }
116                 }
117                 if (!found && len == 3 &&
118                     (cfs_strncasecmp(str, "ALL", len) == 0)) {
119                         if (op == '-')
120                                 newmask = minmask;
121                         else
122                                 newmask = allmask;
123                         found = 1;
124                 }
125                 if (!found) {
126                         CWARN("unknown mask '%.*s'.\n"
127                               "mask usage: [+|-]<all|type> ...\n", len, str);
128                         return -EINVAL;
129                 }
130                 str += len;
131         }
132
133         *oldmask = newmask;
134         return 0;
135 }
136 EXPORT_SYMBOL(cfs_str2mask);
137
138 /* Duplicate a string in a platform-independent way */
139 char *cfs_strdup(const char *str, u_int32_t flags)
140 {
141         size_t lenz; /* length of str + zero byte */
142         char *dup_str;
143
144         lenz = strlen(str) + 1;
145
146         dup_str = cfs_alloc(lenz, flags);
147         if (dup_str == NULL)
148                 return NULL;
149
150         memcpy(dup_str, str, lenz);
151
152         return dup_str;
153 }
154 EXPORT_SYMBOL(cfs_strdup);
155
156 /**
157  * cfs_{v}snprintf() return the actual size that is printed rather than
158  * the size that would be printed in standard functions.
159  */
160 /* safe vsnprintf */
161 int cfs_vsnprintf(char *buf, size_t size, const char *fmt, va_list args)
162 {
163         int i;
164
165         LASSERT(size > 0);
166         i = vsnprintf(buf, size, fmt, args);
167
168         return  (i >= size ? size - 1 : i);
169 }
170 EXPORT_SYMBOL(cfs_vsnprintf);
171
172 /* safe snprintf */
173 int cfs_snprintf(char *buf, size_t size, const char *fmt, ...)
174 {
175         va_list args;
176         int i;
177
178         va_start(args, fmt);
179         i = cfs_vsnprintf(buf, size, fmt, args);
180         va_end(args);
181
182         return  i;
183 }
184 EXPORT_SYMBOL(cfs_snprintf);
185
186 /* get the first string out of @str */
187 char *cfs_firststr(char *str, size_t size)
188 {
189         size_t i = 0;
190         char  *end;
191
192         /* trim leading spaces */
193         while (i < size && *str && isspace(*str)) {
194                 ++i;
195                 ++str;
196         }
197
198         /* string with all spaces */
199         if (*str == '\0')
200                 goto out;
201
202         end = str;
203         while (i < size && *end != '\0' && !isspace(*end)) {
204                 ++i;
205                 ++end;
206         }
207
208         *end= '\0';
209 out:
210         return str;
211 }
212 EXPORT_SYMBOL(cfs_firststr);
213
214 char *
215 cfs_trimwhite(char *str)
216 {
217         char *end;
218
219         while (cfs_iswhite(*str))
220                 str++;
221
222         end = str + strlen(str);
223         while (end > str) {
224                 if (!cfs_iswhite(end[-1]))
225                         break;
226                 end--;
227         }
228
229         *end = 0;
230         return str;
231 }
232 EXPORT_SYMBOL(cfs_trimwhite);
233
234 /**
235  * Extracts tokens from strings.
236  *
237  * Looks for \a delim in string \a next, sets \a res to point to
238  * substring before the delimiter, sets \a next right after the found
239  * delimiter.
240  *
241  * \retval 1 if \a res points to a string of non-whitespace characters
242  * \retval 0 otherwise
243  */
244 int
245 cfs_gettok(struct cfs_lstr *next, char delim, struct cfs_lstr *res)
246 {
247         char *end;
248
249         if (next->ls_str == NULL)
250                 return 0;
251
252         /* skip leading white spaces */
253         while (next->ls_len) {
254                 if (!cfs_iswhite(*next->ls_str))
255                         break;
256                 next->ls_str++;
257                 next->ls_len--;
258         }
259
260         if (next->ls_len == 0) /* whitespaces only */
261                 return 0;
262
263         if (*next->ls_str == delim) {
264                 /* first non-writespace is the delimiter */
265                 return 0;
266         }
267
268         res->ls_str = next->ls_str;
269         end = memchr(next->ls_str, delim, next->ls_len);
270         if (end == NULL) {
271                 /* there is no the delimeter in the string */
272                 end = next->ls_str + next->ls_len;
273                 next->ls_str = NULL;
274         } else {
275                 next->ls_str = end + 1;
276                 next->ls_len -= (end - res->ls_str + 1);
277         }
278
279         /* skip ending whitespaces */
280         while (--end != res->ls_str) {
281                 if (!cfs_iswhite(*end))
282                         break;
283         }
284
285         res->ls_len = end - res->ls_str + 1;
286         return 1;
287 }
288 EXPORT_SYMBOL(cfs_gettok);
289
290 /**
291  * Converts string to integer.
292  *
293  * Accepts decimal and hexadecimal number recordings.
294  *
295  * \retval 1 if first \a nob chars of \a str convert to decimal or
296  * hexadecimal integer in the range [\a min, \a max]
297  * \retval 0 otherwise
298  */
299 int
300 cfs_str2num_check(char *str, int nob, unsigned *num,
301                   unsigned min, unsigned max)
302 {
303         char    *endp;
304
305         str = cfs_trimwhite(str);
306         *num = strtoul(str, &endp, 0);
307         if (endp == str)
308                 return 0;
309
310         for (; endp < str + nob; endp++) {
311                 if (!cfs_iswhite(*endp))
312                         return 0;
313         }
314
315         return (*num >= min && *num <= max);
316 }
317 EXPORT_SYMBOL(cfs_str2num_check);
318
319 /**
320  * Parses \<range_expr\> token of the syntax. If \a bracketed is false,
321  * \a src should only have a single token which can be \<number\> or  \*
322  *
323  * \retval pointer to allocated range_expr and initialized
324  * range_expr::re_lo, range_expr::re_hi and range_expr:re_stride if \a
325  `* src parses to
326  * \<number\> |
327  * \<number\> '-' \<number\> |
328  * \<number\> '-' \<number\> '/' \<number\>
329  * \retval 0 will be returned if it can be parsed, otherwise -EINVAL or
330  * -ENOMEM will be returned.
331  */
332 int
333 cfs_range_expr_parse(struct cfs_lstr *src, unsigned min, unsigned max,
334                      int bracketed, struct cfs_range_expr **expr)
335 {
336         struct cfs_range_expr   *re;
337         struct cfs_lstr         tok;
338
339         LIBCFS_ALLOC(re, sizeof(*re));
340         if (re == NULL)
341                 return -ENOMEM;
342
343         if (src->ls_len == 1 && src->ls_str[0] == '*') {
344                 re->re_lo = min;
345                 re->re_hi = max;
346                 re->re_stride = 1;
347                 goto out;
348         }
349
350         if (cfs_str2num_check(src->ls_str, src->ls_len,
351                               &re->re_lo, min, max)) {
352                 /* <number> is parsed */
353                 re->re_hi = re->re_lo;
354                 re->re_stride = 1;
355                 goto out;
356         }
357
358         if (!bracketed || !cfs_gettok(src, '-', &tok))
359                 goto failed;
360
361         if (!cfs_str2num_check(tok.ls_str, tok.ls_len,
362                                &re->re_lo, min, max))
363                 goto failed;
364
365         /* <number> - */
366         if (cfs_str2num_check(src->ls_str, src->ls_len,
367                               &re->re_hi, min, max)) {
368                 /* <number> - <number> is parsed */
369                 re->re_stride = 1;
370                 goto out;
371         }
372
373         /* go to check <number> '-' <number> '/' <number> */
374         if (cfs_gettok(src, '/', &tok)) {
375                 if (!cfs_str2num_check(tok.ls_str, tok.ls_len,
376                                        &re->re_hi, min, max))
377                         goto failed;
378
379                 /* <number> - <number> / ... */
380                 if (cfs_str2num_check(src->ls_str, src->ls_len,
381                                       &re->re_stride, min, max)) {
382                         /* <number> - <number> / <number> is parsed */
383                         goto out;
384                 }
385         }
386
387  out:
388         *expr = re;
389         return 0;
390
391  failed:
392         LIBCFS_FREE(re, sizeof(*re));
393         return -EINVAL;
394 }
395 EXPORT_SYMBOL(cfs_range_expr_parse);
396
397 /**
398  * Matches value (\a value) against ranges expression list \a expr_list.
399  *
400  * \retval 1 if \a value matches
401  * \retval 0 otherwise
402  */
403 int
404 cfs_expr_list_match(__u32 value, struct cfs_expr_list *expr_list)
405 {
406         struct cfs_range_expr   *expr;
407
408         cfs_list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
409                 if (value >= expr->re_lo && value <= expr->re_hi &&
410                     ((value - expr->re_lo) % expr->re_stride) == 0)
411                         return 1;
412         }
413
414         return 0;
415 }
416 EXPORT_SYMBOL(cfs_expr_list_match);
417
418 /**
419  * Convert express list (\a expr_list) to an array of all matched values
420  *
421  * \retval N N is total number of all matched values
422  * \retval 0 if expression list is empty
423  * \retval < 0 for failure
424  */
425 int
426 cfs_expr_list_values(struct cfs_expr_list *expr_list, int max, __u32 **valpp)
427 {
428         struct cfs_range_expr   *expr;
429         __u32                   *val;
430         int                     count = 0;
431         int                     i;
432
433         cfs_list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
434                 for (i = expr->re_lo; i <= expr->re_hi; i++) {
435                         if (((i - expr->re_lo) % expr->re_stride) == 0)
436                                 count++;
437                 }
438         }
439
440         if (count == 0) /* empty expression list */
441                 return 0;
442
443         if (count > max) {
444                 CERROR("Number of values %d exceeds max allowed %d\n",
445                        max, count);
446                 return -EINVAL;
447         }
448
449         LIBCFS_ALLOC(val, sizeof(val[0]) * count);
450         if (val == NULL)
451                 return -ENOMEM;
452
453         count = 0;
454         cfs_list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
455                 for (i = expr->re_lo; i <= expr->re_hi; i++) {
456                         if (((i - expr->re_lo) % expr->re_stride) == 0)
457                                 val[count++] = i;
458                 }
459         }
460
461         *valpp = val;
462         return count;
463 }
464 EXPORT_SYMBOL(cfs_expr_list_values);
465
466 /**
467  * Frees cfs_range_expr structures of \a expr_list.
468  *
469  * \retval none
470  */
471 void
472 cfs_expr_list_free(struct cfs_expr_list *expr_list)
473 {
474         while (!cfs_list_empty(&expr_list->el_exprs)) {
475                 struct cfs_range_expr *expr;
476
477                 expr = cfs_list_entry(expr_list->el_exprs.next,
478                                       struct cfs_range_expr, re_link),
479                 cfs_list_del(&expr->re_link);
480                 LIBCFS_FREE(expr, sizeof(*expr));
481         }
482
483         LIBCFS_FREE(expr_list, sizeof(*expr_list));
484 }
485 EXPORT_SYMBOL(cfs_expr_list_free);
486
487 void
488 cfs_expr_list_print(struct cfs_expr_list *expr_list)
489 {
490         struct cfs_range_expr *expr;
491
492         cfs_list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
493                 CDEBUG(D_WARNING, "%d-%d/%d\n",
494                        expr->re_lo, expr->re_hi, expr->re_stride);
495         }
496 }
497 EXPORT_SYMBOL(cfs_expr_list_print);
498
499 /**
500  * Parses \<cfs_expr_list\> token of the syntax.
501  *
502  * \retval 1 if \a str parses to \<number\> | \<expr_list\>
503  * \retval 0 otherwise
504  */
505 int
506 cfs_expr_list_parse(char *str, int len, unsigned min, unsigned max,
507                     struct cfs_expr_list **elpp)
508 {
509         struct cfs_expr_list    *expr_list;
510         struct cfs_range_expr   *expr;
511         struct cfs_lstr         src;
512         int                     rc;
513
514         LIBCFS_ALLOC(expr_list, sizeof(*expr_list));
515         if (expr_list == NULL)
516                 return -ENOMEM;
517
518         src.ls_str = str;
519         src.ls_len = len;
520
521         CFS_INIT_LIST_HEAD(&expr_list->el_exprs);
522
523         if (src.ls_str[0] == '[' &&
524             src.ls_str[src.ls_len - 1] == ']') {
525                 src.ls_str++;
526                 src.ls_len -= 2;
527
528                 rc = -EINVAL;
529                 while (src.ls_str != NULL) {
530                         struct cfs_lstr tok;
531
532                         if (!cfs_gettok(&src, ',', &tok)) {
533                                 rc = -EINVAL;
534                                 break;
535                         }
536
537                         rc = cfs_range_expr_parse(&tok, min, max, 1, &expr);
538                         if (rc != 0)
539                                 break;
540
541                         cfs_list_add_tail(&expr->re_link,
542                                           &expr_list->el_exprs);
543                 }
544         } else {
545                 rc = cfs_range_expr_parse(&src, min, max, 0, &expr);
546                 if (rc == 0) {
547                         cfs_list_add_tail(&expr->re_link,
548                                           &expr_list->el_exprs);
549                 }
550         }
551
552         if (rc != 0)
553                 cfs_expr_list_free(expr_list);
554         else
555                 *elpp = expr_list;
556
557         return rc;
558 }
559 EXPORT_SYMBOL(cfs_expr_list_parse);
560
561 /**
562  * Frees cfs_expr_list structures of \a list.
563  *
564  * For each struct cfs_expr_list structure found on \a list it frees
565  * range_expr list attached to it and frees the cfs_expr_list itself.
566  *
567  * \retval none
568  */
569 void
570 cfs_expr_list_free_list(cfs_list_t *list)
571 {
572         struct cfs_expr_list *el;
573
574         while (!cfs_list_empty(list)) {
575                 el = cfs_list_entry(list->next,
576                                     struct cfs_expr_list, el_link);
577                 cfs_list_del(&el->el_link);
578                 cfs_expr_list_free(el);
579         }
580 }
581 EXPORT_SYMBOL(cfs_expr_list_free_list);
582
583 int
584 cfs_ip_addr_parse(char *str, int len, cfs_list_t *list)
585 {
586         struct cfs_expr_list    *el;
587         struct cfs_lstr         src;
588         int                     rc;
589         int                     i;
590
591         src.ls_str = str;
592         src.ls_len = len;
593         i = 0;
594
595         while (src.ls_str != NULL) {
596                 struct cfs_lstr res;
597
598                 if (!cfs_gettok(&src, '.', &res)) {
599                         rc = -EINVAL;
600                         goto out;
601                 }
602
603                 rc = cfs_expr_list_parse(res.ls_str, res.ls_len, 0, 255, &el);
604                 if (rc != 0)
605                         goto out;
606
607                 cfs_list_add_tail(&el->el_link, list);
608                 i++;
609         }
610
611         if (i == 4)
612                 return 0;
613
614         rc = -EINVAL;
615  out:
616         cfs_expr_list_free_list(list);
617
618         return rc;
619 }
620 EXPORT_SYMBOL(cfs_ip_addr_parse);
621
622 /**
623  * Matches address (\a addr) against address set encoded in \a list.
624  *
625  * \retval 1 if \a addr matches
626  * \retval 0 otherwise
627  */
628 int
629 cfs_ip_addr_match(__u32 addr, cfs_list_t *list)
630 {
631         struct cfs_expr_list *el;
632         int i = 0;
633
634         cfs_list_for_each_entry_reverse(el, list, el_link) {
635                 if (!cfs_expr_list_match(addr & 0xff, el))
636                         return 0;
637                 addr >>= 8;
638                 i++;
639         }
640
641         return i == 4;
642 }
643 EXPORT_SYMBOL(cfs_ip_addr_match);
644
645 void
646 cfs_ip_addr_free(cfs_list_t *list)
647 {
648         cfs_expr_list_free_list(list);
649 }
650 EXPORT_SYMBOL(cfs_ip_addr_free);