Whamcloud - gitweb
8449065d88440aeef49aa162c7a4efe6631c7c85
[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, Intel Corporation.
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 #include <libcfs/libcfs.h>
44
45 /* non-0 = don't match */
46 int cfs_strncasecmp(const char *s1, const char *s2, size_t n)
47 {
48         if (s1 == NULL || s2 == NULL)
49                 return 1;
50
51         if (n == 0)
52                 return 0;
53
54         while (n-- != 0 && tolower(*s1) == tolower(*s2)) {
55                 if (n == 0 || *s1 == '\0' || *s2 == '\0')
56                         break;
57                 s1++;
58                 s2++;
59         }
60
61         return tolower(*(unsigned char *)s1) - tolower(*(unsigned char *)s2);
62 }
63 EXPORT_SYMBOL(cfs_strncasecmp);
64
65 /* Convert a text string to a bitmask */
66 int cfs_str2mask(const char *str, const char *(*bit2str)(int bit),
67                  int *oldmask, int minmask, int allmask)
68 {
69         const char *debugstr;
70         char op = 0;
71         int newmask = minmask, i, len, found = 0;
72         ENTRY;
73
74         /* <str> must be a list of tokens separated by whitespace
75          * and optionally an operator ('+' or '-').  If an operator
76          * appears first in <str>, '*oldmask' is used as the starting point
77          * (relative), otherwise minmask is used (absolute).  An operator
78          * applies to all following tokens up to the next operator. */
79         while (*str != 0) {
80                 while (isspace(*str))
81                         str++;
82                 if (*str == 0)
83                         break;
84                 if (*str == '+' || *str == '-') {
85                         op = *str++;
86                         if (!found)
87                                 /* only if first token is relative */
88                                 newmask = *oldmask;
89                         while (isspace(*str))
90                                 str++;
91                         if (*str == 0)          /* trailing op */
92                                 return -EINVAL;
93                 }
94
95                 /* find token length */
96                 for (len = 0; str[len] != 0 && !isspace(str[len]) &&
97                       str[len] != '+' && str[len] != '-'; len++);
98
99                 /* match token */
100                 found = 0;
101                 for (i = 0; i < 32; i++) {
102                         debugstr = bit2str(i);
103                         if (debugstr != NULL &&
104                             strlen(debugstr) == len &&
105                             cfs_strncasecmp(str, debugstr, len) == 0) {
106                                 if (op == '-')
107                                         newmask &= ~(1 << i);
108                                 else
109                                         newmask |= (1 << i);
110                                 found = 1;
111                                 break;
112                         }
113                 }
114                 if (!found && len == 3 &&
115                     (cfs_strncasecmp(str, "ALL", len) == 0)) {
116                         if (op == '-')
117                                 newmask = minmask;
118                         else
119                                 newmask = allmask;
120                         found = 1;
121                 }
122                 if (!found) {
123                         CWARN("unknown mask '%.*s'.\n"
124                               "mask usage: [+|-]<all|type> ...\n", len, str);
125                         return -EINVAL;
126                 }
127                 str += len;
128         }
129
130         *oldmask = newmask;
131         return 0;
132 }
133 EXPORT_SYMBOL(cfs_str2mask);
134
135 /* Duplicate a string in a platform-independent way */
136 char *cfs_strdup(const char *str, u_int32_t flags)
137 {
138         size_t lenz; /* length of str + zero byte */
139         char *dup_str;
140
141         lenz = strlen(str) + 1;
142
143         dup_str = kmalloc(lenz, flags);
144         if (dup_str == NULL)
145                 return NULL;
146
147         memcpy(dup_str, str, lenz);
148
149         return dup_str;
150 }
151 EXPORT_SYMBOL(cfs_strdup);
152
153 /**
154  * cfs_{v}snprintf() return the actual size that is printed rather than
155  * the size that would be printed in standard functions.
156  */
157 /* safe vsnprintf */
158 int cfs_vsnprintf(char *buf, size_t size, const char *fmt, va_list args)
159 {
160         int i;
161
162         LASSERT(size > 0);
163         i = vsnprintf(buf, size, fmt, args);
164
165         return  (i >= size ? size - 1 : i);
166 }
167 EXPORT_SYMBOL(cfs_vsnprintf);
168
169 /* safe snprintf */
170 int cfs_snprintf(char *buf, size_t size, const char *fmt, ...)
171 {
172         va_list args;
173         int i;
174
175         va_start(args, fmt);
176         i = cfs_vsnprintf(buf, size, fmt, args);
177         va_end(args);
178
179         return  i;
180 }
181 EXPORT_SYMBOL(cfs_snprintf);
182
183 /* get the first string out of @str */
184 char *cfs_firststr(char *str, size_t size)
185 {
186         size_t i = 0;
187         char  *end;
188
189         /* trim leading spaces */
190         while (i < size && *str && isspace(*str)) {
191                 ++i;
192                 ++str;
193         }
194
195         /* string with all spaces */
196         if (*str == '\0')
197                 goto out;
198
199         end = str;
200         while (i < size && *end != '\0' && !isspace(*end)) {
201                 ++i;
202                 ++end;
203         }
204
205         *end= '\0';
206 out:
207         return str;
208 }
209 EXPORT_SYMBOL(cfs_firststr);
210
211 char *
212 cfs_trimwhite(char *str)
213 {
214         char *end;
215
216         while (cfs_iswhite(*str))
217                 str++;
218
219         end = str + strlen(str);
220         while (end > str) {
221                 if (!cfs_iswhite(end[-1]))
222                         break;
223                 end--;
224         }
225
226         *end = 0;
227         return str;
228 }
229 EXPORT_SYMBOL(cfs_trimwhite);
230
231 /**
232  * Extracts tokens from strings.
233  *
234  * Looks for \a delim in string \a next, sets \a res to point to
235  * substring before the delimiter, sets \a next right after the found
236  * delimiter.
237  *
238  * \retval 1 if \a res points to a string of non-whitespace characters
239  * \retval 0 otherwise
240  */
241 int
242 cfs_gettok(struct cfs_lstr *next, char delim, struct cfs_lstr *res)
243 {
244         char *end;
245
246         if (next->ls_str == NULL)
247                 return 0;
248
249         /* skip leading white spaces */
250         while (next->ls_len) {
251                 if (!cfs_iswhite(*next->ls_str))
252                         break;
253                 next->ls_str++;
254                 next->ls_len--;
255         }
256
257         if (next->ls_len == 0) /* whitespaces only */
258                 return 0;
259
260         if (*next->ls_str == delim) {
261                 /* first non-writespace is the delimiter */
262                 return 0;
263         }
264
265         res->ls_str = next->ls_str;
266         end = memchr(next->ls_str, delim, next->ls_len);
267         if (end == NULL) {
268                 /* there is no the delimeter in the string */
269                 end = next->ls_str + next->ls_len;
270                 next->ls_str = NULL;
271         } else {
272                 next->ls_str = end + 1;
273                 next->ls_len -= (end - res->ls_str + 1);
274         }
275
276         /* skip ending whitespaces */
277         while (--end != res->ls_str) {
278                 if (!cfs_iswhite(*end))
279                         break;
280         }
281
282         res->ls_len = end - res->ls_str + 1;
283         return 1;
284 }
285 EXPORT_SYMBOL(cfs_gettok);
286
287 /**
288  * Converts string to integer.
289  *
290  * Accepts decimal and hexadecimal number recordings.
291  *
292  * \retval 1 if first \a nob chars of \a str convert to decimal or
293  * hexadecimal integer in the range [\a min, \a max]
294  * \retval 0 otherwise
295  */
296 int
297 cfs_str2num_check(char *str, int nob, unsigned *num,
298                   unsigned min, unsigned max)
299 {
300         char    *endp;
301
302         str = cfs_trimwhite(str);
303         *num = strtoul(str, &endp, 0);
304         if (endp == str)
305                 return 0;
306
307         for (; endp < str + nob; endp++) {
308                 if (!cfs_iswhite(*endp))
309                         return 0;
310         }
311
312         return (*num >= min && *num <= max);
313 }
314 EXPORT_SYMBOL(cfs_str2num_check);
315
316 /**
317  * Parses \<range_expr\> token of the syntax. If \a bracketed is false,
318  * \a src should only have a single token which can be \<number\> or  \*
319  *
320  * \retval pointer to allocated range_expr and initialized
321  * range_expr::re_lo, range_expr::re_hi and range_expr:re_stride if \a
322  `* src parses to
323  * \<number\> |
324  * \<number\> '-' \<number\> |
325  * \<number\> '-' \<number\> '/' \<number\>
326  * \retval 0 will be returned if it can be parsed, otherwise -EINVAL or
327  * -ENOMEM will be returned.
328  */
329 int
330 cfs_range_expr_parse(struct cfs_lstr *src, unsigned min, unsigned max,
331                      int bracketed, struct cfs_range_expr **expr)
332 {
333         struct cfs_range_expr   *re;
334         struct cfs_lstr         tok;
335
336         LIBCFS_ALLOC(re, sizeof(*re));
337         if (re == NULL)
338                 return -ENOMEM;
339
340         if (src->ls_len == 1 && src->ls_str[0] == '*') {
341                 re->re_lo = min;
342                 re->re_hi = max;
343                 re->re_stride = 1;
344                 goto out;
345         }
346
347         if (cfs_str2num_check(src->ls_str, src->ls_len,
348                               &re->re_lo, min, max)) {
349                 /* <number> is parsed */
350                 re->re_hi = re->re_lo;
351                 re->re_stride = 1;
352                 goto out;
353         }
354
355         if (!bracketed || !cfs_gettok(src, '-', &tok))
356                 goto failed;
357
358         if (!cfs_str2num_check(tok.ls_str, tok.ls_len,
359                                &re->re_lo, min, max))
360                 goto failed;
361
362         /* <number> - */
363         if (cfs_str2num_check(src->ls_str, src->ls_len,
364                               &re->re_hi, min, max)) {
365                 /* <number> - <number> is parsed */
366                 re->re_stride = 1;
367                 goto out;
368         }
369
370         /* go to check <number> '-' <number> '/' <number> */
371         if (cfs_gettok(src, '/', &tok)) {
372                 if (!cfs_str2num_check(tok.ls_str, tok.ls_len,
373                                        &re->re_hi, min, max))
374                         goto failed;
375
376                 /* <number> - <number> / ... */
377                 if (cfs_str2num_check(src->ls_str, src->ls_len,
378                                       &re->re_stride, min, max)) {
379                         /* <number> - <number> / <number> is parsed */
380                         goto out;
381                 }
382         }
383
384  out:
385         *expr = re;
386         return 0;
387
388  failed:
389         LIBCFS_FREE(re, sizeof(*re));
390         return -EINVAL;
391 }
392 EXPORT_SYMBOL(cfs_range_expr_parse);
393
394 /**
395  * Print the range expression \a re into specified \a buffer.
396  * If \a bracketed is true, expression does not need additional
397  * brackets.
398  *
399  * \retval number of characters written
400  */
401 static int
402 cfs_range_expr_print(char *buffer, int count, struct cfs_range_expr *expr,
403                      bool bracketed)
404 {
405         int i;
406         char s[] = "[";
407         char e[] = "]";
408
409         if (bracketed)
410                 s[0] = e[0] = '\0';
411
412         if (expr->re_lo == expr->re_hi)
413                 i = cfs_snprintf(buffer, count, "%u", expr->re_lo);
414         else if (expr->re_stride == 1)
415                 i = cfs_snprintf(buffer, count, "%s%u-%u%s",
416                                   s, expr->re_lo, expr->re_hi, e);
417         else
418                 i = cfs_snprintf(buffer, count, "%s%u-%u/%u%s",
419                                   s, expr->re_lo, expr->re_hi,
420                                   expr->re_stride, e);
421         return i;
422 }
423
424 /**
425  * Print a list of range expressions (\a expr_list) into specified \a buffer.
426  * If the list contains several expressions, separate them with comma
427  * and surround the list with brackets.
428  *
429  * \retval number of characters written
430  */
431 int
432 cfs_expr_list_print(char *buffer, int count, struct cfs_expr_list *expr_list)
433 {
434         struct cfs_range_expr *expr;
435         int i = 0, j = 0;
436         int numexprs = 0;
437
438         if (count <= 0)
439                 return 0;
440
441         cfs_list_for_each_entry(expr, &expr_list->el_exprs, re_link)
442                 numexprs++;
443
444         if (numexprs > 1)
445                 i += cfs_snprintf(buffer + i, count - i, "[");
446
447         cfs_list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
448                 if (j++ != 0)
449                         i += cfs_snprintf(buffer + i, count - i, ",");
450                 i += cfs_range_expr_print(buffer + i, count - i, expr,
451                                           numexprs > 1);
452         }
453
454         if (numexprs > 1)
455                 i += cfs_snprintf(buffer + i, count - i, "]");
456
457         return i;
458 }
459 EXPORT_SYMBOL(cfs_expr_list_print);
460
461 /**
462  * Matches value (\a value) against ranges expression list \a expr_list.
463  *
464  * \retval 1 if \a value matches
465  * \retval 0 otherwise
466  */
467 int
468 cfs_expr_list_match(__u32 value, struct cfs_expr_list *expr_list)
469 {
470         struct cfs_range_expr   *expr;
471
472         cfs_list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
473                 if (value >= expr->re_lo && value <= expr->re_hi &&
474                     ((value - expr->re_lo) % expr->re_stride) == 0)
475                         return 1;
476         }
477
478         return 0;
479 }
480 EXPORT_SYMBOL(cfs_expr_list_match);
481
482 /**
483  * Convert express list (\a expr_list) to an array of all matched values
484  *
485  * \retval N N is total number of all matched values
486  * \retval 0 if expression list is empty
487  * \retval < 0 for failure
488  */
489 int
490 cfs_expr_list_values(struct cfs_expr_list *expr_list, int max, __u32 **valpp)
491 {
492         struct cfs_range_expr   *expr;
493         __u32                   *val;
494         int                     count = 0;
495         int                     i;
496
497         cfs_list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
498                 for (i = expr->re_lo; i <= expr->re_hi; i++) {
499                         if (((i - expr->re_lo) % expr->re_stride) == 0)
500                                 count++;
501                 }
502         }
503
504         if (count == 0) /* empty expression list */
505                 return 0;
506
507         if (count > max) {
508                 CERROR("Number of values %d exceeds max allowed %d\n",
509                        max, count);
510                 return -EINVAL;
511         }
512
513         LIBCFS_ALLOC(val, sizeof(val[0]) * count);
514         if (val == NULL)
515                 return -ENOMEM;
516
517         count = 0;
518         cfs_list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
519                 for (i = expr->re_lo; i <= expr->re_hi; i++) {
520                         if (((i - expr->re_lo) % expr->re_stride) == 0)
521                                 val[count++] = i;
522                 }
523         }
524
525         *valpp = val;
526         return count;
527 }
528 EXPORT_SYMBOL(cfs_expr_list_values);
529
530 /**
531  * Frees cfs_range_expr structures of \a expr_list.
532  *
533  * \retval none
534  */
535 void
536 cfs_expr_list_free(struct cfs_expr_list *expr_list)
537 {
538         while (!cfs_list_empty(&expr_list->el_exprs)) {
539                 struct cfs_range_expr *expr;
540
541                 expr = cfs_list_entry(expr_list->el_exprs.next,
542                                       struct cfs_range_expr, re_link),
543                 cfs_list_del(&expr->re_link);
544                 LIBCFS_FREE(expr, sizeof(*expr));
545         }
546
547         LIBCFS_FREE(expr_list, sizeof(*expr_list));
548 }
549 EXPORT_SYMBOL(cfs_expr_list_free);
550
551 /**
552  * Parses \<cfs_expr_list\> token of the syntax.
553  *
554  * \retval 0 if \a str parses to \<number\> | \<expr_list\>
555  * \retval -errno otherwise
556  */
557 int
558 cfs_expr_list_parse(char *str, int len, unsigned min, unsigned max,
559                     struct cfs_expr_list **elpp)
560 {
561         struct cfs_expr_list    *expr_list;
562         struct cfs_range_expr   *expr;
563         struct cfs_lstr         src;
564         int                     rc;
565
566         LIBCFS_ALLOC(expr_list, sizeof(*expr_list));
567         if (expr_list == NULL)
568                 return -ENOMEM;
569
570         src.ls_str = str;
571         src.ls_len = len;
572
573         CFS_INIT_LIST_HEAD(&expr_list->el_exprs);
574
575         if (src.ls_str[0] == '[' &&
576             src.ls_str[src.ls_len - 1] == ']') {
577                 src.ls_str++;
578                 src.ls_len -= 2;
579
580                 rc = -EINVAL;
581                 while (src.ls_str != NULL) {
582                         struct cfs_lstr tok;
583
584                         if (!cfs_gettok(&src, ',', &tok)) {
585                                 rc = -EINVAL;
586                                 break;
587                         }
588
589                         rc = cfs_range_expr_parse(&tok, min, max, 1, &expr);
590                         if (rc != 0)
591                                 break;
592
593                         cfs_list_add_tail(&expr->re_link,
594                                           &expr_list->el_exprs);
595                 }
596         } else {
597                 rc = cfs_range_expr_parse(&src, min, max, 0, &expr);
598                 if (rc == 0) {
599                         cfs_list_add_tail(&expr->re_link,
600                                           &expr_list->el_exprs);
601                 }
602         }
603
604         if (rc != 0)
605                 cfs_expr_list_free(expr_list);
606         else
607                 *elpp = expr_list;
608
609         return rc;
610 }
611 EXPORT_SYMBOL(cfs_expr_list_parse);
612
613 /**
614  * Frees cfs_expr_list structures of \a list.
615  *
616  * For each struct cfs_expr_list structure found on \a list it frees
617  * range_expr list attached to it and frees the cfs_expr_list itself.
618  *
619  * \retval none
620  */
621 void
622 cfs_expr_list_free_list(cfs_list_t *list)
623 {
624         struct cfs_expr_list *el;
625
626         while (!cfs_list_empty(list)) {
627                 el = cfs_list_entry(list->next,
628                                     struct cfs_expr_list, el_link);
629                 cfs_list_del(&el->el_link);
630                 cfs_expr_list_free(el);
631         }
632 }
633 EXPORT_SYMBOL(cfs_expr_list_free_list);
634
635 int
636 cfs_ip_addr_parse(char *str, int len, cfs_list_t *list)
637 {
638         struct cfs_expr_list    *el;
639         struct cfs_lstr         src;
640         int                     rc;
641         int                     i;
642
643         src.ls_str = str;
644         src.ls_len = len;
645         i = 0;
646
647         while (src.ls_str != NULL) {
648                 struct cfs_lstr res;
649
650                 if (!cfs_gettok(&src, '.', &res)) {
651                         rc = -EINVAL;
652                         goto out;
653                 }
654
655                 rc = cfs_expr_list_parse(res.ls_str, res.ls_len, 0, 255, &el);
656                 if (rc != 0)
657                         goto out;
658
659                 cfs_list_add_tail(&el->el_link, list);
660                 i++;
661         }
662
663         if (i == 4)
664                 return 0;
665
666         rc = -EINVAL;
667  out:
668         cfs_expr_list_free_list(list);
669
670         return rc;
671 }
672 EXPORT_SYMBOL(cfs_ip_addr_parse);
673
674 /**
675  * Matches address (\a addr) against address set encoded in \a list.
676  *
677  * \retval 1 if \a addr matches
678  * \retval 0 otherwise
679  */
680 int
681 cfs_ip_addr_match(__u32 addr, cfs_list_t *list)
682 {
683         struct cfs_expr_list *el;
684         int i = 0;
685
686         cfs_list_for_each_entry_reverse(el, list, el_link) {
687                 if (!cfs_expr_list_match(addr & 0xff, el))
688                         return 0;
689                 addr >>= 8;
690                 i++;
691         }
692
693         return i == 4;
694 }
695 EXPORT_SYMBOL(cfs_ip_addr_match);
696
697 void
698 cfs_ip_addr_free(cfs_list_t *list)
699 {
700         cfs_expr_list_free_list(list);
701 }
702 EXPORT_SYMBOL(cfs_ip_addr_free);