lib/util: only change umask during mkdir()
[Samba.git] / lib / util / util.c
blob960bda0f9bf459ca7558ffaf3090ab452c233bcd
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
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.
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.
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/>.
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"
32 #undef malloc
33 #undef strcasecmp
34 #undef strncasecmp
35 #undef strdup
36 #undef realloc
38 /**
39 * @file
40 * @brief Misc utility functions
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)
49 char *p;
50 if ((p = getenv("TMPDIR")))
51 return p;
52 return "/tmp";
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)
63 char *fname;
64 int fd;
66 if (!dir) {
67 dir = tmpdir();
70 fname = talloc_asprintf(talloc_tos(), "%s/listenerlock_XXXXXX", dir);
71 if (fname == NULL) {
72 errno = ENOMEM;
73 return -1;
75 fd = mkstemp(fname);
76 if (fd == -1) {
77 TALLOC_FREE(fname);
78 return -1;
80 if (unlink(fname) == -1) {
81 int sys_errno = errno;
82 close(fd);
83 TALLOC_FREE(fname);
84 errno = sys_errno;
85 return -1;
87 TALLOC_FREE(fname);
88 return fd;
92 /**
93 Check if a file exists - call vfs_file_exist for samba files.
94 **/
95 _PUBLIC_ bool file_exist(const char *fname)
97 struct stat st;
99 if (stat(fname, &st) != 0) {
100 return false;
103 return ((S_ISREG(st.st_mode)) || (S_ISFIFO(st.st_mode)));
107 Check a files mod time.
110 _PUBLIC_ time_t file_modtime(const char *fname)
112 struct stat st;
114 if (stat(fname,&st) != 0)
115 return(0);
117 return(st.st_mtime);
121 Check if a directory exists.
124 _PUBLIC_ bool directory_exist(const char *dname)
126 struct stat st;
127 bool ret;
129 if (stat(dname,&st) != 0) {
130 return false;
133 ret = S_ISDIR(st.st_mode);
134 if(!ret)
135 errno = ENOTDIR;
136 return ret;
140 * Try to create the specified directory if it didn't exist.
142 * @retval true if the directory already existed and has the right permissions
143 * or was successfully created.
145 _PUBLIC_ bool directory_create_or_exist(const char *dname, uid_t uid,
146 mode_t dir_perms)
148 int ret;
149 struct stat st;
151 ret = lstat(dname, &st);
152 if (ret == -1) {
153 mode_t old_umask;
155 if (errno != ENOENT) {
156 DEBUG(0, ("lstat failed on directory %s: %s\n",
157 dname, strerror(errno)));
158 return false;
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;
171 umask(old_umask);
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;
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;
187 if (st.st_uid != uid && !uwrap_enabled()) {
188 DEBUG(0, ("invalid ownership on directory "
189 "%s\n", dname));
190 return false;
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;
199 return true;
204 Sleep for a specified number of milliseconds.
207 _PUBLIC_ void smb_msleep(unsigned int t)
209 #if defined(HAVE_NANOSLEEP)
210 struct timespec ts;
211 int ret;
213 ts.tv_sec = t/1000;
214 ts.tv_nsec = 1000000*(t%1000);
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;
225 GetTimeOfDay(&t1);
226 t2 = t1;
228 while (tdiff < t) {
229 tval.tv_sec = (t-tdiff)/1000;
230 tval.tv_usec = 1000*((t-tdiff)%1000);
232 /* Never wait for more than 1 sec. */
233 if (tval.tv_sec > 1) {
234 tval.tv_sec = 1;
235 tval.tv_usec = 0;
238 FD_ZERO(&fds);
239 errno = 0;
240 select(0,&fds,NULL,NULL,&tval);
242 GetTimeOfDay(&t2);
243 if (t2.tv_sec < t1.tv_sec) {
244 /* Someone adjusted time... */
245 t1 = t2;
248 tdiff = usec_time_diff(&t2,&t1)/1000;
250 #endif
254 Get my own name, return in talloc'ed storage.
257 _PUBLIC_ char *get_myname(TALLOC_CTX *ctx)
259 char *p;
260 char hostname[HOST_NAME_MAX];
262 /* get my host name */
263 if (gethostname(hostname, sizeof(hostname)) == -1) {
264 DEBUG(0,("gethostname failed\n"));
265 return NULL;
268 /* Ensure null termination. */
269 hostname[sizeof(hostname)-1] = '\0';
271 /* split off any parts after an initial . */
272 p = strchr_m(hostname, '.');
273 if (p) {
274 *p = 0;
277 return talloc_strdup(ctx, hostname);
281 Check if a process exists. Does this work on all unixes?
284 _PUBLIC_ bool process_exists_by_pid(pid_t pid)
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);
293 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
294 is dealt with in posix.c
297 _PUBLIC_ bool fcntl_lock(int fd, int op, off_t offset, off_t count, int type)
299 struct flock lock;
300 int ret;
302 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
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;
310 ret = fcntl(fd,op,&lock);
312 if (ret == -1 && errno != 0)
313 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
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;
325 /* it must be not locked or locked by me */
326 return false;
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;
336 /* everything went OK */
337 DEBUG(8,("fcntl_lock: Lock call successful\n"));
339 return true;
342 static void debugadd_cb(const char *buf, void *private_data)
344 int *plevel = (int *)private_data;
345 DEBUGADD(*plevel, ("%s", buf));
348 void print_asc_cb(const uint8_t *buf, int len,
349 void (*cb)(const char *buf, void *private_data),
350 void *private_data)
352 int i;
353 char s[2];
354 s[1] = 0;
356 for (i=0; i<len; i++) {
357 s[0] = isprint(buf[i]) ? buf[i] : '.';
358 cb(s, private_data);
362 void print_asc(int level, const uint8_t *buf,int len)
364 print_asc_cb(buf, len, debugadd_cb, &level);
368 * Write dump of binary data to a callback
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)
375 int i=0;
376 static const uint8_t empty[16] = { 0, };
377 bool skipped = false;
378 char tmp[16];
380 if (len<=0) return;
382 for (i=0;i<len;) {
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))
390 i +=16;
391 continue;
394 if (i<len) {
395 snprintf(tmp, sizeof(tmp), "[%04X] ", i);
396 cb(tmp, private_data);
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);
406 if (i%16 == 0) {
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);
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;
425 if (i%16) {
426 int n;
427 n = 16 - (i%16);
428 cb(" ", private_data);
429 if (n>8) {
430 cb(" ", private_data);
432 while (n--) {
433 cb(" ", private_data);
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);
442 cb("\n", private_data);
448 * Write dump of binary data to the log file.
450 * The data is only written if the log level is at least level.
452 _PUBLIC_ void dump_data(int level, const uint8_t *buf, int len)
454 if (!DEBUGLVL(level)) {
455 return;
457 dump_data_cb(buf, len, false, debugadd_cb, &level);
461 * Write dump of binary data to the log file.
463 * The data is only written if the log level is at least level.
464 * 16 zero bytes in a row are omitted
466 _PUBLIC_ void dump_data_skip_zeros(int level, const uint8_t *buf, int len)
468 if (!DEBUGLVL(level)) {
469 return;
471 dump_data_cb(buf, len, true, debugadd_cb, &level);
474 static void fprintf_cb(const char *buf, void *private_data)
476 FILE *f = (FILE *)private_data;
477 fprintf(f, "%s", buf);
480 void dump_data_file(const uint8_t *buf, int len, bool omit_zero_bytes,
481 FILE *f)
483 dump_data_cb(buf, len, omit_zero_bytes, fprintf_cb, f);
487 malloc that aborts with smb_panic on fail or zero size.
490 _PUBLIC_ void *smb_xmalloc(size_t size)
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;
501 Memdup with smb_panic on fail.
504 _PUBLIC_ void *smb_xmemdup(const void *p, size_t size)
506 void *p2;
507 p2 = smb_xmalloc(size);
508 memcpy(p2, p, size);
509 return p2;
513 strdup that aborts on malloc fail.
516 char *smb_xstrdup(const char *s)
518 #if defined(PARANOID_MALLOC_CHECKER)
519 #ifdef strdup
520 #undef strdup
521 #endif
522 #endif
524 #ifndef HAVE_STRDUP
525 #define strdup rep_strdup
526 #endif
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");
538 return s1;
543 strndup that aborts on malloc fail.
546 char *smb_xstrndup(const char *s, size_t n)
548 #if defined(PARANOID_MALLOC_CHECKER)
549 #ifdef strndup
550 #undef strndup
551 #endif
552 #endif
554 #if (defined(BROKEN_STRNDUP) || !defined(HAVE_STRNDUP))
555 #undef HAVE_STRNDUP
556 #define strndup rep_strndup
557 #endif
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");
569 return s1;
575 Like strdup but for memory.
578 _PUBLIC_ void *memdup(const void *p, size_t size)
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;
591 * Write a password to the log file.
593 * @note Only actually does something if DEBUG_PASSWORD was defined during
594 * compile-time.
596 _PUBLIC_ void dump_data_pw(const char *msg, const uint8_t * data, size_t len)
598 #ifdef DEBUG_PASSWORD
599 DEBUG(11, ("%s", msg));
600 if (data != NULL && len > 0)
602 dump_data(11, data, len);
604 #endif
609 * see if a range of memory is all zero. A NULL pointer is considered
610 * to be all zero
612 _PUBLIC_ bool all_zero(const uint8_t *ptr, size_t size)
614 int i;
615 if (!ptr) return true;
616 for (i=0;i<size;i++) {
617 if (ptr[i]) return false;
619 return true;
623 realloc an array, checking for integer overflow in the array size
625 _PUBLIC_ void *realloc_array(void *ptr, size_t el_size, unsigned count, bool free_on_fail)
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;
634 if (!ptr) {
635 return malloc(el_size * count);
637 return realloc(ptr, el_size * count);
640 /****************************************************************************
641 Type-safe malloc.
642 ****************************************************************************/
644 void *malloc_array(size_t el_size, unsigned int count)
646 return realloc_array(NULL, el_size, count, false);
650 Trim the specified elements off the front and back of a string.
652 _PUBLIC_ bool trim_string(char *s, const char *front, const char *back)
654 bool ret = false;
655 size_t front_len;
656 size_t back_len;
657 size_t len;
659 /* Ignore null or empty strings. */
660 if (!s || (s[0] == '\0'))
661 return false;
663 front_len = front? strlen(front) : 0;
664 back_len = back? strlen(back) : 0;
666 len = strlen(s);
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;
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;
685 return ret;
689 Find the number of 'c' chars in a string
691 _PUBLIC_ _PURE_ size_t count_chars(const char *s, char c)
693 size_t count = 0;
695 while (*s) {
696 if (*s == c) count++;
697 s ++;
700 return count;
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.
711 * valid examples: "0A5D15"; "0x123456"
713 _PUBLIC_ size_t strhex_to_str(char *p, size_t p_len, const char *strhex, size_t strhex_len)
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;
721 /* skip leading 0x prefix */
722 if (strncasecmp(strhex, "0x", 2) == 0) {
723 i += 2; /* skip two chars */
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;
732 i++; /* next hex digit */
734 p2 = strchr(hexchars, toupper((unsigned char)strhex[i]));
735 if (p2 == NULL) {
736 break;
739 /* get the two nybbles */
740 hinybble = PTR_DIFF(p1, hexchars);
741 lonybble = PTR_DIFF(p2, hexchars);
743 if (num_chars >= p_len) {
744 break;
747 p[num_chars] = (hinybble << 4) | lonybble;
748 num_chars++;
750 p1 = NULL;
751 p2 = NULL;
753 return num_chars;
756 /**
757 * Parse a hex string and return a data blob.
759 _PUBLIC_ _PURE_ DATA_BLOB strhex_to_data_blob(TALLOC_CTX *mem_ctx, const char *strhex)
761 DATA_BLOB ret_blob = data_blob_talloc(mem_ctx, NULL, strlen(strhex)/2+1);
763 ret_blob.length = strhex_to_str((char *)ret_blob.data, ret_blob.length,
764 strhex,
765 strlen(strhex));
767 return ret_blob;
771 * Print a buf in hex. Assumes dst is at least (srclen*2)+1 large.
773 _PUBLIC_ void hex_encode_buf(char *dst, const uint8_t *src, size_t srclen)
775 size_t i;
776 for (i=0; i<srclen; i++) {
777 snprintf(dst + i*2, 3, "%02X", src[i]);
780 * Ensure 0-termination for 0-length buffers
782 dst[srclen*2] = '\0';
786 * Routine to print a buffer as HEX digits, into an allocated string.
788 _PUBLIC_ void hex_encode(const unsigned char *buff_in, size_t len, char **out_hex_buffer)
790 char *hex_buffer;
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);
798 * talloc version of hex_encode()
800 _PUBLIC_ char *hex_encode_talloc(TALLOC_CTX *mem_ctx, const unsigned char *buff_in, size_t len)
802 char *hex_buffer;
804 hex_buffer = talloc_array(mem_ctx, char, (len*2)+1);
805 if (!hex_buffer) {
806 return NULL;
808 hex_encode_buf(hex_buffer, buff_in, len);
809 talloc_set_name_const(hex_buffer, hex_buffer);
810 return hex_buffer;
814 varient of strcmp() that handles NULL ptrs
816 _PUBLIC_ int strcmp_safe(const char *s1, const char *s2)
818 if (s1 == s2) {
819 return 0;
821 if (s1 == NULL || s2 == NULL) {
822 return s1?-1:1;
824 return strcmp(s1, s2);
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
833 _PUBLIC_ size_t ascii_len_n(const char *src, size_t n)
835 size_t len;
837 len = strnlen(src, n);
838 if (len+1 <= n) {
839 len += 1;
842 return len;
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.
851 _PUBLIC_ bool set_boolean(const char *boolean_string, bool *boolean)
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;
866 return false;
870 return the number of bytes occupied by a buffer in CH_UTF16 format
871 the result includes the null termination
873 _PUBLIC_ size_t utf16_len(const void *buf)
875 size_t len;
877 for (len = 0; SVAL(buf,len); len += 2) ;
879 return len + 2;
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
887 _PUBLIC_ size_t utf16_len_n(const void *src, size_t n)
889 size_t len;
891 for (len = 0; (len+2 < n) && SVAL(src, len); len += 2) ;
893 if (len+2 <= n) {
894 len += 2;
897 return len;
901 * @file
902 * @brief String utilities.
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)
911 const char *s;
912 const char *saved_s;
913 char *pbuf;
914 bool quoted;
915 size_t len=1;
917 *pp_buff = NULL;
918 if (!ptr) {
919 return(false);
922 s = *ptr;
924 /* default to simple separators */
925 if (!sep) {
926 sep = " \t\n\r";
929 /* find the first non sep char, if left-trimming is requested */
930 if (ltrim) {
931 while (*s && strchr_m(sep,*s)) {
932 s++;
936 /* nothing left? */
937 if (!*s) {
938 return false;
941 /* When restarting we need to go from here. */
942 saved_s = s;
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++;
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;
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;
972 *ptr = (*s) ? s+1 : s;
973 *pbuf = 0;
975 return true;
978 bool next_token_talloc(TALLOC_CTX *ctx,
979 const char **ptr,
980 char **pp_buff,
981 const char *sep)
983 return next_token_internal_talloc(ctx, ptr, pp_buff, sep, true);
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.
992 bool next_token_no_ltrim_talloc(TALLOC_CTX *ctx,
993 const char **ptr,
994 char **pp_buff,
995 const char *sep)
997 return next_token_internal_talloc(ctx, ptr, pp_buff, sep, false);
1001 * Get the next token from a string, return False if none found.
1002 * Handles double-quotes.
1004 * Based on a routine by GJC@VILLAGE.COM.
1005 * Extensively modified by Andrew.Tridgell@anu.edu.au
1007 _PUBLIC_ bool next_token(const char **ptr,char *buff, const char *sep, size_t bufsize)
1009 const char *s;
1010 bool quoted;
1011 size_t len=1;
1013 if (!ptr)
1014 return false;
1016 s = *ptr;
1018 /* default to simple separators */
1019 if (!sep)
1020 sep = " \t\n\r";
1022 /* find the first non sep char */
1023 while (*s && strchr_m(sep,*s))
1024 s++;
1026 /* nothing left? */
1027 if (!*s)
1028 return false;
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;
1040 *ptr = (*s) ? s+1 : s;
1041 *buff = 0;
1043 return true;
1046 struct anonymous_shared_header {
1047 union {
1048 size_t length;
1049 uint8_t pad[16];
1050 } u;
1053 /* Map a shared memory buffer of at least nelem counters. */
1054 void *anonymous_shared_allocate(size_t orig_bufsz)
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;
1063 bufsz += sizeof(*hdr);
1065 /* round up to full pages */
1066 pagecnt = bufsz / pagesz;
1067 if (bufsz % pagesz) {
1068 pagecnt += 1;
1070 bufsz = pagesz * pagecnt;
1072 if (orig_bufsz >= bufsz) {
1073 /* integer wrap */
1074 errno = ENOMEM;
1075 return NULL;
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
1087 if (buf == MAP_FAILED) {
1088 return NULL;
1091 hdr = (struct anonymous_shared_header *)buf;
1092 hdr->u.length = bufsz;
1094 ptr = (void *)(&hdr[1]);
1096 return ptr;
1099 void *anonymous_shared_resize(void *ptr, size_t new_size, bool maymove)
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;
1109 if (ptr == NULL) {
1110 errno = EINVAL;
1111 return NULL;
1114 hdr = (struct anonymous_shared_header *)ptr;
1115 hdr--;
1116 if (hdr->u.length > (new_size + sizeof(*hdr))) {
1117 errno = EINVAL;
1118 return NULL;
1121 bufsz = new_size + sizeof(*hdr);
1123 /* round up to full pages */
1124 pagecnt = bufsz / pagesz;
1125 if (bufsz % pagesz) {
1126 pagecnt += 1;
1128 bufsz = pagesz * pagecnt;
1130 if (new_size >= bufsz) {
1131 /* integer wrap */
1132 errno = ENOSPC;
1133 return NULL;
1136 if (bufsz <= hdr->u.length) {
1137 return ptr;
1140 if (maymove) {
1141 flags = MREMAP_MAYMOVE;
1144 buf = mremap(hdr, hdr->u.length, bufsz, flags);
1146 if (buf == MAP_FAILED) {
1147 errno = ENOSPC;
1148 return NULL;
1151 hdr = (struct anonymous_shared_header *)buf;
1152 hdr->u.length = bufsz;
1154 ptr = (void *)(&hdr[1]);
1156 return ptr;
1157 #else
1158 errno = ENOSPC;
1159 return NULL;
1160 #endif
1163 void anonymous_shared_free(void *ptr)
1165 struct anonymous_shared_header *hdr;
1167 if (ptr == NULL) {
1168 return;
1171 hdr = (struct anonymous_shared_header *)ptr;
1173 hdr--;
1175 munmap(hdr, hdr->u.length);
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.
1183 void samba_start_debugger(void)
1185 char *cmd = NULL;
1186 if (asprintf(&cmd, "xterm -e \"gdb --pid %u\"&", getpid()) == -1) {
1187 return;
1189 if (system(cmd) == -1) {
1190 free(cmd);
1191 return;
1193 free(cmd);
1194 sleep(2);
1196 #endif