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