Whamcloud - gitweb
8f541c67d1eaf597a0c2d4b3c8ea452ecb8e473b
[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.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2012, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * String manipulation functions.
33  *
34  * libcfs/libcfs/util/string.c
35  *
36  * Author: Nathan Rutman <nathan.rutman@sun.com>
37  */
38 #include <ctype.h>
39 #include <errno.h>
40 #include <stdbool.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <limits.h>
45 #include <unistd.h>
46 #include <libcfs/util/string.h>
47
48 /*
49  * According manual of strlcpy() and strlcat() the functions should return
50  * the total length of the string they tried to create. For strlcpy() that
51  * means the length of src. For strlcat() that means the initial length of
52  * dst plus the length of src. So, the function strnlen() cannot be used
53  * otherwise the return value will be wrong.
54  */
55 #ifndef HAVE_STRLCPY /* not in glibc for RHEL 5.x, remove when obsolete */
56 size_t strlcpy(char *dst, const char *src, size_t size)
57 {
58         size_t ret = strlen(src);
59
60         if (size) {
61                 size_t len = (ret >= size) ? size - 1 : ret;
62                 memcpy(dst, src, len);
63                 dst[len] = '\0';
64         }
65         return ret;
66 }
67 #endif
68
69 #ifndef HAVE_STRLCAT /* not in glibc for RHEL 5.x, remove when obsolete */
70 size_t strlcat(char *dst, const char *src, size_t size)
71 {
72         size_t dsize = strlen(dst);
73         size_t len = strlen(src);
74         size_t ret = dsize + len;
75
76         dst  += dsize;
77         size -= dsize;
78         if (len >= size)
79                 len = size-1;
80         memcpy(dst, src, len);
81         dst[len] = '\0';
82         return ret;
83 }
84 #endif
85
86 /**
87  * Extracts tokens from strings.
88  *
89  * Looks for \a delim in string \a next, sets \a res to point to
90  * substring before the delimiter, sets \a next right after the found
91  * delimiter.
92  *
93  * \retval 1 if \a res points to a string of non-whitespace characters
94  * \retval 0 otherwise
95  */
96 int
97 cfs_gettok(struct cfs_lstr *next, char delim, struct cfs_lstr *res)
98 {
99         char *end;
100
101         if (next->ls_str == NULL)
102                 return 0;
103
104         /* skip leading white spaces */
105         while (next->ls_len) {
106                 if (!isspace(*next->ls_str))
107                         break;
108                 next->ls_str++;
109                 next->ls_len--;
110         }
111
112         if (next->ls_len == 0) /* whitespaces only */
113                 return 0;
114
115         if (*next->ls_str == delim) {
116                 /* first non-writespace is the delimiter */
117                 return 0;
118         }
119
120         res->ls_str = next->ls_str;
121         end = memchr(next->ls_str, delim, next->ls_len);
122         if (end == NULL) {
123                 /* there is no the delimeter in the string */
124                 end = next->ls_str + next->ls_len;
125                 next->ls_str = NULL;
126         } else {
127                 next->ls_str = end + 1;
128                 next->ls_len -= (end - res->ls_str + 1);
129         }
130
131         /* skip ending whitespaces */
132         while (--end != res->ls_str) {
133                 if (!isspace(*end))
134                         break;
135         }
136
137         res->ls_len = end - res->ls_str + 1;
138         return 1;
139 }
140
141 /**
142  * Converts string to integer.
143  *
144  * Accepts decimal and hexadecimal number recordings.
145  *
146  * \retval 1 if first \a nob chars of \a str convert to decimal or
147  * hexadecimal integer in the range [\a min, \a max]
148  * \retval 0 otherwise
149  */
150 int
151 cfs_str2num_check(char *str, int nob, unsigned *num,
152                   unsigned min, unsigned max)
153 {
154         char    *endp;
155
156         *num = strtoul(str, &endp, 0);
157         if (endp == str)
158                 return 0;
159
160         for (; endp < str + nob; endp++) {
161                 if (!isspace(*endp))
162                         return 0;
163         }
164
165         return (*num >= min && *num <= max);
166 }
167
168 /**
169  * Parses \<range_expr\> token of the syntax. If \a bracketed is false,
170  * \a src should only have a single token which can be \<number\> or  \*
171  *
172  * \retval pointer to allocated range_expr and initialized
173  * range_expr::re_lo, range_expr::re_hi and range_expr:re_stride if \a
174  * src parses to
175  * \<number\> |
176  * \<number\> '-' \<number\> |
177  * \<number\> '-' \<number\> '/' \<number\>
178  * \retval 0 will be returned if it can be parsed, otherwise -EINVAL or
179  * -ENOMEM will be returned.
180  */
181 static int
182 cfs_range_expr_parse(struct cfs_lstr *src, unsigned min, unsigned max,
183                      int bracketed, struct cfs_range_expr **expr)
184 {
185         struct cfs_range_expr   *re;
186         struct cfs_lstr         tok;
187
188         re = calloc(1, sizeof(*re));
189         if (re == NULL)
190                 return -ENOMEM;
191
192         if (src->ls_len == 1 && src->ls_str[0] == '*') {
193                 re->re_lo = min;
194                 re->re_hi = max;
195                 re->re_stride = 1;
196                 goto out;
197         }
198
199         if (cfs_str2num_check(src->ls_str, src->ls_len,
200                               &re->re_lo, min, max)) {
201                 /* <number> is parsed */
202                 re->re_hi = re->re_lo;
203                 re->re_stride = 1;
204                 goto out;
205         }
206
207         if (!bracketed || !cfs_gettok(src, '-', &tok))
208                 goto failed;
209
210         if (!cfs_str2num_check(tok.ls_str, tok.ls_len,
211                                &re->re_lo, min, max))
212                 goto failed;
213
214         /* <number> - */
215         if (cfs_str2num_check(src->ls_str, src->ls_len,
216                               &re->re_hi, min, max)) {
217                 /* <number> - <number> is parsed */
218                 re->re_stride = 1;
219                 goto out;
220         }
221
222         /* go to check <number> '-' <number> '/' <number> */
223         if (cfs_gettok(src, '/', &tok)) {
224                 if (!cfs_str2num_check(tok.ls_str, tok.ls_len,
225                                        &re->re_hi, min, max))
226                         goto failed;
227
228                 /* <number> - <number> / ... */
229                 if (cfs_str2num_check(src->ls_str, src->ls_len,
230                                       &re->re_stride, min, max)) {
231                         /* <number> - <number> / <number> is parsed */
232                         goto out;
233                 }
234         }
235
236  out:
237         *expr = re;
238         return 0;
239
240  failed:
241         free(re);
242         return -EINVAL;
243 }
244
245 /**
246  * Print the range expression \a re into specified \a buffer.
247  * If \a bracketed is true, expression does not need additional
248  * brackets.
249  *
250  * \retval number of characters written
251  */
252 static int
253 cfs_range_expr_print(char *buffer, int count, struct cfs_range_expr *expr,
254                      bool bracketed)
255 {
256         int i;
257         char s[] = "[";
258         char e[] = "]";
259
260         if (bracketed)
261                 s[0] = e[0] = '\0';
262
263         if (expr->re_lo == expr->re_hi)
264                 i = snprintf(buffer, count, "%u", expr->re_lo);
265         else if (expr->re_stride == 1)
266                 i = snprintf(buffer, count, "%s%u-%u%s",
267                                   s, expr->re_lo, expr->re_hi, e);
268         else
269                 i = snprintf(buffer, count, "%s%u-%u/%u%s",
270                                   s, expr->re_lo, expr->re_hi,
271                                   expr->re_stride, e);
272         return i;
273 }
274
275 /**
276  * Print a list of range expressions (\a expr_list) into specified \a buffer.
277  * If the list contains several expressions, separate them with comma
278  * and surround the list with brackets.
279  *
280  * \retval number of characters written
281  */
282 int
283 cfs_expr_list_print(char *buffer, int count, struct cfs_expr_list *expr_list)
284 {
285         struct cfs_range_expr *expr;
286         int i = 0, j = 0;
287         int numexprs = 0;
288
289         if (count <= 0)
290                 return 0;
291
292         list_for_each_entry(expr, &expr_list->el_exprs, re_link)
293                 numexprs++;
294
295         if (numexprs > 1)
296                 i += snprintf(buffer + i, count - i, "[");
297
298         list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
299                 if (j++ != 0)
300                         i += snprintf(buffer + i, count - i, ",");
301                 i += cfs_range_expr_print(buffer + i, count - i, expr,
302                                           numexprs > 1);
303         }
304
305         if (numexprs > 1)
306                 i += snprintf(buffer + i, count - i, "]");
307
308         return i;
309 }
310
311 /**
312  * Matches value (\a value) against ranges expression list \a expr_list.
313  *
314  * \retval 1 if \a value matches
315  * \retval 0 otherwise
316  */
317 int
318 cfs_expr_list_match(__u32 value, struct cfs_expr_list *expr_list)
319 {
320         struct cfs_range_expr   *expr;
321
322         list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
323                 if (value >= expr->re_lo && value <= expr->re_hi &&
324                     ((value - expr->re_lo) % expr->re_stride) == 0)
325                         return 1;
326         }
327
328         return 0;
329 }
330
331 /**
332  * Convert express list (\a expr_list) to an array of all matched values
333  *
334  * \retval N N is total number of all matched values
335  * \retval 0 if expression list is empty
336  * \retval < 0 for failure
337  */
338 int
339 cfs_expr_list_values(struct cfs_expr_list *expr_list, int max, __u32 **valpp)
340 {
341         struct cfs_range_expr   *expr;
342         __u32                   *val;
343         int                     count = 0;
344         int                     i;
345
346         list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
347                 for (i = expr->re_lo; i <= expr->re_hi; i++) {
348                         if (((i - expr->re_lo) % expr->re_stride) == 0)
349                                 count++;
350                 }
351         }
352
353         if (count == 0) /* empty expression list */
354                 return 0;
355
356         if (count > max)
357                 return -EINVAL;
358
359         val = calloc(sizeof(val[0]), count);
360         if (val == NULL)
361                 return -ENOMEM;
362
363         count = 0;
364         list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
365                 for (i = expr->re_lo; i <= expr->re_hi; i++) {
366                         if (((i - expr->re_lo) % expr->re_stride) == 0)
367                                 val[count++] = i;
368                 }
369         }
370
371         *valpp = val;
372         return count;
373 }
374
375 void
376 cfs_expr_list_values_free(__u32 *values, int num)
377 {
378         /* This array is allocated by LIBCFS_ALLOC(), so it shouldn't be freed
379          * by OBD_FREE() if it's called by module other than libcfs & LNet,
380          * otherwise we will see fake memory leak */
381         free(values);
382 }
383
384 /**
385  * Frees cfs_range_expr structures of \a expr_list.
386  *
387  * \retval none
388  */
389 void
390 cfs_expr_list_free(struct cfs_expr_list *expr_list)
391 {
392         while (!list_empty(&expr_list->el_exprs)) {
393                 struct cfs_range_expr *expr;
394
395                 expr = list_entry(expr_list->el_exprs.next,
396                                   struct cfs_range_expr, re_link);
397                 list_del(&expr->re_link);
398                 free(expr);
399         }
400
401         free(expr_list);
402 }
403
404 /**
405  * Parses \<cfs_expr_list\> token of the syntax.
406  *
407  * \retval 0 if \a str parses to \<number\> | \<expr_list\>
408  * \retval -errno otherwise
409  */
410 int
411 cfs_expr_list_parse(char *str, int len, unsigned min, unsigned max,
412                     struct cfs_expr_list **elpp)
413 {
414         struct cfs_expr_list    *expr_list;
415         struct cfs_range_expr   *expr;
416         struct cfs_lstr         src;
417         int                     rc;
418
419         expr_list = calloc(1, sizeof(*expr_list));
420         if (expr_list == NULL)
421                 return -ENOMEM;
422
423         src.ls_str = str;
424         src.ls_len = len;
425
426         INIT_LIST_HEAD(&expr_list->el_exprs);
427
428         if (src.ls_str[0] == '[' &&
429             src.ls_str[src.ls_len - 1] == ']') {
430                 src.ls_str++;
431                 src.ls_len -= 2;
432
433                 rc = -EINVAL;
434                 while (src.ls_str != NULL) {
435                         struct cfs_lstr tok;
436
437                         if (!cfs_gettok(&src, ',', &tok)) {
438                                 rc = -EINVAL;
439                                 break;
440                         }
441
442                         rc = cfs_range_expr_parse(&tok, min, max, 1, &expr);
443                         if (rc != 0)
444                                 break;
445
446                         list_add_tail(&expr->re_link,
447                                           &expr_list->el_exprs);
448                 }
449         } else {
450                 rc = cfs_range_expr_parse(&src, min, max, 0, &expr);
451                 if (rc == 0) {
452                         list_add_tail(&expr->re_link,
453                                           &expr_list->el_exprs);
454                 }
455         }
456
457         if (rc != 0)
458                 cfs_expr_list_free(expr_list);
459         else
460                 *elpp = expr_list;
461
462         return rc;
463 }
464
465 /**
466  * Frees cfs_expr_list structures of \a list.
467  *
468  * For each struct cfs_expr_list structure found on \a list it frees
469  * range_expr list attached to it and frees the cfs_expr_list itself.
470  *
471  * \retval none
472  */
473 void
474 cfs_expr_list_free_list(struct list_head *list)
475 {
476         struct cfs_expr_list *el;
477
478         while (!list_empty(list)) {
479                 el = list_entry(list->next,
480                                     struct cfs_expr_list, el_link);
481                 list_del(&el->el_link);
482                 cfs_expr_list_free(el);
483         }
484 }
485
486 /**
487  * cfs_abs_path() - Get the absolute path of a relative path
488  * @request_path:       The relative path to be resolved
489  * @resolved_path:      Set to the resolved absolute path
490  *
491  * Returns the canonicalized absolute pathname.  This function is a wrapper to
492  * realpath, but will work even if the target file does not exist.  All
493  * directories in the path must exist.
494  *
495  * Return: On success, 0 is returned and resolved_path points to an allocated
496  * string containing the absolute pathname.  On error, errno is set
497  * appropriately, -errno is returned, and resolved_path points to NULL.
498  */
499 int cfs_abs_path(const char *request_path, char **resolved_path)
500 {
501         char  buf[PATH_MAX + 1] = "";
502         char *path;
503         char *ptr;
504         int len;
505         int rc = 0;
506         const char *fmt;
507
508         path = malloc(sizeof(buf));
509         if (path == NULL)
510                 return -ENOMEM;
511
512         if (request_path[0] != '/') {
513                 if (getcwd(path, sizeof(buf) - 1) == NULL) {
514                         rc = -errno;
515                         goto out;
516                 }
517                 len = snprintf(buf, sizeof(buf), "%s/%s", path, request_path);
518                 if (len >= sizeof(buf)) {
519                         rc = -ENAMETOOLONG;
520                         goto out;
521                 }
522         } else {
523                 /* skip duplicate leading '/' */
524                 len = snprintf(buf, sizeof(buf), "%s",
525                                request_path + strspn(request_path, "/") - 1);
526                 if (len >= sizeof(buf)) {
527                         rc = -ENAMETOOLONG;
528                         goto out;
529                 }
530         }
531
532         /* if filename not in root directory, call realpath for parent path */
533         ptr = strrchr(buf, '/');
534         if (ptr != buf) {
535                 *ptr = '\0';
536                 if (path != realpath(buf, path)) {
537                         rc = -errno;
538                         goto out;
539                 }
540                 /* add the filename back */
541                 len = strlen(path);
542                 fmt = (path[len - 1] == '/') ? "%s" : "/%s";
543                 len = snprintf(path + len, sizeof(buf) - len, fmt, ptr + 1);
544                 if (len >= sizeof(buf) - len) {
545                         rc = -ENAMETOOLONG;
546                         goto out;
547                 }
548         } else {
549                 len = snprintf(path, sizeof(buf), "%s", buf);
550                 if (len >= sizeof(buf)) {
551                         rc = -ENAMETOOLONG;
552                         goto out;
553                 }
554         }
555
556 out:
557         if (rc == 0) {
558                 *resolved_path = path;
559         } else {
560                 *resolved_path = NULL;
561                 free(path);
562         }
563         return rc;
564 }