133bd0dfb0b42658a06d6386a85daa6a2811e3fc
[kai/samba.git] / lib / util / util.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Samba utility functions
4    Copyright (C) Andrew Tridgell 1992-1998
5    Copyright (C) Jeremy Allison 2001-2002
6    Copyright (C) Simo Sorce 2001-2011
7    Copyright (C) Jim McDonough (jmcd@us.ibm.com)  2003.
8    Copyright (C) James J Myers 2003
9    Copyright (C) Volker Lendecke 2010
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 "system/network.h"
27 #include "system/filesys.h"
28 #include "system/locale.h"
29 #include "system/shmem.h"
30
31 #undef malloc
32 #undef strcasecmp
33 #undef strncasecmp
34 #undef strdup
35 #undef realloc
36
37 #if defined(UID_WRAPPER)
38 #if !defined(UID_WRAPPER_REPLACE) && !defined(UID_WRAPPER_NOT_REPLACE)
39 #define UID_WRAPPER_REPLACE
40 #include "../uid_wrapper/uid_wrapper.h"
41 #endif
42 #else
43 #define uwrap_enabled() 0
44 #endif
45
46 /**
47  * @file
48  * @brief Misc utility functions
49  */
50
51 /**
52  Find a suitable temporary directory. The result should be copied immediately
53  as it may be overwritten by a subsequent call.
54 **/
55 _PUBLIC_ const char *tmpdir(void)
56 {
57         char *p;
58         if ((p = getenv("TMPDIR")))
59                 return p;
60         return "/tmp";
61 }
62
63
64 /**
65  Create a tmp file, open it and immediately unlink it.
66  If dir is NULL uses tmpdir()
67  Returns the file descriptor or -1 on error.
68 **/
69 int create_unlink_tmp(const char *dir)
70 {
71         char *fname;
72         int fd;
73
74         if (!dir) {
75                 dir = tmpdir();
76         }
77
78         fname = talloc_asprintf(talloc_tos(), "%s/listenerlock_XXXXXX", dir);
79         if (fname == NULL) {
80                 errno = ENOMEM;
81                 return -1;
82         }
83         fd = mkstemp(fname);
84         if (fd == -1) {
85                 TALLOC_FREE(fname);
86                 return -1;
87         }
88         if (unlink(fname) == -1) {
89                 int sys_errno = errno;
90                 close(fd);
91                 TALLOC_FREE(fname);
92                 errno = sys_errno;
93                 return -1;
94         }
95         TALLOC_FREE(fname);
96         return fd;
97 }
98
99
100 /**
101  Check if a file exists - call vfs_file_exist for samba files.
102 **/
103 _PUBLIC_ bool file_exist(const char *fname)
104 {
105         struct stat st;
106
107         if (stat(fname, &st) != 0) {
108                 return false;
109         }
110
111         return ((S_ISREG(st.st_mode)) || (S_ISFIFO(st.st_mode)));
112 }
113
114 /**
115  Check a files mod time.
116 **/
117
118 _PUBLIC_ time_t file_modtime(const char *fname)
119 {
120         struct stat st;
121   
122         if (stat(fname,&st) != 0) 
123                 return(0);
124
125         return(st.st_mtime);
126 }
127
128 /**
129  Check if a directory exists.
130 **/
131
132 _PUBLIC_ bool directory_exist(const char *dname)
133 {
134         struct stat st;
135         bool ret;
136
137         if (stat(dname,&st) != 0) {
138                 return false;
139         }
140
141         ret = S_ISDIR(st.st_mode);
142         if(!ret)
143                 errno = ENOTDIR;
144         return ret;
145 }
146
147 /**
148  * Try to create the specified directory if it didn't exist.
149  *
150  * @retval true if the directory already existed and has the right permissions 
151  * or was successfully created.
152  */
153 _PUBLIC_ bool directory_create_or_exist(const char *dname, uid_t uid, 
154                                mode_t dir_perms)
155 {
156         mode_t old_umask;
157         struct stat st;
158       
159         old_umask = umask(0);
160         if (lstat(dname, &st) == -1) {
161                 if (errno == ENOENT) {
162                         /* Create directory */
163                         if (mkdir(dname, dir_perms) == -1) {
164                                 DEBUG(0, ("error creating directory "
165                                           "%s: %s\n", dname, 
166                                           strerror(errno)));
167                                 umask(old_umask);
168                                 return false;
169                         }
170                 } else {
171                         DEBUG(0, ("lstat failed on directory %s: %s\n",
172                                   dname, strerror(errno)));
173                         umask(old_umask);
174                         return false;
175                 }
176         } else {
177                 /* Check ownership and permission on existing directory */
178                 if (!S_ISDIR(st.st_mode)) {
179                         DEBUG(0, ("directory %s isn't a directory\n",
180                                 dname));
181                         umask(old_umask);
182                         return false;
183                 }
184                 if (st.st_uid != uid && !uwrap_enabled()) {
185                         DEBUG(0, ("invalid ownership on directory "
186                                   "%s\n", dname));
187                         umask(old_umask);
188                         return false;
189                 }
190                 if ((st.st_mode & 0777) != dir_perms) {
191                         DEBUG(0, ("invalid permissions on directory "
192                                   "'%s': has 0%o should be 0%o\n", dname,
193                                   (st.st_mode & 0777), dir_perms));
194                         umask(old_umask);
195                         return false;
196                 }
197         }
198         return true;
199 }       
200
201
202 /**
203  Sleep for a specified number of milliseconds.
204 **/
205
206 _PUBLIC_ void smb_msleep(unsigned int t)
207 {
208 #if defined(HAVE_NANOSLEEP)
209         struct timespec ts;
210         int ret;
211
212         ts.tv_sec = t/1000;
213         ts.tv_nsec = 1000000*(t%1000);
214
215         do {
216                 errno = 0;
217                 ret = nanosleep(&ts, &ts);
218         } while (ret < 0 && errno == EINTR && (ts.tv_sec > 0 || ts.tv_nsec > 0));
219 #else
220         unsigned int tdiff=0;
221         struct timeval tval,t1,t2;
222         fd_set fds;
223
224         GetTimeOfDay(&t1);
225         t2 = t1;
226
227         while (tdiff < t) {
228                 tval.tv_sec = (t-tdiff)/1000;
229                 tval.tv_usec = 1000*((t-tdiff)%1000);
230
231                 /* Never wait for more than 1 sec. */
232                 if (tval.tv_sec > 1) {
233                         tval.tv_sec = 1;
234                         tval.tv_usec = 0;
235                 }
236
237                 FD_ZERO(&fds);
238                 errno = 0;
239                 select(0,&fds,NULL,NULL,&tval);
240
241                 GetTimeOfDay(&t2);
242                 if (t2.tv_sec < t1.tv_sec) {
243                         /* Someone adjusted time... */
244                         t1 = t2;
245                 }
246
247                 tdiff = usec_time_diff(&t2,&t1)/1000;
248         }
249 #endif
250 }
251
252 /**
253  Get my own name, return in talloc'ed storage.
254 **/
255
256 _PUBLIC_ char *get_myname(TALLOC_CTX *ctx)
257 {
258         char *p;
259         char hostname[HOST_NAME_MAX];
260
261         /* get my host name */
262         if (gethostname(hostname, sizeof(hostname)) == -1) {
263                 DEBUG(0,("gethostname failed\n"));
264                 return NULL;
265         }
266
267         /* Ensure null termination. */
268         hostname[sizeof(hostname)-1] = '\0';
269
270         /* split off any parts after an initial . */
271         p = strchr_m(hostname, '.');
272         if (p) {
273                 *p = 0;
274         }
275
276         return talloc_strdup(ctx, hostname);
277 }
278
279 /**
280  Check if a process exists. Does this work on all unixes?
281 **/
282
283 _PUBLIC_ bool process_exists_by_pid(pid_t pid)
284 {
285         /* Doing kill with a non-positive pid causes messages to be
286          * sent to places we don't want. */
287         SMB_ASSERT(pid > 0);
288         return(kill(pid,0) == 0 || errno != ESRCH);
289 }
290
291 /**
292  Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
293  is dealt with in posix.c
294 **/
295
296 _PUBLIC_ bool fcntl_lock(int fd, int op, off_t offset, off_t count, int type)
297 {
298         struct flock lock;
299         int ret;
300
301         DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
302
303         lock.l_type = type;
304         lock.l_whence = SEEK_SET;
305         lock.l_start = offset;
306         lock.l_len = count;
307         lock.l_pid = 0;
308
309         ret = fcntl(fd,op,&lock);
310
311         if (ret == -1 && errno != 0)
312                 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
313
314         /* a lock query */
315         if (op == F_GETLK) {
316                 if ((ret != -1) &&
317                                 (lock.l_type != F_UNLCK) && 
318                                 (lock.l_pid != 0) && 
319                                 (lock.l_pid != getpid())) {
320                         DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
321                         return true;
322                 }
323
324                 /* it must be not locked or locked by me */
325                 return false;
326         }
327
328         /* a lock set or unset */
329         if (ret == -1) {
330                 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
331                         (double)offset,(double)count,op,type,strerror(errno)));
332                 return false;
333         }
334
335         /* everything went OK */
336         DEBUG(8,("fcntl_lock: Lock call successful\n"));
337
338         return true;
339 }
340
341 static void debugadd_cb(const char *buf, void *private_data)
342 {
343         int *plevel = (int *)private_data;
344         DEBUGADD(*plevel, ("%s", buf));
345 }
346
347 void print_asc_cb(const uint8_t *buf, int len,
348                   void (*cb)(const char *buf, void *private_data),
349                   void *private_data)
350 {
351         int i;
352         char s[2];
353         s[1] = 0;
354
355         for (i=0; i<len; i++) {
356                 s[0] = isprint(buf[i]) ? buf[i] : '.';
357                 cb(s, private_data);
358         }
359 }
360
361 void print_asc(int level, const uint8_t *buf,int len)
362 {
363         print_asc_cb(buf, len, debugadd_cb, &level);
364 }
365
366 /**
367  * Write dump of binary data to a callback
368  */
369 void dump_data_cb(const uint8_t *buf, int len,
370                   bool omit_zero_bytes,
371                   void (*cb)(const char *buf, void *private_data),
372                   void *private_data)
373 {
374         int i=0;
375         static const uint8_t empty[16] = { 0, };
376         bool skipped = false;
377         char tmp[16];
378
379         if (len<=0) return;
380
381         for (i=0;i<len;) {
382
383                 if (i%16 == 0) {
384                         if ((omit_zero_bytes == true) &&
385                             (i > 0) &&
386                             (len > i+16) &&
387                             (memcmp(&buf[i], &empty, 16) == 0))
388                         {
389                                 i +=16;
390                                 continue;
391                         }
392
393                         if (i<len)  {
394                                 snprintf(tmp, sizeof(tmp), "[%04X] ", i);
395                                 cb(tmp, private_data);
396                         }
397                 }
398
399                 snprintf(tmp, sizeof(tmp), "%02X ", (int)buf[i]);
400                 cb(tmp, private_data);
401                 i++;
402                 if (i%8 == 0) {
403                         cb("  ", private_data);
404                 }
405                 if (i%16 == 0) {
406
407                         print_asc_cb(&buf[i-16], 8, cb, private_data);
408                         cb(" ", private_data);
409                         print_asc_cb(&buf[i-8], 8, cb, private_data);
410                         cb("\n", private_data);
411
412                         if ((omit_zero_bytes == true) &&
413                             (len > i+16) &&
414                             (memcmp(&buf[i], &empty, 16) == 0)) {
415                                 if (!skipped) {
416                                         cb("skipping zero buffer bytes\n",
417                                            private_data);
418                                         skipped = true;
419                                 }
420                         }
421                 }
422         }
423
424         if (i%16) {
425                 int n;
426                 n = 16 - (i%16);
427                 cb(" ", private_data);
428                 if (n>8) {
429                         cb(" ", private_data);
430                 }
431                 while (n--) {
432                         cb("   ", private_data);
433                 }
434                 n = MIN(8,i%16);
435                 print_asc_cb(&buf[i-(i%16)], n, cb, private_data);
436                 cb(" ", private_data);
437                 n = (i%16) - n;
438                 if (n>0) {
439                         print_asc_cb(&buf[i-n], n, cb, private_data);
440                 }
441                 cb("\n", private_data);
442         }
443
444 }
445
446 /**
447  * Write dump of binary data to the log file.
448  *
449  * The data is only written if the log level is at least level.
450  */
451 _PUBLIC_ void dump_data(int level, const uint8_t *buf, int len)
452 {
453         if (!DEBUGLVL(level)) {
454                 return;
455         }
456         dump_data_cb(buf, len, false, debugadd_cb, &level);
457 }
458
459 /**
460  * Write dump of binary data to the log file.
461  *
462  * The data is only written if the log level is at least level.
463  * 16 zero bytes in a row are omitted
464  */
465 _PUBLIC_ void dump_data_skip_zeros(int level, const uint8_t *buf, int len)
466 {
467         if (!DEBUGLVL(level)) {
468                 return;
469         }
470         dump_data_cb(buf, len, true, debugadd_cb, &level);
471 }
472
473
474 /**
475  malloc that aborts with smb_panic on fail or zero size.
476 **/
477
478 _PUBLIC_ void *smb_xmalloc(size_t size)
479 {
480         void *p;
481         if (size == 0)
482                 smb_panic("smb_xmalloc: called with zero size.\n");
483         if ((p = malloc(size)) == NULL)
484                 smb_panic("smb_xmalloc: malloc fail.\n");
485         return p;
486 }
487
488 /**
489  Memdup with smb_panic on fail.
490 **/
491
492 _PUBLIC_ void *smb_xmemdup(const void *p, size_t size)
493 {
494         void *p2;
495         p2 = smb_xmalloc(size);
496         memcpy(p2, p, size);
497         return p2;
498 }
499
500 /**
501  strdup that aborts on malloc fail.
502 **/
503
504 char *smb_xstrdup(const char *s)
505 {
506 #if defined(PARANOID_MALLOC_CHECKER)
507 #ifdef strdup
508 #undef strdup
509 #endif
510 #endif
511
512 #ifndef HAVE_STRDUP
513 #define strdup rep_strdup
514 #endif
515
516         char *s1 = strdup(s);
517 #if defined(PARANOID_MALLOC_CHECKER)
518 #ifdef strdup
519 #undef strdup
520 #endif
521 #define strdup(s) __ERROR_DONT_USE_STRDUP_DIRECTLY
522 #endif
523         if (!s1) {
524                 smb_panic("smb_xstrdup: malloc failed");
525         }
526         return s1;
527
528 }
529
530 /**
531  strndup that aborts on malloc fail.
532 **/
533
534 char *smb_xstrndup(const char *s, size_t n)
535 {
536 #if defined(PARANOID_MALLOC_CHECKER)
537 #ifdef strndup
538 #undef strndup
539 #endif
540 #endif
541
542 #if (defined(BROKEN_STRNDUP) || !defined(HAVE_STRNDUP))
543 #undef HAVE_STRNDUP
544 #define strndup rep_strndup
545 #endif
546
547         char *s1 = strndup(s, n);
548 #if defined(PARANOID_MALLOC_CHECKER)
549 #ifdef strndup
550 #undef strndup
551 #endif
552 #define strndup(s,n) __ERROR_DONT_USE_STRNDUP_DIRECTLY
553 #endif
554         if (!s1) {
555                 smb_panic("smb_xstrndup: malloc failed");
556         }
557         return s1;
558 }
559
560
561
562 /**
563  Like strdup but for memory.
564 **/
565
566 _PUBLIC_ void *memdup(const void *p, size_t size)
567 {
568         void *p2;
569         if (size == 0)
570                 return NULL;
571         p2 = malloc(size);
572         if (!p2)
573                 return NULL;
574         memcpy(p2, p, size);
575         return p2;
576 }
577
578 /**
579  * Write a password to the log file.
580  *
581  * @note Only actually does something if DEBUG_PASSWORD was defined during 
582  * compile-time.
583  */
584 _PUBLIC_ void dump_data_pw(const char *msg, const uint8_t * data, size_t len)
585 {
586 #ifdef DEBUG_PASSWORD
587         DEBUG(11, ("%s", msg));
588         if (data != NULL && len > 0)
589         {
590                 dump_data(11, data, len);
591         }
592 #endif
593 }
594
595
596 /**
597  * see if a range of memory is all zero. A NULL pointer is considered
598  * to be all zero 
599  */
600 _PUBLIC_ bool all_zero(const uint8_t *ptr, size_t size)
601 {
602         int i;
603         if (!ptr) return true;
604         for (i=0;i<size;i++) {
605                 if (ptr[i]) return false;
606         }
607         return true;
608 }
609
610 /**
611   realloc an array, checking for integer overflow in the array size
612 */
613 _PUBLIC_ void *realloc_array(void *ptr, size_t el_size, unsigned count, bool free_on_fail)
614 {
615 #define MAX_MALLOC_SIZE 0x7fffffff
616         if (count == 0 ||
617             count >= MAX_MALLOC_SIZE/el_size) {
618                 if (free_on_fail)
619                         SAFE_FREE(ptr);
620                 return NULL;
621         }
622         if (!ptr) {
623                 return malloc(el_size * count);
624         }
625         return realloc(ptr, el_size * count);
626 }
627
628 /****************************************************************************
629  Type-safe malloc.
630 ****************************************************************************/
631
632 void *malloc_array(size_t el_size, unsigned int count)
633 {
634         return realloc_array(NULL, el_size, count, false);
635 }
636
637 /**
638  Trim the specified elements off the front and back of a string.
639 **/
640 _PUBLIC_ bool trim_string(char *s, const char *front, const char *back)
641 {
642         bool ret = false;
643         size_t front_len;
644         size_t back_len;
645         size_t len;
646
647         /* Ignore null or empty strings. */
648         if (!s || (s[0] == '\0'))
649                 return false;
650
651         front_len       = front? strlen(front) : 0;
652         back_len        = back? strlen(back) : 0;
653
654         len = strlen(s);
655
656         if (front_len) {
657                 while (len && strncmp(s, front, front_len)==0) {
658                         /* Must use memmove here as src & dest can
659                          * easily overlap. Found by valgrind. JRA. */
660                         memmove(s, s+front_len, (len-front_len)+1);
661                         len -= front_len;
662                         ret=true;
663                 }
664         }
665         
666         if (back_len) {
667                 while ((len >= back_len) && strncmp(s+len-back_len,back,back_len)==0) {
668                         s[len-back_len]='\0';
669                         len -= back_len;
670                         ret=true;
671                 }
672         }
673         return ret;
674 }
675
676 /**
677  Find the number of 'c' chars in a string
678 **/
679 _PUBLIC_ _PURE_ size_t count_chars(const char *s, char c)
680 {
681         size_t count = 0;
682
683         while (*s) {
684                 if (*s == c) count++;
685                 s ++;
686         }
687
688         return count;
689 }
690
691 /**
692  * Routine to get hex characters and turn them into a byte array.
693  * the array can be variable length.
694  * -  "0xnn" or "0Xnn" is specially catered for.
695  * - The first non-hex-digit character (apart from possibly leading "0x"
696  *   finishes the conversion and skips the rest of the input.
697  * - A single hex-digit character at the end of the string is skipped.
698  *
699  * valid examples: "0A5D15"; "0x123456"
700  */
701 _PUBLIC_ size_t strhex_to_str(char *p, size_t p_len, const char *strhex, size_t strhex_len)
702 {
703         size_t i = 0;
704         size_t num_chars = 0;
705         uint8_t   lonybble, hinybble;
706         const char     *hexchars = "0123456789ABCDEF";
707         char           *p1 = NULL, *p2 = NULL;
708
709         /* skip leading 0x prefix */
710         if (strncasecmp(strhex, "0x", 2) == 0) {
711                 i += 2; /* skip two chars */
712         }
713
714         for (; i+1 < strhex_len && strhex[i] != 0 && strhex[i+1] != 0; i++) {
715                 p1 = strchr(hexchars, toupper((unsigned char)strhex[i]));
716                 if (p1 == NULL) {
717                         break;
718                 }
719
720                 i++; /* next hex digit */
721
722                 p2 = strchr(hexchars, toupper((unsigned char)strhex[i]));
723                 if (p2 == NULL) {
724                         break;
725                 }
726
727                 /* get the two nybbles */
728                 hinybble = PTR_DIFF(p1, hexchars);
729                 lonybble = PTR_DIFF(p2, hexchars);
730
731                 if (num_chars >= p_len) {
732                         break;
733                 }
734
735                 p[num_chars] = (hinybble << 4) | lonybble;
736                 num_chars++;
737
738                 p1 = NULL;
739                 p2 = NULL;
740         }
741         return num_chars;
742 }
743
744 /** 
745  * Parse a hex string and return a data blob. 
746  */
747 _PUBLIC_ _PURE_ DATA_BLOB strhex_to_data_blob(TALLOC_CTX *mem_ctx, const char *strhex) 
748 {
749         DATA_BLOB ret_blob = data_blob_talloc(mem_ctx, NULL, strlen(strhex)/2+1);
750
751         ret_blob.length = strhex_to_str((char *)ret_blob.data, ret_blob.length,
752                                         strhex,
753                                         strlen(strhex));
754
755         return ret_blob;
756 }
757
758
759 /**
760  * Routine to print a buffer as HEX digits, into an allocated string.
761  */
762 _PUBLIC_ void hex_encode(const unsigned char *buff_in, size_t len, char **out_hex_buffer)
763 {
764         int i;
765         char *hex_buffer;
766
767         *out_hex_buffer = malloc_array_p(char, (len*2)+1);
768         hex_buffer = *out_hex_buffer;
769
770         for (i = 0; i < len; i++)
771                 slprintf(&hex_buffer[i*2], 3, "%02X", buff_in[i]);
772 }
773
774 /**
775  * talloc version of hex_encode()
776  */
777 _PUBLIC_ char *hex_encode_talloc(TALLOC_CTX *mem_ctx, const unsigned char *buff_in, size_t len)
778 {
779         int i;
780         char *hex_buffer;
781
782         hex_buffer = talloc_array(mem_ctx, char, (len*2)+1);
783         if (!hex_buffer) {
784                 return NULL;
785         }
786
787         for (i = 0; i < len; i++)
788                 slprintf(&hex_buffer[i*2], 3, "%02X", buff_in[i]);
789
790         talloc_set_name_const(hex_buffer, hex_buffer);
791         return hex_buffer;
792 }
793
794 /**
795   varient of strcmp() that handles NULL ptrs
796 **/
797 _PUBLIC_ int strcmp_safe(const char *s1, const char *s2)
798 {
799         if (s1 == s2) {
800                 return 0;
801         }
802         if (s1 == NULL || s2 == NULL) {
803                 return s1?-1:1;
804         }
805         return strcmp(s1, s2);
806 }
807
808
809 /**
810 return the number of bytes occupied by a buffer in ASCII format
811 the result includes the null termination
812 limited by 'n' bytes
813 **/
814 _PUBLIC_ size_t ascii_len_n(const char *src, size_t n)
815 {
816         size_t len;
817
818         len = strnlen(src, n);
819         if (len+1 <= n) {
820                 len += 1;
821         }
822
823         return len;
824 }
825
826 /**
827  Set a boolean variable from the text value stored in the passed string.
828  Returns true in success, false if the passed string does not correctly 
829  represent a boolean.
830 **/
831
832 _PUBLIC_ bool set_boolean(const char *boolean_string, bool *boolean)
833 {
834         if (strwicmp(boolean_string, "yes") == 0 ||
835             strwicmp(boolean_string, "true") == 0 ||
836             strwicmp(boolean_string, "on") == 0 ||
837             strwicmp(boolean_string, "1") == 0) {
838                 *boolean = true;
839                 return true;
840         } else if (strwicmp(boolean_string, "no") == 0 ||
841                    strwicmp(boolean_string, "false") == 0 ||
842                    strwicmp(boolean_string, "off") == 0 ||
843                    strwicmp(boolean_string, "0") == 0) {
844                 *boolean = false;
845                 return true;
846         }
847         return false;
848 }
849
850 /**
851 return the number of bytes occupied by a buffer in CH_UTF16 format
852 the result includes the null termination
853 **/
854 _PUBLIC_ size_t utf16_len(const void *buf)
855 {
856         size_t len;
857
858         for (len = 0; SVAL(buf,len); len += 2) ;
859
860         return len + 2;
861 }
862
863 /**
864 return the number of bytes occupied by a buffer in CH_UTF16 format
865 the result includes the null termination
866 limited by 'n' bytes
867 **/
868 _PUBLIC_ size_t utf16_len_n(const void *src, size_t n)
869 {
870         size_t len;
871
872         for (len = 0; (len+2 < n) && SVAL(src, len); len += 2) ;
873
874         if (len+2 <= n) {
875                 len += 2;
876         }
877
878         return len;
879 }
880
881 /**
882  * @file
883  * @brief String utilities.
884  **/
885
886 static bool next_token_internal_talloc(TALLOC_CTX *ctx,
887                                 const char **ptr,
888                                 char **pp_buff,
889                                 const char *sep,
890                                 bool ltrim)
891 {
892         const char *s;
893         const char *saved_s;
894         char *pbuf;
895         bool quoted;
896         size_t len=1;
897
898         *pp_buff = NULL;
899         if (!ptr) {
900                 return(false);
901         }
902
903         s = *ptr;
904
905         /* default to simple separators */
906         if (!sep) {
907                 sep = " \t\n\r";
908         }
909
910         /* find the first non sep char, if left-trimming is requested */
911         if (ltrim) {
912                 while (*s && strchr_m(sep,*s)) {
913                         s++;
914                 }
915         }
916
917         /* nothing left? */
918         if (!*s) {
919                 return false;
920         }
921
922         /* When restarting we need to go from here. */
923         saved_s = s;
924
925         /* Work out the length needed. */
926         for (quoted = false; *s &&
927                         (quoted || !strchr_m(sep,*s)); s++) {
928                 if (*s == '\"') {
929                         quoted = !quoted;
930                 } else {
931                         len++;
932                 }
933         }
934
935         /* We started with len = 1 so we have space for the nul. */
936         *pp_buff = talloc_array(ctx, char, len);
937         if (!*pp_buff) {
938                 return false;
939         }
940
941         /* copy over the token */
942         pbuf = *pp_buff;
943         s = saved_s;
944         for (quoted = false; *s &&
945                         (quoted || !strchr_m(sep,*s)); s++) {
946                 if ( *s == '\"' ) {
947                         quoted = !quoted;
948                 } else {
949                         *pbuf++ = *s;
950                 }
951         }
952
953         *ptr = (*s) ? s+1 : s;
954         *pbuf = 0;
955
956         return true;
957 }
958
959 bool next_token_talloc(TALLOC_CTX *ctx,
960                         const char **ptr,
961                         char **pp_buff,
962                         const char *sep)
963 {
964         return next_token_internal_talloc(ctx, ptr, pp_buff, sep, true);
965 }
966
967 /*
968  * Get the next token from a string, return false if none found.  Handles
969  * double-quotes.  This version does not trim leading separator characters
970  * before looking for a token.
971  */
972
973 bool next_token_no_ltrim_talloc(TALLOC_CTX *ctx,
974                         const char **ptr,
975                         char **pp_buff,
976                         const char *sep)
977 {
978         return next_token_internal_talloc(ctx, ptr, pp_buff, sep, false);
979 }
980
981 /**
982  * Get the next token from a string, return False if none found.
983  * Handles double-quotes.
984  *
985  * Based on a routine by GJC@VILLAGE.COM.
986  * Extensively modified by Andrew.Tridgell@anu.edu.au
987  **/
988 _PUBLIC_ bool next_token(const char **ptr,char *buff, const char *sep, size_t bufsize)
989 {
990         const char *s;
991         bool quoted;
992         size_t len=1;
993
994         if (!ptr)
995                 return false;
996
997         s = *ptr;
998
999         /* default to simple separators */
1000         if (!sep)
1001                 sep = " \t\n\r";
1002
1003         /* find the first non sep char */
1004         while (*s && strchr_m(sep,*s))
1005                 s++;
1006
1007         /* nothing left? */
1008         if (!*s)
1009                 return false;
1010
1011         /* copy over the token */
1012         for (quoted = false; len < bufsize && *s && (quoted || !strchr_m(sep,*s)); s++) {
1013                 if (*s == '\"') {
1014                         quoted = !quoted;
1015                 } else {
1016                         len++;
1017                         *buff++ = *s;
1018                 }
1019         }
1020
1021         *ptr = (*s) ? s+1 : s;
1022         *buff = 0;
1023
1024         return true;
1025 }
1026
1027 struct anonymous_shared_header {
1028         union {
1029                 size_t length;
1030                 uint8_t pad[16];
1031         } u;
1032 };
1033
1034 /* Map a shared memory buffer of at least nelem counters. */
1035 void *anonymous_shared_allocate(size_t orig_bufsz)
1036 {
1037         void *ptr;
1038         void *buf;
1039         size_t pagesz = getpagesize();
1040         size_t pagecnt;
1041         size_t bufsz = orig_bufsz;
1042         struct anonymous_shared_header *hdr;
1043
1044         bufsz += sizeof(*hdr);
1045
1046         /* round up to full pages */
1047         pagecnt = bufsz / pagesz;
1048         if (bufsz % pagesz) {
1049                 pagecnt += 1;
1050         }
1051         bufsz = pagesz * pagecnt;
1052
1053         if (orig_bufsz >= bufsz) {
1054                 /* integer wrap */
1055                 errno = ENOMEM;
1056                 return NULL;
1057         }
1058
1059 #ifdef MAP_ANON
1060         /* BSD */
1061         buf = mmap(NULL, bufsz, PROT_READ|PROT_WRITE, MAP_ANON|MAP_SHARED,
1062                         -1 /* fd */, 0 /* offset */);
1063 #else
1064         buf = mmap(NULL, bufsz, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED,
1065                         open("/dev/zero", O_RDWR), 0 /* offset */);
1066 #endif
1067
1068         if (buf == MAP_FAILED) {
1069                 return NULL;
1070         }
1071
1072         hdr = (struct anonymous_shared_header *)buf;
1073         hdr->u.length = bufsz;
1074
1075         ptr = (void *)(&hdr[1]);
1076
1077         return ptr;
1078 }
1079
1080 void *anonymous_shared_resize(void *ptr, size_t new_size, bool maymove)
1081 {
1082 #ifdef HAVE_MREMAP
1083         void *buf;
1084         size_t pagesz = getpagesize();
1085         size_t pagecnt;
1086         size_t bufsz;
1087         struct anonymous_shared_header *hdr;
1088         int flags = 0;
1089
1090         if (ptr == NULL) {
1091                 errno = EINVAL;
1092                 return NULL;
1093         }
1094
1095         hdr = (struct anonymous_shared_header *)ptr;
1096         hdr--;
1097         if (hdr->u.length > (new_size + sizeof(*hdr))) {
1098                 errno = EINVAL;
1099                 return NULL;
1100         }
1101
1102         bufsz = new_size + sizeof(*hdr);
1103
1104         /* round up to full pages */
1105         pagecnt = bufsz / pagesz;
1106         if (bufsz % pagesz) {
1107                 pagecnt += 1;
1108         }
1109         bufsz = pagesz * pagecnt;
1110
1111         if (new_size >= bufsz) {
1112                 /* integer wrap */
1113                 errno = ENOSPC;
1114                 return NULL;
1115         }
1116
1117         if (bufsz <= hdr->u.length) {
1118                 return ptr;
1119         }
1120
1121         if (maymove) {
1122                 flags = MREMAP_MAYMOVE;
1123         }
1124
1125         buf = mremap(hdr, hdr->u.length, bufsz, flags);
1126
1127         if (buf == MAP_FAILED) {
1128                 errno = ENOSPC;
1129                 return NULL;
1130         }
1131
1132         hdr = (struct anonymous_shared_header *)buf;
1133         hdr->u.length = bufsz;
1134
1135         ptr = (void *)(&hdr[1]);
1136
1137         return ptr;
1138 #else
1139         errno = ENOSPC;
1140         return NULL;
1141 #endif
1142 }
1143
1144 void anonymous_shared_free(void *ptr)
1145 {
1146         struct anonymous_shared_header *hdr;
1147
1148         if (ptr == NULL) {
1149                 return;
1150         }
1151
1152         hdr = (struct anonymous_shared_header *)ptr;
1153
1154         hdr--;
1155
1156         munmap(hdr, hdr->u.length);
1157 }
1158
1159 #ifdef DEVELOPER
1160 /* used when you want a debugger started at a particular point in the
1161    code. Mostly useful in code that runs as a child process, where
1162    normal gdb attach is harder to organise.
1163 */
1164 void samba_start_debugger(void)
1165 {
1166         char *cmd = NULL;
1167         if (asprintf(&cmd, "xterm -e \"gdb --pid %u\"&", getpid()) == -1) {
1168                 return;
1169         }
1170         if (system(cmd) == -1) {
1171                 free(cmd);
1172                 return;
1173         }
1174         free(cmd);
1175         sleep(2);
1176 }
1177 #endif