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