Check error returns on strnorm().
[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 void strlower_m(char *s)
467 {
468         size_t len;
469         int errno_save;
470
471         /* this is quite a common operation, so we want it to be
472            fast. We optimise for the ascii case, knowing that all our
473            supported multi-byte character sets are ascii-compatible
474            (ie. they match for the first 128 chars) */
475
476         while (*s && !(((unsigned char)s[0]) & 0x80)) {
477                 *s = tolower_m((unsigned char)*s);
478                 s++;
479         }
480
481         if (!*s)
482                 return;
483
484         /* I assume that lowercased string takes the same number of bytes
485          * as source string even in UTF-8 encoding. (VIV) */
486         len = strlen(s) + 1;
487         errno_save = errno;
488         errno = 0;
489         unix_strlower(s,len,s,len);
490         /* Catch mb conversion errors that may not terminate. */
491         if (errno)
492                 s[len-1] = '\0';
493         errno = errno_save;
494 }
495
496 static bool unix_strupper(const char *src, size_t srclen, char *dest, size_t destlen)
497 {
498         size_t size;
499         smb_ucs2_t *buffer;
500         bool ret;
501
502         if (!push_ucs2_talloc(talloc_tos(), &buffer, src, &size)) {
503                 return false;
504         }
505
506         if (!strupper_w(buffer) && (dest == src)) {
507                 TALLOC_FREE(buffer);
508                 return true;
509         }
510
511         ret = convert_string(CH_UTF16LE, CH_UNIX, buffer, size, dest, destlen, &size);
512         TALLOC_FREE(buffer);
513         return ret;
514 }
515
516 #if 0 /* Alternate function that avoid talloc calls for ASCII and non ASCII */
517
518 /**
519  Convert a string to UPPER case.
520 **/
521 _PUBLIC_ void strupper_m(char *s)
522 {
523         char *d;
524         struct smb_iconv_handle *iconv_handle;
525
526         iconv_handle = get_iconv_handle();
527
528         d = s;
529
530         while (*s) {
531                 size_t c_size, c_size2;
532                 codepoint_t c = next_codepoint_handle(iconv_handle, s, &c_size);
533                 c_size2 = push_codepoint_handle(iconv_handle, d, toupper_m(c));
534                 if (c_size2 > c_size) {
535                         DEBUG(0,("FATAL: codepoint 0x%x (0x%x) expanded from %d to %d bytes in strupper_m\n",
536                                  c, toupper_m(c), (int)c_size, (int)c_size2));
537                         smb_panic("codepoint expansion in strupper_m\n");
538                 }
539                 s += c_size;
540                 d += c_size2;
541         }
542         *d = 0;
543 }
544
545 #endif
546
547 /**
548  Convert a string to upper case.
549 **/
550
551 bool strupper_m(char *s)
552 {
553         size_t len;
554         int errno_save;
555         bool ret = false;
556
557         /* this is quite a common operation, so we want it to be
558            fast. We optimise for the ascii case, knowing that all our
559            supported multi-byte character sets are ascii-compatible
560            (ie. they match for the first 128 chars) */
561
562         while (*s && !(((unsigned char)s[0]) & 0x80)) {
563                 *s = toupper_ascii_fast((unsigned char)*s);
564                 s++;
565         }
566
567         if (!*s)
568                 return true;
569
570         /* I assume that lowercased string takes the same number of bytes
571          * as source string even in multibyte encoding. (VIV) */
572         len = strlen(s) + 1;
573         errno_save = errno;
574         errno = 0;
575         ret = unix_strupper(s,len,s,len);
576         /* Catch mb conversion errors that may not terminate. */
577         if (errno) {
578                 s[len-1] = '\0';
579         }
580         errno = errno_save;
581         return ret;
582 }
583
584 /**
585  Just a typesafety wrapper for snprintf into a fstring.
586 **/
587
588 int fstr_sprintf(fstring s, const char *fmt, ...)
589 {
590         va_list ap;
591         int ret;
592
593         va_start(ap, fmt);
594         ret = vsnprintf(s, FSTRING_LEN, fmt, ap);
595         va_end(ap);
596         return ret;
597 }
598
599 /**
600  List of Strings manipulation functions
601 **/
602
603 #define S_LIST_ABS 16 /* List Allocation Block Size */
604
605 /******************************************************************************
606  substitute a specific pattern in a string list
607  *****************************************************************************/
608
609 bool str_list_substitute(char **list, const char *pattern, const char *insert)
610 {
611         TALLOC_CTX *ctx = list;
612         char *p, *s, *t;
613         ssize_t ls, lp, li, ld, i, d;
614
615         if (!list)
616                 return false;
617         if (!pattern)
618                 return false;
619         if (!insert)
620                 return false;
621
622         lp = (ssize_t)strlen(pattern);
623         li = (ssize_t)strlen(insert);
624         ld = li -lp;
625
626         while (*list) {
627                 s = *list;
628                 ls = (ssize_t)strlen(s);
629
630                 while ((p = strstr_m(s, pattern))) {
631                         t = *list;
632                         d = p -t;
633                         if (ld) {
634                                 t = talloc_array(ctx, char, ls +ld +1);
635                                 if (!t) {
636                                         DEBUG(0,("str_list_substitute: "
637                                                 "Unable to allocate memory"));
638                                         return false;
639                                 }
640                                 memcpy(t, *list, d);
641                                 memcpy(t +d +li, p +lp, ls -d -lp +1);
642                                 TALLOC_FREE(*list);
643                                 *list = t;
644                                 ls += ld;
645                                 s = t +d +li;
646                         }
647
648                         for (i = 0; i < li; i++) {
649                                 switch (insert[i]) {
650                                         case '`':
651                                         case '"':
652                                         case '\'':
653                                         case ';':
654                                         case '$':
655                                         case '%':
656                                         case '\r':
657                                         case '\n':
658                                                 t[d +i] = '_';
659                                                 break;
660                                         default:
661                                                 t[d +i] = insert[i];
662                                 }
663                         }
664                 }
665
666                 list++;
667         }
668
669         return true;
670 }
671
672
673 #define IPSTR_LIST_SEP  ","
674 #define IPSTR_LIST_CHAR ','
675
676 /**
677  * Add ip string representation to ipstr list. Used also
678  * as part of @function ipstr_list_make
679  *
680  * @param ipstr_list pointer to string containing ip list;
681  *        MUST BE already allocated and IS reallocated if necessary
682  * @param ipstr_size pointer to current size of ipstr_list (might be changed
683  *        as a result of reallocation)
684  * @param ip IP address which is to be added to list
685  * @return pointer to string appended with new ip and possibly
686  *         reallocated to new length
687  **/
688
689 static char *ipstr_list_add(char **ipstr_list, const struct ip_service *service)
690 {
691         char *new_ipstr = NULL;
692         char addr_buf[INET6_ADDRSTRLEN];
693         int ret;
694
695         /* arguments checking */
696         if (!ipstr_list || !service) {
697                 return NULL;
698         }
699
700         print_sockaddr(addr_buf,
701                         sizeof(addr_buf),
702                         &service->ss);
703
704         /* attempt to convert ip to a string and append colon separator to it */
705         if (*ipstr_list) {
706                 if (service->ss.ss_family == AF_INET) {
707                         /* IPv4 */
708                         ret = asprintf(&new_ipstr, "%s%s%s:%d", *ipstr_list,
709                                        IPSTR_LIST_SEP, addr_buf,
710                                        service->port);
711                 } else {
712                         /* IPv6 */
713                         ret = asprintf(&new_ipstr, "%s%s[%s]:%d", *ipstr_list,
714                                        IPSTR_LIST_SEP, addr_buf,
715                                        service->port);
716                 }
717                 SAFE_FREE(*ipstr_list);
718         } else {
719                 if (service->ss.ss_family == AF_INET) {
720                         /* IPv4 */
721                         ret = asprintf(&new_ipstr, "%s:%d", addr_buf,
722                                        service->port);
723                 } else {
724                         /* IPv6 */
725                         ret = asprintf(&new_ipstr, "[%s]:%d", addr_buf,
726                                        service->port);
727                 }
728         }
729         if (ret == -1) {
730                 return NULL;
731         }
732         *ipstr_list = new_ipstr;
733         return *ipstr_list;
734 }
735
736 /**
737  * Allocate and initialise an ipstr list using ip adresses
738  * passed as arguments.
739  *
740  * @param ipstr_list pointer to string meant to be allocated and set
741  * @param ip_list array of ip addresses to place in the list
742  * @param ip_count number of addresses stored in ip_list
743  * @return pointer to allocated ip string
744  **/
745
746 char *ipstr_list_make(char **ipstr_list,
747                         const struct ip_service *ip_list,
748                         int ip_count)
749 {
750         int i;
751
752         /* arguments checking */
753         if (!ip_list || !ipstr_list) {
754                 return 0;
755         }
756
757         *ipstr_list = NULL;
758
759         /* process ip addresses given as arguments */
760         for (i = 0; i < ip_count; i++) {
761                 *ipstr_list = ipstr_list_add(ipstr_list, &ip_list[i]);
762         }
763
764         return (*ipstr_list);
765 }
766
767
768 /**
769  * Parse given ip string list into array of ip addresses
770  * (as ip_service structures)
771  *    e.g. [IPv6]:port,192.168.1.100:389,192.168.1.78, ...
772  *
773  * @param ipstr ip string list to be parsed
774  * @param ip_list pointer to array of ip addresses which is
775  *        allocated by this function and must be freed by caller
776  * @return number of successfully parsed addresses
777  **/
778
779 int ipstr_list_parse(const char *ipstr_list, struct ip_service **ip_list)
780 {
781         TALLOC_CTX *frame;
782         char *token_str = NULL;
783         size_t count;
784         int i;
785
786         if (!ipstr_list || !ip_list)
787                 return 0;
788
789         count = count_chars(ipstr_list, IPSTR_LIST_CHAR) + 1;
790         if ( (*ip_list = SMB_MALLOC_ARRAY(struct ip_service, count)) == NULL ) {
791                 DEBUG(0,("ipstr_list_parse: malloc failed for %lu entries\n",
792                                         (unsigned long)count));
793                 return 0;
794         }
795
796         frame = talloc_stackframe();
797         for ( i=0; next_token_talloc(frame, &ipstr_list, &token_str,
798                                 IPSTR_LIST_SEP) && i<count; i++ ) {
799                 char *s = token_str;
800                 char *p = strrchr(token_str, ':');
801
802                 if (p) {
803                         *p = 0;
804                         (*ip_list)[i].port = atoi(p+1);
805                 }
806
807                 /* convert single token to ip address */
808                 if (token_str[0] == '[') {
809                         /* IPv6 address. */
810                         s++;
811                         p = strchr(token_str, ']');
812                         if (!p) {
813                                 continue;
814                         }
815                         *p = '\0';
816                 }
817                 if (!interpret_string_addr(&(*ip_list)[i].ss,
818                                         s,
819                                         AI_NUMERICHOST)) {
820                         continue;
821                 }
822         }
823         TALLOC_FREE(frame);
824         return count;
825 }
826
827 /**
828  * Safely free ip string list
829  *
830  * @param ipstr_list ip string list to be freed
831  **/
832
833 void ipstr_list_free(char* ipstr_list)
834 {
835         SAFE_FREE(ipstr_list);
836 }
837
838 /* read a SMB_BIG_UINT from a string */
839 uint64_t STR_TO_SMB_BIG_UINT(const char *nptr, const char **entptr)
840 {
841
842         uint64_t val = (uint64_t)-1;
843         const char *p = nptr;
844
845         if (!p) {
846                 if (entptr) {
847                         *entptr = p;
848                 }
849                 return val;
850         }
851
852         while (*p && isspace(*p))
853                 p++;
854
855         sscanf(p,"%"PRIu64,&val);
856         if (entptr) {
857                 while (*p && isdigit(*p))
858                         p++;
859                 *entptr = p;
860         }
861
862         return val;
863 }
864
865 /* Convert a size specification to a count of bytes. We accept the following
866  * suffixes:
867  *          bytes if there is no suffix
868  *      kK  kibibytes
869  *      mM  mebibytes
870  *      gG  gibibytes
871  *      tT  tibibytes
872  *      pP  whatever the ISO name for petabytes is
873  *
874  *  Returns 0 if the string can't be converted.
875  */
876 uint64_t conv_str_size(const char * str)
877 {
878         uint64_t lval;
879         char * end;
880
881         if (str == NULL || *str == '\0') {
882                 return 0;
883         }
884
885         lval = strtoull(str, &end, 10 /* base */);
886
887         if (end == NULL || end == str) {
888                 return 0;
889         }
890
891         if (*end == '\0') {
892                 return lval;
893         }
894
895         if (strwicmp(end, "K") == 0) {
896                 lval *= 1024ULL;
897         } else if (strwicmp(end, "M") == 0) {
898                 lval *= (1024ULL * 1024ULL);
899         } else if (strwicmp(end, "G") == 0) {
900                 lval *= (1024ULL * 1024ULL *
901                          1024ULL);
902         } else if (strwicmp(end, "T") == 0) {
903                 lval *= (1024ULL * 1024ULL *
904                          1024ULL * 1024ULL);
905         } else if (strwicmp(end, "P") == 0) {
906                 lval *= (1024ULL * 1024ULL *
907                          1024ULL * 1024ULL *
908                          1024ULL);
909         } else {
910                 return 0;
911         }
912
913         return lval;
914 }
915
916 /* Append an sprintf'ed string. Double buffer size on demand. Usable without
917  * error checking in between. The indiation that something weird happened is
918  * string==NULL */
919
920 void sprintf_append(TALLOC_CTX *mem_ctx, char **string, ssize_t *len,
921                     size_t *bufsize, const char *fmt, ...)
922 {
923         va_list ap;
924         char *newstr;
925         int ret;
926         bool increased;
927
928         /* len<0 is an internal marker that something failed */
929         if (*len < 0)
930                 goto error;
931
932         if (*string == NULL) {
933                 if (*bufsize == 0)
934                         *bufsize = 128;
935
936                 *string = talloc_array(mem_ctx, char, *bufsize);
937                 if (*string == NULL)
938                         goto error;
939         }
940
941         va_start(ap, fmt);
942         ret = vasprintf(&newstr, fmt, ap);
943         va_end(ap);
944
945         if (ret < 0)
946                 goto error;
947
948         increased = false;
949
950         while ((*len)+ret >= *bufsize) {
951                 increased = true;
952                 *bufsize *= 2;
953                 if (*bufsize >= (1024*1024*256))
954                         goto error;
955         }
956
957         if (increased) {
958                 *string = talloc_realloc(mem_ctx, *string, char,
959                                                *bufsize);
960                 if (*string == NULL) {
961                         goto error;
962                 }
963         }
964
965         StrnCpy((*string)+(*len), newstr, ret);
966         (*len) += ret;
967         free(newstr);
968         return;
969
970  error:
971         *len = -1;
972         *string = NULL;
973 }
974
975 /*
976  * asprintf into a string and strupper_m it after that.
977  */
978
979 int asprintf_strupper_m(char **strp, const char *fmt, ...)
980 {
981         va_list ap;
982         char *result;
983         int ret;
984
985         va_start(ap, fmt);
986         ret = vasprintf(&result, fmt, ap);
987         va_end(ap);
988
989         if (ret == -1)
990                 return -1;
991
992         if (!strupper_m(result)) {
993                 SAFE_FREE(result);
994                 return -1;
995         }
996
997         *strp = result;
998         return ret;
999 }
1000
1001 char *talloc_asprintf_strupper_m(TALLOC_CTX *t, const char *fmt, ...)
1002 {
1003         va_list ap;
1004         char *ret;
1005
1006         va_start(ap, fmt);
1007         ret = talloc_vasprintf(t, fmt, ap);
1008         va_end(ap);
1009
1010         if (ret == NULL) {
1011                 return NULL;
1012         }
1013         if (!strupper_m(ret)) {
1014                 TALLOC_FREE(ret);
1015                 return NULL;
1016         }
1017         return ret;
1018 }
1019
1020 char *talloc_asprintf_strlower_m(TALLOC_CTX *t, const char *fmt, ...)
1021 {
1022         va_list ap;
1023         char *ret;
1024
1025         va_start(ap, fmt);
1026         ret = talloc_vasprintf(t, fmt, ap);
1027         va_end(ap);
1028
1029         if (ret == NULL) {
1030                 return NULL;
1031         }
1032         strlower_m(ret);
1033         return ret;
1034 }
1035
1036
1037 /********************************************************************
1038  Check a string for any occurrences of a specified list of invalid
1039  characters.
1040 ********************************************************************/
1041
1042 bool validate_net_name( const char *name,
1043                 const char *invalid_chars,
1044                 int max_len)
1045 {
1046         int i;
1047
1048         if (!name) {
1049                 return false;
1050         }
1051
1052         for ( i=0; i<max_len && name[i]; i++ ) {
1053                 /* fail if strchr_m() finds one of the invalid characters */
1054                 if ( name[i] && strchr_m( invalid_chars, name[i] ) ) {
1055                         return false;
1056                 }
1057         }
1058
1059         return true;
1060 }
1061
1062
1063 /*******************************************************************
1064  Add a shell escape character '\' to any character not in a known list
1065  of characters. UNIX charset format.
1066 *******************************************************************/
1067
1068 #define INCLUDE_LIST "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_/ \t.,"
1069 #define INSIDE_DQUOTE_LIST "$`\n\"\\"
1070
1071 char *escape_shell_string(const char *src)
1072 {
1073         size_t srclen = strlen(src);
1074         char *ret = SMB_MALLOC_ARRAY(char, (srclen * 2) + 1);
1075         char *dest = ret;
1076         bool in_s_quote = false;
1077         bool in_d_quote = false;
1078         bool next_escaped = false;
1079
1080         if (!ret) {
1081                 return NULL;
1082         }
1083
1084         while (*src) {
1085                 size_t c_size;
1086                 codepoint_t c = next_codepoint(src, &c_size);
1087
1088                 if (c == INVALID_CODEPOINT) {
1089                         SAFE_FREE(ret);
1090                         return NULL;
1091                 }
1092
1093                 if (c_size > 1) {
1094                         memcpy(dest, src, c_size);
1095                         src += c_size;
1096                         dest += c_size;
1097                         next_escaped = false;
1098                         continue;
1099                 }
1100
1101                 /*
1102                  * Deal with backslash escaped state.
1103                  * This only lasts for one character.
1104                  */
1105
1106                 if (next_escaped) {
1107                         *dest++ = *src++;
1108                         next_escaped = false;
1109                         continue;
1110                 }
1111
1112                 /*
1113                  * Deal with single quote state. The
1114                  * only thing we care about is exiting
1115                  * this state.
1116                  */
1117
1118                 if (in_s_quote) {
1119                         if (*src == '\'') {
1120                                 in_s_quote = false;
1121                         }
1122                         *dest++ = *src++;
1123                         continue;
1124                 }
1125
1126                 /*
1127                  * Deal with double quote state. The most
1128                  * complex state. We must cope with \, meaning
1129                  * possibly escape next char (depending what it
1130                  * is), ", meaning exit this state, and possibly
1131                  * add an \ escape to any unprotected character
1132                  * (listed in INSIDE_DQUOTE_LIST).
1133                  */
1134
1135                 if (in_d_quote) {
1136                         if (*src == '\\') {
1137                                 /*
1138                                  * Next character might be escaped.
1139                                  * We have to peek. Inside double
1140                                  * quotes only INSIDE_DQUOTE_LIST
1141                                  * characters are escaped by a \.
1142                                  */
1143
1144                                 char nextchar;
1145
1146                                 c = next_codepoint(&src[1], &c_size);
1147                                 if (c == INVALID_CODEPOINT) {
1148                                         SAFE_FREE(ret);
1149                                         return NULL;
1150                                 }
1151                                 if (c_size > 1) {
1152                                         /*
1153                                          * Don't escape the next char.
1154                                          * Just copy the \.
1155                                          */
1156                                         *dest++ = *src++;
1157                                         continue;
1158                                 }
1159
1160                                 nextchar = src[1];
1161
1162                                 if (nextchar && strchr(INSIDE_DQUOTE_LIST,
1163                                                         (int)nextchar)) {
1164                                         next_escaped = true;
1165                                 }
1166                                 *dest++ = *src++;
1167                                 continue;
1168                         }
1169
1170                         if (*src == '\"') {
1171                                 /* Exit double quote state. */
1172                                 in_d_quote = false;
1173                                 *dest++ = *src++;
1174                                 continue;
1175                         }
1176
1177                         /*
1178                          * We know the character isn't \ or ",
1179                          * so escape it if it's any of the other
1180                          * possible unprotected characters.
1181                          */
1182
1183                         if (strchr(INSIDE_DQUOTE_LIST, (int)*src)) {
1184                                 *dest++ = '\\';
1185                         }
1186                         *dest++ = *src++;
1187                         continue;
1188                 }
1189
1190                 /*
1191                  * From here to the end of the loop we're
1192                  * not in the single or double quote state.
1193                  */
1194
1195                 if (*src == '\\') {
1196                         /* Next character must be escaped. */
1197                         next_escaped = true;
1198                         *dest++ = *src++;
1199                         continue;
1200                 }
1201
1202                 if (*src == '\'') {
1203                         /* Go into single quote state. */
1204                         in_s_quote = true;
1205                         *dest++ = *src++;
1206                         continue;
1207                 }
1208
1209                 if (*src == '\"') {
1210                         /* Go into double quote state. */
1211                         in_d_quote = true;
1212                         *dest++ = *src++;
1213                         continue;
1214                 }
1215
1216                 /* Check if we need to escape the character. */
1217
1218                 if (!strchr(INCLUDE_LIST, (int)*src)) {
1219                         *dest++ = '\\';
1220                 }
1221                 *dest++ = *src++;
1222         }
1223         *dest++ = '\0';
1224         return ret;
1225 }
1226
1227 /***************************************************
1228  str_list_make, v3 version. The v4 version does not
1229  look at quoted strings with embedded blanks, so
1230  do NOT merge this function please!
1231 ***************************************************/
1232
1233 #define S_LIST_ABS 16 /* List Allocation Block Size */
1234
1235 char **str_list_make_v3(TALLOC_CTX *mem_ctx, const char *string,
1236         const char *sep)
1237 {
1238         char **list;
1239         const char *str;
1240         char *s, *tok;
1241         int num, lsize;
1242
1243         if (!string || !*string)
1244                 return NULL;
1245
1246         list = talloc_array(mem_ctx, char *, S_LIST_ABS+1);
1247         if (list == NULL) {
1248                 return NULL;
1249         }
1250         lsize = S_LIST_ABS;
1251
1252         s = talloc_strdup(list, string);
1253         if (s == NULL) {
1254                 DEBUG(0,("str_list_make: Unable to allocate memory"));
1255                 TALLOC_FREE(list);
1256                 return NULL;
1257         }
1258         if (!sep) sep = LIST_SEP;
1259
1260         num = 0;
1261         str = s;
1262
1263         while (next_token_talloc(list, &str, &tok, sep)) {
1264
1265                 if (num == lsize) {
1266                         char **tmp;
1267
1268                         lsize += S_LIST_ABS;
1269
1270                         tmp = talloc_realloc(mem_ctx, list, char *,
1271                                                    lsize + 1);
1272                         if (tmp == NULL) {
1273                                 DEBUG(0,("str_list_make: "
1274                                         "Unable to allocate memory"));
1275                                 TALLOC_FREE(list);
1276                                 return NULL;
1277                         }
1278
1279                         list = tmp;
1280
1281                         memset (&list[num], 0,
1282                                 ((sizeof(char**)) * (S_LIST_ABS +1)));
1283                 }
1284
1285                 list[num] = tok;
1286                 num += 1;
1287         }
1288
1289         list[num] = NULL;
1290
1291         TALLOC_FREE(s);
1292         return list;
1293 }