lib-util: Make create_unlink_tmp argument optional
[sfrench/samba-autobuild/.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 16 byte array.
693  the array can be variable length, and any non-hex-numeric
694  characters are skipped.  "0xnn" or "0Xnn" is specially catered
695  for.
696
697  valid examples: "0A5D15"; "0x15, 0x49, 0xa2"; "59\ta9\te3\n"
698
699
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 < strhex_len && strhex[i] != 0; i++) {
715                 if (!(p1 = strchr(hexchars, toupper((unsigned char)strhex[i]))))
716                         break;
717
718                 i++; /* next hex digit */
719
720                 if (!(p2 = strchr(hexchars, toupper((unsigned char)strhex[i]))))
721                         break;
722
723                 /* get the two nybbles */
724                 hinybble = PTR_DIFF(p1, hexchars);
725                 lonybble = PTR_DIFF(p2, hexchars);
726
727                 if (num_chars >= p_len) {
728                         break;
729                 }
730
731                 p[num_chars] = (hinybble << 4) | lonybble;
732                 num_chars++;
733
734                 p1 = NULL;
735                 p2 = NULL;
736         }
737         return num_chars;
738 }
739
740 /** 
741  * Parse a hex string and return a data blob. 
742  */
743 _PUBLIC_ _PURE_ DATA_BLOB strhex_to_data_blob(TALLOC_CTX *mem_ctx, const char *strhex) 
744 {
745         DATA_BLOB ret_blob = data_blob_talloc(mem_ctx, NULL, strlen(strhex)/2+1);
746
747         ret_blob.length = strhex_to_str((char *)ret_blob.data, ret_blob.length,
748                                         strhex,
749                                         strlen(strhex));
750
751         return ret_blob;
752 }
753
754
755 /**
756  * Routine to print a buffer as HEX digits, into an allocated string.
757  */
758 _PUBLIC_ void hex_encode(const unsigned char *buff_in, size_t len, char **out_hex_buffer)
759 {
760         int i;
761         char *hex_buffer;
762
763         *out_hex_buffer = malloc_array_p(char, (len*2)+1);
764         hex_buffer = *out_hex_buffer;
765
766         for (i = 0; i < len; i++)
767                 slprintf(&hex_buffer[i*2], 3, "%02X", buff_in[i]);
768 }
769
770 /**
771  * talloc version of hex_encode()
772  */
773 _PUBLIC_ char *hex_encode_talloc(TALLOC_CTX *mem_ctx, const unsigned char *buff_in, size_t len)
774 {
775         int i;
776         char *hex_buffer;
777
778         hex_buffer = talloc_array(mem_ctx, char, (len*2)+1);
779         if (!hex_buffer) {
780                 return NULL;
781         }
782
783         for (i = 0; i < len; i++)
784                 slprintf(&hex_buffer[i*2], 3, "%02X", buff_in[i]);
785
786         talloc_set_name_const(hex_buffer, hex_buffer);
787         return hex_buffer;
788 }
789
790 /**
791   varient of strcmp() that handles NULL ptrs
792 **/
793 _PUBLIC_ int strcmp_safe(const char *s1, const char *s2)
794 {
795         if (s1 == s2) {
796                 return 0;
797         }
798         if (s1 == NULL || s2 == NULL) {
799                 return s1?-1:1;
800         }
801         return strcmp(s1, s2);
802 }
803
804
805 /**
806 return the number of bytes occupied by a buffer in ASCII format
807 the result includes the null termination
808 limited by 'n' bytes
809 **/
810 _PUBLIC_ size_t ascii_len_n(const char *src, size_t n)
811 {
812         size_t len;
813
814         len = strnlen(src, n);
815         if (len+1 <= n) {
816                 len += 1;
817         }
818
819         return len;
820 }
821
822 /**
823  Set a boolean variable from the text value stored in the passed string.
824  Returns true in success, false if the passed string does not correctly 
825  represent a boolean.
826 **/
827
828 _PUBLIC_ bool set_boolean(const char *boolean_string, bool *boolean)
829 {
830         if (strwicmp(boolean_string, "yes") == 0 ||
831             strwicmp(boolean_string, "true") == 0 ||
832             strwicmp(boolean_string, "on") == 0 ||
833             strwicmp(boolean_string, "1") == 0) {
834                 *boolean = true;
835                 return true;
836         } else if (strwicmp(boolean_string, "no") == 0 ||
837                    strwicmp(boolean_string, "false") == 0 ||
838                    strwicmp(boolean_string, "off") == 0 ||
839                    strwicmp(boolean_string, "0") == 0) {
840                 *boolean = false;
841                 return true;
842         }
843         return false;
844 }
845
846 /**
847 return the number of bytes occupied by a buffer in CH_UTF16 format
848 the result includes the null termination
849 **/
850 _PUBLIC_ size_t utf16_len(const void *buf)
851 {
852         size_t len;
853
854         for (len = 0; SVAL(buf,len); len += 2) ;
855
856         return len + 2;
857 }
858
859 /**
860 return the number of bytes occupied by a buffer in CH_UTF16 format
861 the result includes the null termination
862 limited by 'n' bytes
863 **/
864 _PUBLIC_ size_t utf16_len_n(const void *src, size_t n)
865 {
866         size_t len;
867
868         for (len = 0; (len+2 < n) && SVAL(src, len); len += 2) ;
869
870         if (len+2 <= n) {
871                 len += 2;
872         }
873
874         return len;
875 }
876
877 /**
878  * @file
879  * @brief String utilities.
880  **/
881
882 static bool next_token_internal_talloc(TALLOC_CTX *ctx,
883                                 const char **ptr,
884                                 char **pp_buff,
885                                 const char *sep,
886                                 bool ltrim)
887 {
888         const char *s;
889         const char *saved_s;
890         char *pbuf;
891         bool quoted;
892         size_t len=1;
893
894         *pp_buff = NULL;
895         if (!ptr) {
896                 return(false);
897         }
898
899         s = *ptr;
900
901         /* default to simple separators */
902         if (!sep) {
903                 sep = " \t\n\r";
904         }
905
906         /* find the first non sep char, if left-trimming is requested */
907         if (ltrim) {
908                 while (*s && strchr_m(sep,*s)) {
909                         s++;
910                 }
911         }
912
913         /* nothing left? */
914         if (!*s) {
915                 return false;
916         }
917
918         /* When restarting we need to go from here. */
919         saved_s = s;
920
921         /* Work out the length needed. */
922         for (quoted = false; *s &&
923                         (quoted || !strchr_m(sep,*s)); s++) {
924                 if (*s == '\"') {
925                         quoted = !quoted;
926                 } else {
927                         len++;
928                 }
929         }
930
931         /* We started with len = 1 so we have space for the nul. */
932         *pp_buff = talloc_array(ctx, char, len);
933         if (!*pp_buff) {
934                 return false;
935         }
936
937         /* copy over the token */
938         pbuf = *pp_buff;
939         s = saved_s;
940         for (quoted = false; *s &&
941                         (quoted || !strchr_m(sep,*s)); s++) {
942                 if ( *s == '\"' ) {
943                         quoted = !quoted;
944                 } else {
945                         *pbuf++ = *s;
946                 }
947         }
948
949         *ptr = (*s) ? s+1 : s;
950         *pbuf = 0;
951
952         return true;
953 }
954
955 bool next_token_talloc(TALLOC_CTX *ctx,
956                         const char **ptr,
957                         char **pp_buff,
958                         const char *sep)
959 {
960         return next_token_internal_talloc(ctx, ptr, pp_buff, sep, true);
961 }
962
963 /*
964  * Get the next token from a string, return false if none found.  Handles
965  * double-quotes.  This version does not trim leading separator characters
966  * before looking for a token.
967  */
968
969 bool next_token_no_ltrim_talloc(TALLOC_CTX *ctx,
970                         const char **ptr,
971                         char **pp_buff,
972                         const char *sep)
973 {
974         return next_token_internal_talloc(ctx, ptr, pp_buff, sep, false);
975 }
976
977 /**
978  * Get the next token from a string, return False if none found.
979  * Handles double-quotes.
980  *
981  * Based on a routine by GJC@VILLAGE.COM.
982  * Extensively modified by Andrew.Tridgell@anu.edu.au
983  **/
984 _PUBLIC_ bool next_token(const char **ptr,char *buff, const char *sep, size_t bufsize)
985 {
986         const char *s;
987         bool quoted;
988         size_t len=1;
989
990         if (!ptr)
991                 return false;
992
993         s = *ptr;
994
995         /* default to simple separators */
996         if (!sep)
997                 sep = " \t\n\r";
998
999         /* find the first non sep char */
1000         while (*s && strchr_m(sep,*s))
1001                 s++;
1002
1003         /* nothing left? */
1004         if (!*s)
1005                 return false;
1006
1007         /* copy over the token */
1008         for (quoted = false; len < bufsize && *s && (quoted || !strchr_m(sep,*s)); s++) {
1009                 if (*s == '\"') {
1010                         quoted = !quoted;
1011                 } else {
1012                         len++;
1013                         *buff++ = *s;
1014                 }
1015         }
1016
1017         *ptr = (*s) ? s+1 : s;
1018         *buff = 0;
1019
1020         return true;
1021 }
1022
1023 struct anonymous_shared_header {
1024         union {
1025                 size_t length;
1026                 uint8_t pad[16];
1027         } u;
1028 };
1029
1030 /* Map a shared memory buffer of at least nelem counters. */
1031 void *anonymous_shared_allocate(size_t orig_bufsz)
1032 {
1033         void *ptr;
1034         void *buf;
1035         size_t pagesz = getpagesize();
1036         size_t pagecnt;
1037         size_t bufsz = orig_bufsz;
1038         struct anonymous_shared_header *hdr;
1039
1040         bufsz += sizeof(*hdr);
1041
1042         /* round up to full pages */
1043         pagecnt = bufsz / pagesz;
1044         if (bufsz % pagesz) {
1045                 pagecnt += 1;
1046         }
1047         bufsz = pagesz * pagecnt;
1048
1049         if (orig_bufsz >= bufsz) {
1050                 /* integer wrap */
1051                 errno = ENOMEM;
1052                 return NULL;
1053         }
1054
1055 #ifdef MAP_ANON
1056         /* BSD */
1057         buf = mmap(NULL, bufsz, PROT_READ|PROT_WRITE, MAP_ANON|MAP_SHARED,
1058                         -1 /* fd */, 0 /* offset */);
1059 #else
1060         buf = mmap(NULL, bufsz, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED,
1061                         open("/dev/zero", O_RDWR), 0 /* offset */);
1062 #endif
1063
1064         if (buf == MAP_FAILED) {
1065                 return NULL;
1066         }
1067
1068         hdr = (struct anonymous_shared_header *)buf;
1069         hdr->u.length = bufsz;
1070
1071         ptr = (void *)(&hdr[1]);
1072
1073         return ptr;
1074 }
1075
1076 void anonymous_shared_free(void *ptr)
1077 {
1078         struct anonymous_shared_header *hdr;
1079
1080         if (ptr == NULL) {
1081                 return;
1082         }
1083
1084         hdr = (struct anonymous_shared_header *)ptr;
1085
1086         hdr--;
1087
1088         munmap(hdr, hdr->u.length);
1089 }
1090
1091 #ifdef DEVELOPER
1092 /* used when you want a debugger started at a particular point in the
1093    code. Mostly useful in code that runs as a child process, where
1094    normal gdb attach is harder to organise.
1095 */
1096 void samba_start_debugger(void)
1097 {
1098         char *cmd = NULL;
1099         if (asprintf(&cmd, "xterm -e \"gdb --pid %u\"&", getpid()) == -1) {
1100                 return;
1101         }
1102         if (system(cmd) == -1) {
1103                 free(cmd);
1104                 return;
1105         }
1106         free(cmd);
1107         sleep(2);
1108 }
1109 #endif