Whamcloud - gitweb
LU-6245 libcfs: move cfs_ip_addr_* function from kernel libcfs to LNet
[fs/lustre-release.git] / libcfs / libcfs / util / 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, 2014, 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/util/string.c
39  *
40  * Author: Nathan Rutman <nathan.rutman@sun.com>
41  */
42 #include <ctype.h>
43 #include <errno.h>
44 #include <stdbool.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <libcfs/util/string.h>
49
50 /*
51  * According manual of strlcpy() and strlcat() the functions should return
52  * the total length of the string they tried to create. For strlcpy() that
53  * means the length of src. For strlcat() that means the initial length of
54  * dst plus the length of src. So, the function strnlen() cannot be used
55  * otherwise the return value will be wrong.
56  */
57 #ifndef HAVE_STRLCPY /* not in glibc for RHEL 5.x, remove when obsolete */
58 size_t strlcpy(char *dst, const char *src, size_t size)
59 {
60         size_t ret = strlen(src);
61
62         if (size) {
63                 size_t len = (ret >= size) ? size - 1 : ret;
64                 memcpy(dst, src, len);
65                 dst[len] = '\0';
66         }
67         return ret;
68 }
69 #endif
70
71 #ifndef HAVE_STRLCAT /* not in glibc for RHEL 5.x, remove when obsolete */
72 size_t strlcat(char *dst, const char *src, size_t size)
73 {
74         size_t dsize = strlen(dst);
75         size_t len = strlen(src);
76         size_t ret = dsize + len;
77
78         dst  += dsize;
79         size -= dsize;
80         if (len >= size)
81                 len = size-1;
82         memcpy(dst, src, len);
83         dst[len] = '\0';
84         return ret;
85 }
86 #endif
87
88 /**
89  * Extracts tokens from strings.
90  *
91  * Looks for \a delim in string \a next, sets \a res to point to
92  * substring before the delimiter, sets \a next right after the found
93  * delimiter.
94  *
95  * \retval 1 if \a res points to a string of non-whitespace characters
96  * \retval 0 otherwise
97  */
98 int
99 cfs_gettok(struct cfs_lstr *next, char delim, struct cfs_lstr *res)
100 {
101         char *end;
102
103         if (next->ls_str == NULL)
104                 return 0;
105
106         /* skip leading white spaces */
107         while (next->ls_len) {
108                 if (!isspace(*next->ls_str))
109                         break;
110                 next->ls_str++;
111                 next->ls_len--;
112         }
113
114         if (next->ls_len == 0) /* whitespaces only */
115                 return 0;
116
117         if (*next->ls_str == delim) {
118                 /* first non-writespace is the delimiter */
119                 return 0;
120         }
121
122         res->ls_str = next->ls_str;
123         end = memchr(next->ls_str, delim, next->ls_len);
124         if (end == NULL) {
125                 /* there is no the delimeter in the string */
126                 end = next->ls_str + next->ls_len;
127                 next->ls_str = NULL;
128         } else {
129                 next->ls_str = end + 1;
130                 next->ls_len -= (end - res->ls_str + 1);
131         }
132
133         /* skip ending whitespaces */
134         while (--end != res->ls_str) {
135                 if (!isspace(*end))
136                         break;
137         }
138
139         res->ls_len = end - res->ls_str + 1;
140         return 1;
141 }
142
143 /**
144  * Converts string to integer.
145  *
146  * Accepts decimal and hexadecimal number recordings.
147  *
148  * \retval 1 if first \a nob chars of \a str convert to decimal or
149  * hexadecimal integer in the range [\a min, \a max]
150  * \retval 0 otherwise
151  */
152 int
153 cfs_str2num_check(char *str, int nob, unsigned *num,
154                   unsigned min, unsigned max)
155 {
156         char    *endp;
157
158         *num = strtoul(str, &endp, 0);
159         if (endp == str)
160                 return 0;
161
162         for (; endp < str + nob; endp++) {
163                 if (!isspace(*endp))
164                         return 0;
165         }
166
167         return (*num >= min && *num <= max);
168 }
169
170 /**
171  * Parses \<range_expr\> token of the syntax. If \a bracketed is false,
172  * \a src should only have a single token which can be \<number\> or  \*
173  *
174  * \retval pointer to allocated range_expr and initialized
175  * range_expr::re_lo, range_expr::re_hi and range_expr:re_stride if \a
176  * src parses to
177  * \<number\> |
178  * \<number\> '-' \<number\> |
179  * \<number\> '-' \<number\> '/' \<number\>
180  * \retval 0 will be returned if it can be parsed, otherwise -EINVAL or
181  * -ENOMEM will be returned.
182  */
183 static int
184 cfs_range_expr_parse(struct cfs_lstr *src, unsigned min, unsigned max,
185                      int bracketed, struct cfs_range_expr **expr)
186 {
187         struct cfs_range_expr   *re;
188         struct cfs_lstr         tok;
189
190         re = calloc(1, sizeof(*re));
191         if (re == NULL)
192                 return -ENOMEM;
193
194         if (src->ls_len == 1 && src->ls_str[0] == '*') {
195                 re->re_lo = min;
196                 re->re_hi = max;
197                 re->re_stride = 1;
198                 goto out;
199         }
200
201         if (cfs_str2num_check(src->ls_str, src->ls_len,
202                               &re->re_lo, min, max)) {
203                 /* <number> is parsed */
204                 re->re_hi = re->re_lo;
205                 re->re_stride = 1;
206                 goto out;
207         }
208
209         if (!bracketed || !cfs_gettok(src, '-', &tok))
210                 goto failed;
211
212         if (!cfs_str2num_check(tok.ls_str, tok.ls_len,
213                                &re->re_lo, min, max))
214                 goto failed;
215
216         /* <number> - */
217         if (cfs_str2num_check(src->ls_str, src->ls_len,
218                               &re->re_hi, min, max)) {
219                 /* <number> - <number> is parsed */
220                 re->re_stride = 1;
221                 goto out;
222         }
223
224         /* go to check <number> '-' <number> '/' <number> */
225         if (cfs_gettok(src, '/', &tok)) {
226                 if (!cfs_str2num_check(tok.ls_str, tok.ls_len,
227                                        &re->re_hi, min, max))
228                         goto failed;
229
230                 /* <number> - <number> / ... */
231                 if (cfs_str2num_check(src->ls_str, src->ls_len,
232                                       &re->re_stride, min, max)) {
233                         /* <number> - <number> / <number> is parsed */
234                         goto out;
235                 }
236         }
237
238  out:
239         *expr = re;
240         return 0;
241
242  failed:
243         free(re);
244         return -EINVAL;
245 }
246
247 /**
248  * Print the range expression \a re into specified \a buffer.
249  * If \a bracketed is true, expression does not need additional
250  * brackets.
251  *
252  * \retval number of characters written
253  */
254 static int
255 cfs_range_expr_print(char *buffer, int count, struct cfs_range_expr *expr,
256                      bool bracketed)
257 {
258         int i;
259         char s[] = "[";
260         char e[] = "]";
261
262         if (bracketed)
263                 s[0] = e[0] = '\0';
264
265         if (expr->re_lo == expr->re_hi)
266                 i = snprintf(buffer, count, "%u", expr->re_lo);
267         else if (expr->re_stride == 1)
268                 i = snprintf(buffer, count, "%s%u-%u%s",
269                                   s, expr->re_lo, expr->re_hi, e);
270         else
271                 i = snprintf(buffer, count, "%s%u-%u/%u%s",
272                                   s, expr->re_lo, expr->re_hi,
273                                   expr->re_stride, e);
274         return i;
275 }
276
277 /**
278  * Print a list of range expressions (\a expr_list) into specified \a buffer.
279  * If the list contains several expressions, separate them with comma
280  * and surround the list with brackets.
281  *
282  * \retval number of characters written
283  */
284 int
285 cfs_expr_list_print(char *buffer, int count, struct cfs_expr_list *expr_list)
286 {
287         struct cfs_range_expr *expr;
288         int i = 0, j = 0;
289         int numexprs = 0;
290
291         if (count <= 0)
292                 return 0;
293
294         list_for_each_entry(expr, &expr_list->el_exprs, re_link)
295                 numexprs++;
296
297         if (numexprs > 1)
298                 i += snprintf(buffer + i, count - i, "[");
299
300         list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
301                 if (j++ != 0)
302                         i += snprintf(buffer + i, count - i, ",");
303                 i += cfs_range_expr_print(buffer + i, count - i, expr,
304                                           numexprs > 1);
305         }
306
307         if (numexprs > 1)
308                 i += snprintf(buffer + i, count - i, "]");
309
310         return i;
311 }
312
313 /**
314  * Matches value (\a value) against ranges expression list \a expr_list.
315  *
316  * \retval 1 if \a value matches
317  * \retval 0 otherwise
318  */
319 int
320 cfs_expr_list_match(__u32 value, struct cfs_expr_list *expr_list)
321 {
322         struct cfs_range_expr   *expr;
323
324         list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
325                 if (value >= expr->re_lo && value <= expr->re_hi &&
326                     ((value - expr->re_lo) % expr->re_stride) == 0)
327                         return 1;
328         }
329
330         return 0;
331 }
332
333 /**
334  * Frees cfs_range_expr structures of \a expr_list.
335  *
336  * \retval none
337  */
338 static void
339 cfs_expr_list_free(struct cfs_expr_list *expr_list)
340 {
341         while (!list_empty(&expr_list->el_exprs)) {
342                 struct cfs_range_expr *expr;
343
344                 expr = list_entry(expr_list->el_exprs.next,
345                                   struct cfs_range_expr, re_link);
346                 list_del(&expr->re_link);
347                 free(expr);
348         }
349
350         free(expr_list);
351 }
352
353 /**
354  * Parses \<cfs_expr_list\> token of the syntax.
355  *
356  * \retval 0 if \a str parses to \<number\> | \<expr_list\>
357  * \retval -errno otherwise
358  */
359 int
360 cfs_expr_list_parse(char *str, int len, unsigned min, unsigned max,
361                     struct cfs_expr_list **elpp)
362 {
363         struct cfs_expr_list    *expr_list;
364         struct cfs_range_expr   *expr;
365         struct cfs_lstr         src;
366         int                     rc;
367
368         expr_list = calloc(1, sizeof(*expr_list));
369         if (expr_list == NULL)
370                 return -ENOMEM;
371
372         src.ls_str = str;
373         src.ls_len = len;
374
375         INIT_LIST_HEAD(&expr_list->el_exprs);
376
377         if (src.ls_str[0] == '[' &&
378             src.ls_str[src.ls_len - 1] == ']') {
379                 src.ls_str++;
380                 src.ls_len -= 2;
381
382                 rc = -EINVAL;
383                 while (src.ls_str != NULL) {
384                         struct cfs_lstr tok;
385
386                         if (!cfs_gettok(&src, ',', &tok)) {
387                                 rc = -EINVAL;
388                                 break;
389                         }
390
391                         rc = cfs_range_expr_parse(&tok, min, max, 1, &expr);
392                         if (rc != 0)
393                                 break;
394
395                         list_add_tail(&expr->re_link,
396                                           &expr_list->el_exprs);
397                 }
398         } else {
399                 rc = cfs_range_expr_parse(&src, min, max, 0, &expr);
400                 if (rc == 0) {
401                         list_add_tail(&expr->re_link,
402                                           &expr_list->el_exprs);
403                 }
404         }
405
406         if (rc != 0)
407                 cfs_expr_list_free(expr_list);
408         else
409                 *elpp = expr_list;
410
411         return rc;
412 }
413
414 /**
415  * Frees cfs_expr_list structures of \a list.
416  *
417  * For each struct cfs_expr_list structure found on \a list it frees
418  * range_expr list attached to it and frees the cfs_expr_list itself.
419  *
420  * \retval none
421  */
422 void
423 cfs_expr_list_free_list(struct list_head *list)
424 {
425         struct cfs_expr_list *el;
426
427         while (!list_empty(list)) {
428                 el = list_entry(list->next,
429                                     struct cfs_expr_list, el_link);
430                 list_del(&el->el_link);
431                 cfs_expr_list_free(el);
432         }
433 }