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