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