Fix strlower_m() to return an error indication.
[kai/samba.git] / source3 / lib / util_str.c
1 /*
2    Unix SMB/CIFS implementation.
3    Samba utility functions
4
5    Copyright (C) Andrew Tridgell 1992-2001
6    Copyright (C) Simo Sorce      2001-2002
7    Copyright (C) Martin Pool     2003
8    Copyright (C) James Peach     2006
9    Copyright (C) Jeremy Allison  1992-2007
10
11    This program is free software; you can redistribute it and/or modify
12    it under the terms of the GNU General Public License as published by
13    the Free Software Foundation; either version 3 of the License, or
14    (at your option) any later version.
15
16    This program is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19    GNU General Public License for more details.
20
21    You should have received a copy of the GNU General Public License
22    along with this program.  If not, see <http://www.gnu.org/licenses/>.
23 */
24
25 #include "includes.h"
26 #include "lib/param/loadparm.h"
27
28 const char toupper_ascii_fast_table[128] = {
29         0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf,
30         0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
31         0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
32         0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
33         0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,
34         0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f,
35         0x60, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,
36         0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f
37 };
38
39 /**
40  * Compare 2 strings up to and including the nth char.
41  *
42  * @note The comparison is case-insensitive.
43  **/
44 bool strnequal(const char *s1,const char *s2,size_t n)
45 {
46         if (s1 == s2)
47                 return(true);
48         if (!s1 || !s2 || !n)
49                 return(false);
50
51         return(strncasecmp_m(s1,s2,n)==0);
52 }
53
54 /**
55  Convert a string to "normal" form.
56 **/
57
58 bool strnorm(char *s, int case_default)
59 {
60         if (case_default == CASE_UPPER)
61                 return strupper_m(s);
62         else
63                 strlower_m(s);
64         return true; /* FIXME - return strlower_m value later. */
65 }
66
67 /**
68  *  Skip past some strings in a buffer - old version - no checks.
69  *  **/
70
71 char *push_skip_string(char *buf)
72 {
73         buf += strlen(buf) + 1;
74         return(buf);
75 }
76
77 /**
78  Skip past a string in a buffer. Buffer may not be
79  null terminated. end_ptr points to the first byte after
80  then end of the buffer.
81 **/
82
83 char *skip_string(const char *base, size_t len, char *buf)
84 {
85         const char *end_ptr = base + len;
86
87         if (end_ptr < base || !base || !buf || buf >= end_ptr) {
88                 return NULL;
89         }
90
91         /* Skip the string */
92         while (*buf) {
93                 buf++;
94                 if (buf >= end_ptr) {
95                         return NULL;
96                 }
97         }
98         /* Skip the '\0' */
99         buf++;
100         return buf;
101 }
102
103 /**
104  Count the number of characters in a string. Normally this will
105  be the same as the number of bytes in a string for single byte strings,
106  but will be different for multibyte.
107 **/
108
109 size_t str_charnum(const char *s)
110 {
111         size_t ret, converted_size;
112         smb_ucs2_t *tmpbuf2 = NULL;
113         if (!push_ucs2_talloc(talloc_tos(), &tmpbuf2, s, &converted_size)) {
114                 return 0;
115         }
116         ret = strlen_w(tmpbuf2);
117         TALLOC_FREE(tmpbuf2);
118         return ret;
119 }
120
121 bool trim_char(char *s,char cfront,char cback)
122 {
123         bool ret = false;
124         char *ep;
125         char *fp = s;
126
127         /* Ignore null or empty strings. */
128         if (!s || (s[0] == '\0'))
129                 return false;
130
131         if (cfront) {
132                 while (*fp && *fp == cfront)
133                         fp++;
134                 if (!*fp) {
135                         /* We ate the string. */
136                         s[0] = '\0';
137                         return true;
138                 }
139                 if (fp != s)
140                         ret = true;
141         }
142
143         ep = fp + strlen(fp) - 1;
144         if (cback) {
145                 /* Attempt ascii only. Bail for mb strings. */
146                 while ((ep >= fp) && (*ep == cback)) {
147                         ret = true;
148                         if ((ep > fp) && (((unsigned char)ep[-1]) & 0x80)) {
149                                 /* Could be mb... bail back to tim_string. */
150                                 char fs[2], bs[2];
151                                 if (cfront) {
152                                         fs[0] = cfront;
153                                         fs[1] = '\0';
154                                 }
155                                 bs[0] = cback;
156                                 bs[1] = '\0';
157                                 return trim_string(s, cfront ? fs : NULL, bs);
158                         } else {
159                                 ep--;
160                         }
161                 }
162                 if (ep < fp) {
163                         /* We ate the string. */
164                         s[0] = '\0';
165                         return true;
166                 }
167         }
168
169         ep[1] = '\0';
170         memmove(s, fp, ep-fp+2);
171         return ret;
172 }
173
174 /**
175  Like strncpy but always null terminates. Make sure there is room!
176  The variable n should always be one less than the available size.
177 **/
178 char *StrnCpy(char *dest,const char *src,size_t n)
179 {
180         char *d = dest;
181
182         if (!dest) {
183                 smb_panic("ERROR: NULL dest in StrnCpy");
184         }
185
186         if (!src) {
187                 *dest = 0;
188                 return(dest);
189         }
190
191         while (n-- && (*d = *src)) {
192                 d++;
193                 src++;
194         }
195
196         *d = 0;
197         return(dest);
198 }
199
200 /**
201  Check if a string is part of a list.
202 **/
203
204 bool in_list(const char *s, const char *list, bool casesensitive)
205 {
206         char *tok = NULL;
207         bool ret = false;
208         TALLOC_CTX *frame;
209
210         if (!list) {
211                 return false;
212         }
213
214         frame = talloc_stackframe();
215         while (next_token_talloc(frame, &list, &tok,LIST_SEP)) {
216                 if (casesensitive) {
217                         if (strcmp(tok,s) == 0) {
218                                 ret = true;
219                                 break;
220                         }
221                 } else {
222                         if (strcasecmp_m(tok,s) == 0) {
223                                 ret = true;
224                                 break;
225                         }
226                 }
227         }
228         TALLOC_FREE(frame);
229         return ret;
230 }
231
232 /*
233  * Internal guts of talloc_string_sub and talloc_all_string_sub.
234  * talloc version of string_sub2.
235  */
236
237 char *talloc_string_sub2(TALLOC_CTX *mem_ctx, const char *src,
238                         const char *pattern,
239                         const char *insert,
240                         bool remove_unsafe_characters,
241                         bool replace_once,
242                         bool allow_trailing_dollar)
243 {
244         char *p, *in;
245         char *s;
246         char *string;
247         ssize_t ls,lp,li,ld, i;
248
249         if (!insert || !pattern || !*pattern || !src) {
250                 return NULL;
251         }
252
253         string = talloc_strdup(mem_ctx, src);
254         if (string == NULL) {
255                 DEBUG(0, ("talloc_string_sub2: "
256                         "talloc_strdup failed\n"));
257                 return NULL;
258         }
259
260         s = string;
261
262         in = talloc_strdup(mem_ctx, insert);
263         if (!in) {
264                 DEBUG(0, ("talloc_string_sub2: ENOMEM\n"));
265                 return NULL;
266         }
267         ls = (ssize_t)strlen(s);
268         lp = (ssize_t)strlen(pattern);
269         li = (ssize_t)strlen(insert);
270         ld = li - lp;
271
272         for (i=0;i<li;i++) {
273                 switch (in[i]) {
274                         case '$':
275                                 /* allow a trailing $
276                                  * (as in machine accounts) */
277                                 if (allow_trailing_dollar && (i == li - 1 )) {
278                                         break;
279                                 }
280                         case '`':
281                         case '"':
282                         case '\'':
283                         case ';':
284                         case '%':
285                         case '\r':
286                         case '\n':
287                                 if (remove_unsafe_characters) {
288                                         in[i] = '_';
289                                         break;
290                                 }
291                         default:
292                                 /* ok */
293                                 break;
294                 }
295         }
296
297         while ((p = strstr_m(s,pattern))) {
298                 if (ld > 0) {
299                         int offset = PTR_DIFF(s,string);
300                         string = (char *)TALLOC_REALLOC(mem_ctx, string,
301                                                         ls + ld + 1);
302                         if (!string) {
303                                 DEBUG(0, ("talloc_string_sub: out of "
304                                           "memory!\n"));
305                                 TALLOC_FREE(in);
306                                 return NULL;
307                         }
308                         p = string + offset + (p - s);
309                 }
310                 if (li != lp) {
311                         memmove(p+li,p+lp,strlen(p+lp)+1);
312                 }
313                 memcpy(p, in, li);
314                 s = p + li;
315                 ls += ld;
316
317                 if (replace_once) {
318                         break;
319                 }
320         }
321         TALLOC_FREE(in);
322         return string;
323 }
324
325 /* Same as string_sub, but returns a talloc'ed string */
326
327 char *talloc_string_sub(TALLOC_CTX *mem_ctx,
328                         const char *src,
329                         const char *pattern,
330                         const char *insert)
331 {
332         return talloc_string_sub2(mem_ctx, src, pattern, insert,
333                         true, false, false);
334 }
335
336 char *talloc_all_string_sub(TALLOC_CTX *ctx,
337                                 const char *src,
338                                 const char *pattern,
339                                 const char *insert)
340 {
341         return talloc_string_sub2(ctx, src, pattern, insert,
342                         false, false, false);
343 }
344
345 /**
346  Write an octal as a string.
347 **/
348
349 char *octal_string(int i)
350 {
351         char *result;
352         if (i == -1) {
353                 result = talloc_strdup(talloc_tos(), "-1");
354         }
355         else {
356                 result = talloc_asprintf(talloc_tos(), "0%o", i);
357         }
358         SMB_ASSERT(result != NULL);
359         return result;
360 }
361
362
363 /**
364  Truncate a string at a specified length.
365 **/
366
367 char *string_truncate(char *s, unsigned int length)
368 {
369         if (s && strlen(s) > length)
370                 s[length] = 0;
371         return s;
372 }
373
374
375 /***********************************************************************
376  Return the equivalent of doing strrchr 'n' times - always going
377  backwards.
378 ***********************************************************************/
379
380 char *strnrchr_m(const char *s, char c, unsigned int n)
381 {
382         smb_ucs2_t *ws = NULL;
383         char *s2 = NULL;
384         smb_ucs2_t *p;
385         char *ret;
386         size_t converted_size;
387
388         if (!push_ucs2_talloc(talloc_tos(), &ws, s, &converted_size)) {
389                 /* Too hard to try and get right. */
390                 return NULL;
391         }
392         p = strnrchr_w(ws, UCS2_CHAR(c), n);
393         if (!p) {
394                 TALLOC_FREE(ws);
395                 return NULL;
396         }
397         *p = 0;
398         if (!pull_ucs2_talloc(talloc_tos(), &s2, ws, &converted_size)) {
399                 TALLOC_FREE(ws);
400                 /* Too hard to try and get right. */
401                 return NULL;
402         }
403         ret = discard_const_p(char, (s+strlen(s2)));
404         TALLOC_FREE(ws);
405         TALLOC_FREE(s2);
406         return ret;
407 }
408
409 static bool unix_strlower(const char *src, size_t srclen, char *dest, size_t destlen)
410 {
411         size_t size;
412         smb_ucs2_t *buffer = NULL;
413         bool ret;
414
415         if (!convert_string_talloc(talloc_tos(), CH_UNIX, CH_UTF16LE, src, srclen,
416                                    (void **)(void *)&buffer, &size))
417         {
418                 smb_panic("failed to create UCS2 buffer");
419                 /* NOTREACHED. Yet. */
420                 return false;
421         }
422         if (!strlower_w(buffer) && (dest == src)) {
423                 TALLOC_FREE(buffer);
424                 return true;
425         }
426         ret = convert_string(CH_UTF16LE, CH_UNIX, buffer, size, dest, destlen, &size);
427         TALLOC_FREE(buffer);
428         return ret;
429 }
430
431 #if 0 /* Alternate function that avoid talloc calls for ASCII and non ASCII */
432
433 /**
434  Convert a string to lower case.
435 **/
436 _PUBLIC_ void strlower_m(char *s)
437 {
438         char *d;
439         struct smb_iconv_handle *iconv_handle;
440
441         iconv_handle = get_iconv_handle();
442
443         d = s;
444
445         while (*s) {
446                 size_t c_size, c_size2;
447                 codepoint_t c = next_codepoint_handle(iconv_handle, s, &c_size);
448                 c_size2 = push_codepoint_handle(iconv_handle, d, tolower_m(c));
449                 if (c_size2 > c_size) {
450                         DEBUG(0,("FATAL: codepoint 0x%x (0x%x) expanded from %d to %d bytes in strlower_m\n",
451                                  c, tolower_m(c), (int)c_size, (int)c_size2));
452                         smb_panic("codepoint expansion in strlower_m\n");
453                 }
454                 s += c_size;
455                 d += c_size2;
456         }
457         *d = 0;
458 }
459
460 #endif
461
462 /**
463  Convert a string to lower case.
464 **/
465
466 bool strlower_m(char *s)
467 {
468         size_t len;
469         int errno_save;
470         bool ret = false;
471
472         /* this is quite a common operation, so we want it to be
473            fast. We optimise for the ascii case, knowing that all our
474            supported multi-byte character sets are ascii-compatible
475            (ie. they match for the first 128 chars) */
476
477         while (*s && !(((unsigned char)s[0]) & 0x80)) {
478                 *s = tolower_m((unsigned char)*s);
479                 s++;
480         }
481
482         if (!*s)
483                 return true;
484
485         /* I assume that lowercased string takes the same number of bytes
486          * as source string even in UTF-8 encoding. (VIV) */
487         len = strlen(s) + 1;
488         errno_save = errno;
489         errno = 0;
490         ret = unix_strlower(s,len,s,len);
491         /* Catch mb conversion errors that may not terminate. */
492         if (errno) {
493                 s[len-1] = '\0';
494                 ret = false;
495         }
496         errno = errno_save;
497         return ret;
498 }
499
500 static bool unix_strupper(const char *src, size_t srclen, char *dest, size_t destlen)
501 {
502         size_t size;
503         smb_ucs2_t *buffer;
504         bool ret;
505
506         if (!push_ucs2_talloc(talloc_tos(), &buffer, src, &size)) {
507                 return false;
508         }
509
510         if (!strupper_w(buffer) && (dest == src)) {
511                 TALLOC_FREE(buffer);
512                 return true;
513         }
514
515         ret = convert_string(CH_UTF16LE, CH_UNIX, buffer, size, dest, destlen, &size);
516         TALLOC_FREE(buffer);
517         return ret;
518 }
519
520 #if 0 /* Alternate function that avoid talloc calls for ASCII and non ASCII */
521
522 /**
523  Convert a string to UPPER case.
524 **/
525 _PUBLIC_ void strupper_m(char *s)
526 {
527         char *d;
528         struct smb_iconv_handle *iconv_handle;
529
530         iconv_handle = get_iconv_handle();
531
532         d = s;
533
534         while (*s) {
535                 size_t c_size, c_size2;
536                 codepoint_t c = next_codepoint_handle(iconv_handle, s, &c_size);
537                 c_size2 = push_codepoint_handle(iconv_handle, d, toupper_m(c));
538                 if (c_size2 > c_size) {
539                         DEBUG(0,("FATAL: codepoint 0x%x (0x%x) expanded from %d to %d bytes in strupper_m\n",
540                                  c, toupper_m(c), (int)c_size, (int)c_size2));
541                         smb_panic("codepoint expansion in strupper_m\n");
542                 }
543                 s += c_size;
544                 d += c_size2;
545         }
546         *d = 0;
547 }
548
549 #endif
550
551 /**
552  Convert a string to upper case.
553 **/
554
555 bool strupper_m(char *s)
556 {
557         size_t len;
558         int errno_save;
559         bool ret = false;
560
561         /* this is quite a common operation, so we want it to be
562            fast. We optimise for the ascii case, knowing that all our
563            supported multi-byte character sets are ascii-compatible
564            (ie. they match for the first 128 chars) */
565
566         while (*s && !(((unsigned char)s[0]) & 0x80)) {
567                 *s = toupper_ascii_fast((unsigned char)*s);
568                 s++;
569         }
570
571         if (!*s)
572                 return true;
573
574         /* I assume that lowercased string takes the same number of bytes
575          * as source string even in multibyte encoding. (VIV) */
576         len = strlen(s) + 1;
577         errno_save = errno;
578         errno = 0;
579         ret = unix_strupper(s,len,s,len);
580         /* Catch mb conversion errors that may not terminate. */
581         if (errno) {
582                 s[len-1] = '\0';
583         }
584         errno = errno_save;
585         return ret;
586 }
587
588 /**
589  Just a typesafety wrapper for snprintf into a fstring.
590 **/
591
592 int fstr_sprintf(fstring s, const char *fmt, ...)
593 {
594         va_list ap;
595         int ret;
596
597         va_start(ap, fmt);
598         ret = vsnprintf(s, FSTRING_LEN, fmt, ap);
599         va_end(ap);
600         return ret;
601 }
602
603 /**
604  List of Strings manipulation functions
605 **/
606
607 #define S_LIST_ABS 16 /* List Allocation Block Size */
608
609 /******************************************************************************
610  substitute a specific pattern in a string list
611  *****************************************************************************/
612
613 bool str_list_substitute(char **list, const char *pattern, const char *insert)
614 {
615         TALLOC_CTX *ctx = list;
616         char *p, *s, *t;
617         ssize_t ls, lp, li, ld, i, d;
618
619         if (!list)
620                 return false;
621         if (!pattern)
622                 return false;
623         if (!insert)
624                 return false;
625
626         lp = (ssize_t)strlen(pattern);
627         li = (ssize_t)strlen(insert);
628         ld = li -lp;
629
630         while (*list) {
631                 s = *list;
632                 ls = (ssize_t)strlen(s);
633
634                 while ((p = strstr_m(s, pattern))) {
635                         t = *list;
636                         d = p -t;
637                         if (ld) {
638                                 t = talloc_array(ctx, char, ls +ld +1);
639                                 if (!t) {
640                                         DEBUG(0,("str_list_substitute: "
641                                                 "Unable to allocate memory"));
642                                         return false;
643                                 }
644                                 memcpy(t, *list, d);
645                                 memcpy(t +d +li, p +lp, ls -d -lp +1);
646                                 TALLOC_FREE(*list);
647                                 *list = t;
648                                 ls += ld;
649                                 s = t +d +li;
650                         }
651
652                         for (i = 0; i < li; i++) {
653                                 switch (insert[i]) {
654                                         case '`':
655                                         case '"':
656                                         case '\'':
657                                         case ';':
658                                         case '$':
659                                         case '%':
660                                         case '\r':
661                                         case '\n':
662                                                 t[d +i] = '_';
663                                                 break;
664                                         default:
665                                                 t[d +i] = insert[i];
666                                 }
667                         }
668                 }
669
670                 list++;
671         }
672
673         return true;
674 }
675
676
677 #define IPSTR_LIST_SEP  ","
678 #define IPSTR_LIST_CHAR ','
679
680 /**
681  * Add ip string representation to ipstr list. Used also
682  * as part of @function ipstr_list_make
683  *
684  * @param ipstr_list pointer to string containing ip list;
685  *        MUST BE already allocated and IS reallocated if necessary
686  * @param ipstr_size pointer to current size of ipstr_list (might be changed
687  *        as a result of reallocation)
688  * @param ip IP address which is to be added to list
689  * @return pointer to string appended with new ip and possibly
690  *         reallocated to new length
691  **/
692
693 static char *ipstr_list_add(char **ipstr_list, const struct ip_service *service)
694 {
695         char *new_ipstr = NULL;
696         char addr_buf[INET6_ADDRSTRLEN];
697         int ret;
698
699         /* arguments checking */
700         if (!ipstr_list || !service) {
701                 return NULL;
702         }
703
704         print_sockaddr(addr_buf,
705                         sizeof(addr_buf),
706                         &service->ss);
707
708         /* attempt to convert ip to a string and append colon separator to it */
709         if (*ipstr_list) {
710                 if (service->ss.ss_family == AF_INET) {
711                         /* IPv4 */
712                         ret = asprintf(&new_ipstr, "%s%s%s:%d", *ipstr_list,
713                                        IPSTR_LIST_SEP, addr_buf,
714                                        service->port);
715                 } else {
716                         /* IPv6 */
717                         ret = asprintf(&new_ipstr, "%s%s[%s]:%d", *ipstr_list,
718                                        IPSTR_LIST_SEP, addr_buf,
719                                        service->port);
720                 }
721                 SAFE_FREE(*ipstr_list);
722         } else {
723                 if (service->ss.ss_family == AF_INET) {
724                         /* IPv4 */
725                         ret = asprintf(&new_ipstr, "%s:%d", addr_buf,
726                                        service->port);
727                 } else {
728                         /* IPv6 */
729                         ret = asprintf(&new_ipstr, "[%s]:%d", addr_buf,
730                                        service->port);
731                 }
732         }
733         if (ret == -1) {
734                 return NULL;
735         }
736         *ipstr_list = new_ipstr;
737         return *ipstr_list;
738 }
739
740 /**
741  * Allocate and initialise an ipstr list using ip adresses
742  * passed as arguments.
743  *
744  * @param ipstr_list pointer to string meant to be allocated and set
745  * @param ip_list array of ip addresses to place in the list
746  * @param ip_count number of addresses stored in ip_list
747  * @return pointer to allocated ip string
748  **/
749
750 char *ipstr_list_make(char **ipstr_list,
751                         const struct ip_service *ip_list,
752                         int ip_count)
753 {
754         int i;
755
756         /* arguments checking */
757         if (!ip_list || !ipstr_list) {
758                 return 0;
759         }
760
761         *ipstr_list = NULL;
762
763         /* process ip addresses given as arguments */
764         for (i = 0; i < ip_count; i++) {
765                 *ipstr_list = ipstr_list_add(ipstr_list, &ip_list[i]);
766         }
767
768         return (*ipstr_list);
769 }
770
771
772 /**
773  * Parse given ip string list into array of ip addresses
774  * (as ip_service structures)
775  *    e.g. [IPv6]:port,192.168.1.100:389,192.168.1.78, ...
776  *
777  * @param ipstr ip string list to be parsed
778  * @param ip_list pointer to array of ip addresses which is
779  *        allocated by this function and must be freed by caller
780  * @return number of successfully parsed addresses
781  **/
782
783 int ipstr_list_parse(const char *ipstr_list, struct ip_service **ip_list)
784 {
785         TALLOC_CTX *frame;
786         char *token_str = NULL;
787         size_t count;
788         int i;
789
790         if (!ipstr_list || !ip_list)
791                 return 0;
792
793         count = count_chars(ipstr_list, IPSTR_LIST_CHAR) + 1;
794         if ( (*ip_list = SMB_MALLOC_ARRAY(struct ip_service, count)) == NULL ) {
795                 DEBUG(0,("ipstr_list_parse: malloc failed for %lu entries\n",
796                                         (unsigned long)count));
797                 return 0;
798         }
799
800         frame = talloc_stackframe();
801         for ( i=0; next_token_talloc(frame, &ipstr_list, &token_str,
802                                 IPSTR_LIST_SEP) && i<count; i++ ) {
803                 char *s = token_str;
804                 char *p = strrchr(token_str, ':');
805
806                 if (p) {
807                         *p = 0;
808                         (*ip_list)[i].port = atoi(p+1);
809                 }
810
811                 /* convert single token to ip address */
812                 if (token_str[0] == '[') {
813                         /* IPv6 address. */
814                         s++;
815                         p = strchr(token_str, ']');
816                         if (!p) {
817                                 continue;
818                         }
819                         *p = '\0';
820                 }
821                 if (!interpret_string_addr(&(*ip_list)[i].ss,
822                                         s,
823                                         AI_NUMERICHOST)) {
824                         continue;
825                 }
826         }
827         TALLOC_FREE(frame);
828         return count;
829 }
830
831 /**
832  * Safely free ip string list
833  *
834  * @param ipstr_list ip string list to be freed
835  **/
836
837 void ipstr_list_free(char* ipstr_list)
838 {
839         SAFE_FREE(ipstr_list);
840 }
841
842 /* read a SMB_BIG_UINT from a string */
843 uint64_t STR_TO_SMB_BIG_UINT(const char *nptr, const char **entptr)
844 {
845
846         uint64_t val = (uint64_t)-1;
847         const char *p = nptr;
848
849         if (!p) {
850                 if (entptr) {
851                         *entptr = p;
852                 }
853                 return val;
854         }
855
856         while (*p && isspace(*p))
857                 p++;
858
859         sscanf(p,"%"PRIu64,&val);
860         if (entptr) {
861                 while (*p && isdigit(*p))
862                         p++;
863                 *entptr = p;
864         }
865
866         return val;
867 }
868
869 /* Convert a size specification to a count of bytes. We accept the following
870  * suffixes:
871  *          bytes if there is no suffix
872  *      kK  kibibytes
873  *      mM  mebibytes
874  *      gG  gibibytes
875  *      tT  tibibytes
876  *      pP  whatever the ISO name for petabytes is
877  *
878  *  Returns 0 if the string can't be converted.
879  */
880 uint64_t conv_str_size(const char * str)
881 {
882         uint64_t lval;
883         char * end;
884
885         if (str == NULL || *str == '\0') {
886                 return 0;
887         }
888
889         lval = strtoull(str, &end, 10 /* base */);
890
891         if (end == NULL || end == str) {
892                 return 0;
893         }
894
895         if (*end == '\0') {
896                 return lval;
897         }
898
899         if (strwicmp(end, "K") == 0) {
900                 lval *= 1024ULL;
901         } else if (strwicmp(end, "M") == 0) {
902                 lval *= (1024ULL * 1024ULL);
903         } else if (strwicmp(end, "G") == 0) {
904                 lval *= (1024ULL * 1024ULL *
905                          1024ULL);
906         } else if (strwicmp(end, "T") == 0) {
907                 lval *= (1024ULL * 1024ULL *
908                          1024ULL * 1024ULL);
909         } else if (strwicmp(end, "P") == 0) {
910                 lval *= (1024ULL * 1024ULL *
911                          1024ULL * 1024ULL *
912                          1024ULL);
913         } else {
914                 return 0;
915         }
916
917         return lval;
918 }
919
920 /* Append an sprintf'ed string. Double buffer size on demand. Usable without
921  * error checking in between. The indiation that something weird happened is
922  * string==NULL */
923
924 void sprintf_append(TALLOC_CTX *mem_ctx, char **string, ssize_t *len,
925                     size_t *bufsize, const char *fmt, ...)
926 {
927         va_list ap;
928         char *newstr;
929         int ret;
930         bool increased;
931
932         /* len<0 is an internal marker that something failed */
933         if (*len < 0)
934                 goto error;
935
936         if (*string == NULL) {
937                 if (*bufsize == 0)
938                         *bufsize = 128;
939
940                 *string = talloc_array(mem_ctx, char, *bufsize);
941                 if (*string == NULL)
942                         goto error;
943         }
944
945         va_start(ap, fmt);
946         ret = vasprintf(&newstr, fmt, ap);
947         va_end(ap);
948
949         if (ret < 0)
950                 goto error;
951
952         increased = false;
953
954         while ((*len)+ret >= *bufsize) {
955                 increased = true;
956                 *bufsize *= 2;
957                 if (*bufsize >= (1024*1024*256))
958                         goto error;
959         }
960
961         if (increased) {
962                 *string = talloc_realloc(mem_ctx, *string, char,
963                                                *bufsize);
964                 if (*string == NULL) {
965                         goto error;
966                 }
967         }
968
969         StrnCpy((*string)+(*len), newstr, ret);
970         (*len) += ret;
971         free(newstr);
972         return;
973
974  error:
975         *len = -1;
976         *string = NULL;
977 }
978
979 /*
980  * asprintf into a string and strupper_m it after that.
981  */
982
983 int asprintf_strupper_m(char **strp, const char *fmt, ...)
984 {
985         va_list ap;
986         char *result;
987         int ret;
988
989         va_start(ap, fmt);
990         ret = vasprintf(&result, fmt, ap);
991         va_end(ap);
992
993         if (ret == -1)
994                 return -1;
995
996         if (!strupper_m(result)) {
997                 SAFE_FREE(result);
998                 return -1;
999         }
1000
1001         *strp = result;
1002         return ret;
1003 }
1004
1005 char *talloc_asprintf_strupper_m(TALLOC_CTX *t, const char *fmt, ...)
1006 {
1007         va_list ap;
1008         char *ret;
1009
1010         va_start(ap, fmt);
1011         ret = talloc_vasprintf(t, fmt, ap);
1012         va_end(ap);
1013
1014         if (ret == NULL) {
1015                 return NULL;
1016         }
1017         if (!strupper_m(ret)) {
1018                 TALLOC_FREE(ret);
1019                 return NULL;
1020         }
1021         return ret;
1022 }
1023
1024 char *talloc_asprintf_strlower_m(TALLOC_CTX *t, const char *fmt, ...)
1025 {
1026         va_list ap;
1027         char *ret;
1028
1029         va_start(ap, fmt);
1030         ret = talloc_vasprintf(t, fmt, ap);
1031         va_end(ap);
1032
1033         if (ret == NULL) {
1034                 return NULL;
1035         }
1036         strlower_m(ret);
1037         return ret;
1038 }
1039
1040
1041 /********************************************************************
1042  Check a string for any occurrences of a specified list of invalid
1043  characters.
1044 ********************************************************************/
1045
1046 bool validate_net_name( const char *name,
1047                 const char *invalid_chars,
1048                 int max_len)
1049 {
1050         int i;
1051
1052         if (!name) {
1053                 return false;
1054         }
1055
1056         for ( i=0; i<max_len && name[i]; i++ ) {
1057                 /* fail if strchr_m() finds one of the invalid characters */
1058                 if ( name[i] && strchr_m( invalid_chars, name[i] ) ) {
1059                         return false;
1060                 }
1061         }
1062
1063         return true;
1064 }
1065
1066
1067 /*******************************************************************
1068  Add a shell escape character '\' to any character not in a known list
1069  of characters. UNIX charset format.
1070 *******************************************************************/
1071
1072 #define INCLUDE_LIST "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_/ \t.,"
1073 #define INSIDE_DQUOTE_LIST "$`\n\"\\"
1074
1075 char *escape_shell_string(const char *src)
1076 {
1077         size_t srclen = strlen(src);
1078         char *ret = SMB_MALLOC_ARRAY(char, (srclen * 2) + 1);
1079         char *dest = ret;
1080         bool in_s_quote = false;
1081         bool in_d_quote = false;
1082         bool next_escaped = false;
1083
1084         if (!ret) {
1085                 return NULL;
1086         }
1087
1088         while (*src) {
1089                 size_t c_size;
1090                 codepoint_t c = next_codepoint(src, &c_size);
1091
1092                 if (c == INVALID_CODEPOINT) {
1093                         SAFE_FREE(ret);
1094                         return NULL;
1095                 }
1096
1097                 if (c_size > 1) {
1098                         memcpy(dest, src, c_size);
1099                         src += c_size;
1100                         dest += c_size;
1101                         next_escaped = false;
1102                         continue;
1103                 }
1104
1105                 /*
1106                  * Deal with backslash escaped state.
1107                  * This only lasts for one character.
1108                  */
1109
1110                 if (next_escaped) {
1111                         *dest++ = *src++;
1112                         next_escaped = false;
1113                         continue;
1114                 }
1115
1116                 /*
1117                  * Deal with single quote state. The
1118                  * only thing we care about is exiting
1119                  * this state.
1120                  */
1121
1122                 if (in_s_quote) {
1123                         if (*src == '\'') {
1124                                 in_s_quote = false;
1125                         }
1126                         *dest++ = *src++;
1127                         continue;
1128                 }
1129
1130                 /*
1131                  * Deal with double quote state. The most
1132                  * complex state. We must cope with \, meaning
1133                  * possibly escape next char (depending what it
1134                  * is), ", meaning exit this state, and possibly
1135                  * add an \ escape to any unprotected character
1136                  * (listed in INSIDE_DQUOTE_LIST).
1137                  */
1138
1139                 if (in_d_quote) {
1140                         if (*src == '\\') {
1141                                 /*
1142                                  * Next character might be escaped.
1143                                  * We have to peek. Inside double
1144                                  * quotes only INSIDE_DQUOTE_LIST
1145                                  * characters are escaped by a \.
1146                                  */
1147
1148                                 char nextchar;
1149
1150                                 c = next_codepoint(&src[1], &c_size);
1151                                 if (c == INVALID_CODEPOINT) {
1152                                         SAFE_FREE(ret);
1153                                         return NULL;
1154                                 }
1155                                 if (c_size > 1) {
1156                                         /*
1157                                          * Don't escape the next char.
1158                                          * Just copy the \.
1159                                          */
1160                                         *dest++ = *src++;
1161                                         continue;
1162                                 }
1163
1164                                 nextchar = src[1];
1165
1166                                 if (nextchar && strchr(INSIDE_DQUOTE_LIST,
1167                                                         (int)nextchar)) {
1168                                         next_escaped = true;
1169                                 }
1170                                 *dest++ = *src++;
1171                                 continue;
1172                         }
1173
1174                         if (*src == '\"') {
1175                                 /* Exit double quote state. */
1176                                 in_d_quote = false;
1177                                 *dest++ = *src++;
1178                                 continue;
1179                         }
1180
1181                         /*
1182                          * We know the character isn't \ or ",
1183                          * so escape it if it's any of the other
1184                          * possible unprotected characters.
1185                          */
1186
1187                         if (strchr(INSIDE_DQUOTE_LIST, (int)*src)) {
1188                                 *dest++ = '\\';
1189                         }
1190                         *dest++ = *src++;
1191                         continue;
1192                 }
1193
1194                 /*
1195                  * From here to the end of the loop we're
1196                  * not in the single or double quote state.
1197                  */
1198
1199                 if (*src == '\\') {
1200                         /* Next character must be escaped. */
1201                         next_escaped = true;
1202                         *dest++ = *src++;
1203                         continue;
1204                 }
1205
1206                 if (*src == '\'') {
1207                         /* Go into single quote state. */
1208                         in_s_quote = true;
1209                         *dest++ = *src++;
1210                         continue;
1211                 }
1212
1213                 if (*src == '\"') {
1214                         /* Go into double quote state. */
1215                         in_d_quote = true;
1216                         *dest++ = *src++;
1217                         continue;
1218                 }
1219
1220                 /* Check if we need to escape the character. */
1221
1222                 if (!strchr(INCLUDE_LIST, (int)*src)) {
1223                         *dest++ = '\\';
1224                 }
1225                 *dest++ = *src++;
1226         }
1227         *dest++ = '\0';
1228         return ret;
1229 }
1230
1231 /***************************************************
1232  str_list_make, v3 version. The v4 version does not
1233  look at quoted strings with embedded blanks, so
1234  do NOT merge this function please!
1235 ***************************************************/
1236
1237 #define S_LIST_ABS 16 /* List Allocation Block Size */
1238
1239 char **str_list_make_v3(TALLOC_CTX *mem_ctx, const char *string,
1240         const char *sep)
1241 {
1242         char **list;
1243         const char *str;
1244         char *s, *tok;
1245         int num, lsize;
1246
1247         if (!string || !*string)
1248                 return NULL;
1249
1250         list = talloc_array(mem_ctx, char *, S_LIST_ABS+1);
1251         if (list == NULL) {
1252                 return NULL;
1253         }
1254         lsize = S_LIST_ABS;
1255
1256         s = talloc_strdup(list, string);
1257         if (s == NULL) {
1258                 DEBUG(0,("str_list_make: Unable to allocate memory"));
1259                 TALLOC_FREE(list);
1260                 return NULL;
1261         }
1262         if (!sep) sep = LIST_SEP;
1263
1264         num = 0;
1265         str = s;
1266
1267         while (next_token_talloc(list, &str, &tok, sep)) {
1268
1269                 if (num == lsize) {
1270                         char **tmp;
1271
1272                         lsize += S_LIST_ABS;
1273
1274                         tmp = talloc_realloc(mem_ctx, list, char *,
1275                                                    lsize + 1);
1276                         if (tmp == NULL) {
1277                                 DEBUG(0,("str_list_make: "
1278                                         "Unable to allocate memory"));
1279                                 TALLOC_FREE(list);
1280                                 return NULL;
1281                         }
1282
1283                         list = tmp;
1284
1285                         memset (&list[num], 0,
1286                                 ((sizeof(char**)) * (S_LIST_ABS +1)));
1287                 }
1288
1289                 list[num] = tok;
1290                 num += 1;
1291         }
1292
1293         list[num] = NULL;
1294
1295         TALLOC_FREE(s);
1296         return list;
1297 }