s4:lib/stream: make use of smb_len_tcp()
[Samba.git] / lib / util / util.c
blob133bd0dfb0b42658a06d6386a85daa6a2811e3fc
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"
31 #undef malloc
32 #undef strcasecmp
33 #undef strncasecmp
34 #undef strdup
35 #undef realloc
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
46 /**
47 * @file
48 * @brief Misc utility functions
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)
57 char *p;
58 if ((p = getenv("TMPDIR")))
59 return p;
60 return "/tmp";
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)
71 char *fname;
72 int fd;
74 if (!dir) {
75 dir = tmpdir();
78 fname = talloc_asprintf(talloc_tos(), "%s/listenerlock_XXXXXX", dir);
79 if (fname == NULL) {
80 errno = ENOMEM;
81 return -1;
83 fd = mkstemp(fname);
84 if (fd == -1) {
85 TALLOC_FREE(fname);
86 return -1;
88 if (unlink(fname) == -1) {
89 int sys_errno = errno;
90 close(fd);
91 TALLOC_FREE(fname);
92 errno = sys_errno;
93 return -1;
95 TALLOC_FREE(fname);
96 return fd;
101 Check if a file exists - call vfs_file_exist for samba files.
103 _PUBLIC_ bool file_exist(const char *fname)
105 struct stat st;
107 if (stat(fname, &st) != 0) {
108 return false;
111 return ((S_ISREG(st.st_mode)) || (S_ISFIFO(st.st_mode)));
115 Check a files mod time.
118 _PUBLIC_ time_t file_modtime(const char *fname)
120 struct stat st;
122 if (stat(fname,&st) != 0)
123 return(0);
125 return(st.st_mtime);
129 Check if a directory exists.
132 _PUBLIC_ bool directory_exist(const char *dname)
134 struct stat st;
135 bool ret;
137 if (stat(dname,&st) != 0) {
138 return false;
141 ret = S_ISDIR(st.st_mode);
142 if(!ret)
143 errno = ENOTDIR;
144 return ret;
148 * Try to create the specified directory if it didn't exist.
150 * @retval true if the directory already existed and has the right permissions
151 * or was successfully created.
153 _PUBLIC_ bool directory_create_or_exist(const char *dname, uid_t uid,
154 mode_t dir_perms)
156 mode_t old_umask;
157 struct stat st;
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;
170 } else {
171 DEBUG(0, ("lstat failed on directory %s: %s\n",
172 dname, strerror(errno)));
173 umask(old_umask);
174 return false;
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;
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;
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;
198 return true;
203 Sleep for a specified number of milliseconds.
206 _PUBLIC_ void smb_msleep(unsigned int t)
208 #if defined(HAVE_NANOSLEEP)
209 struct timespec ts;
210 int ret;
212 ts.tv_sec = t/1000;
213 ts.tv_nsec = 1000000*(t%1000);
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;
224 GetTimeOfDay(&t1);
225 t2 = t1;
227 while (tdiff < t) {
228 tval.tv_sec = (t-tdiff)/1000;
229 tval.tv_usec = 1000*((t-tdiff)%1000);
231 /* Never wait for more than 1 sec. */
232 if (tval.tv_sec > 1) {
233 tval.tv_sec = 1;
234 tval.tv_usec = 0;
237 FD_ZERO(&fds);
238 errno = 0;
239 select(0,&fds,NULL,NULL,&tval);
241 GetTimeOfDay(&t2);
242 if (t2.tv_sec < t1.tv_sec) {
243 /* Someone adjusted time... */
244 t1 = t2;
247 tdiff = usec_time_diff(&t2,&t1)/1000;
249 #endif
253 Get my own name, return in talloc'ed storage.
256 _PUBLIC_ char *get_myname(TALLOC_CTX *ctx)
258 char *p;
259 char hostname[HOST_NAME_MAX];
261 /* get my host name */
262 if (gethostname(hostname, sizeof(hostname)) == -1) {
263 DEBUG(0,("gethostname failed\n"));
264 return NULL;
267 /* Ensure null termination. */
268 hostname[sizeof(hostname)-1] = '\0';
270 /* split off any parts after an initial . */
271 p = strchr_m(hostname, '.');
272 if (p) {
273 *p = 0;
276 return talloc_strdup(ctx, hostname);
280 Check if a process exists. Does this work on all unixes?
283 _PUBLIC_ bool process_exists_by_pid(pid_t pid)
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);
292 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
293 is dealt with in posix.c
296 _PUBLIC_ bool fcntl_lock(int fd, int op, off_t offset, off_t count, int type)
298 struct flock lock;
299 int ret;
301 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
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;
309 ret = fcntl(fd,op,&lock);
311 if (ret == -1 && errno != 0)
312 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
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;
324 /* it must be not locked or locked by me */
325 return false;
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;
335 /* everything went OK */
336 DEBUG(8,("fcntl_lock: Lock call successful\n"));
338 return true;
341 static void debugadd_cb(const char *buf, void *private_data)
343 int *plevel = (int *)private_data;
344 DEBUGADD(*plevel, ("%s", buf));
347 void print_asc_cb(const uint8_t *buf, int len,
348 void (*cb)(const char *buf, void *private_data),
349 void *private_data)
351 int i;
352 char s[2];
353 s[1] = 0;
355 for (i=0; i<len; i++) {
356 s[0] = isprint(buf[i]) ? buf[i] : '.';
357 cb(s, private_data);
361 void print_asc(int level, const uint8_t *buf,int len)
363 print_asc_cb(buf, len, debugadd_cb, &level);
367 * Write dump of binary data to a callback
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)
374 int i=0;
375 static const uint8_t empty[16] = { 0, };
376 bool skipped = false;
377 char tmp[16];
379 if (len<=0) return;
381 for (i=0;i<len;) {
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))
389 i +=16;
390 continue;
393 if (i<len) {
394 snprintf(tmp, sizeof(tmp), "[%04X] ", i);
395 cb(tmp, private_data);
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);
405 if (i%16 == 0) {
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);
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;
424 if (i%16) {
425 int n;
426 n = 16 - (i%16);
427 cb(" ", private_data);
428 if (n>8) {
429 cb(" ", private_data);
431 while (n--) {
432 cb(" ", private_data);
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);
441 cb("\n", private_data);
447 * Write dump of binary data to the log file.
449 * The data is only written if the log level is at least level.
451 _PUBLIC_ void dump_data(int level, const uint8_t *buf, int len)
453 if (!DEBUGLVL(level)) {
454 return;
456 dump_data_cb(buf, len, false, debugadd_cb, &level);
460 * Write dump of binary data to the log file.
462 * The data is only written if the log level is at least level.
463 * 16 zero bytes in a row are omitted
465 _PUBLIC_ void dump_data_skip_zeros(int level, const uint8_t *buf, int len)
467 if (!DEBUGLVL(level)) {
468 return;
470 dump_data_cb(buf, len, true, debugadd_cb, &level);
475 malloc that aborts with smb_panic on fail or zero size.
478 _PUBLIC_ void *smb_xmalloc(size_t size)
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;
489 Memdup with smb_panic on fail.
492 _PUBLIC_ void *smb_xmemdup(const void *p, size_t size)
494 void *p2;
495 p2 = smb_xmalloc(size);
496 memcpy(p2, p, size);
497 return p2;
501 strdup that aborts on malloc fail.
504 char *smb_xstrdup(const char *s)
506 #if defined(PARANOID_MALLOC_CHECKER)
507 #ifdef strdup
508 #undef strdup
509 #endif
510 #endif
512 #ifndef HAVE_STRDUP
513 #define strdup rep_strdup
514 #endif
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");
526 return s1;
531 strndup that aborts on malloc fail.
534 char *smb_xstrndup(const char *s, size_t n)
536 #if defined(PARANOID_MALLOC_CHECKER)
537 #ifdef strndup
538 #undef strndup
539 #endif
540 #endif
542 #if (defined(BROKEN_STRNDUP) || !defined(HAVE_STRNDUP))
543 #undef HAVE_STRNDUP
544 #define strndup rep_strndup
545 #endif
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");
557 return s1;
563 Like strdup but for memory.
566 _PUBLIC_ void *memdup(const void *p, size_t size)
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;
579 * Write a password to the log file.
581 * @note Only actually does something if DEBUG_PASSWORD was defined during
582 * compile-time.
584 _PUBLIC_ void dump_data_pw(const char *msg, const uint8_t * data, size_t len)
586 #ifdef DEBUG_PASSWORD
587 DEBUG(11, ("%s", msg));
588 if (data != NULL && len > 0)
590 dump_data(11, data, len);
592 #endif
597 * see if a range of memory is all zero. A NULL pointer is considered
598 * to be all zero
600 _PUBLIC_ bool all_zero(const uint8_t *ptr, size_t size)
602 int i;
603 if (!ptr) return true;
604 for (i=0;i<size;i++) {
605 if (ptr[i]) return false;
607 return true;
611 realloc an array, checking for integer overflow in the array size
613 _PUBLIC_ void *realloc_array(void *ptr, size_t el_size, unsigned count, bool free_on_fail)
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;
622 if (!ptr) {
623 return malloc(el_size * count);
625 return realloc(ptr, el_size * count);
628 /****************************************************************************
629 Type-safe malloc.
630 ****************************************************************************/
632 void *malloc_array(size_t el_size, unsigned int count)
634 return realloc_array(NULL, el_size, count, false);
638 Trim the specified elements off the front and back of a string.
640 _PUBLIC_ bool trim_string(char *s, const char *front, const char *back)
642 bool ret = false;
643 size_t front_len;
644 size_t back_len;
645 size_t len;
647 /* Ignore null or empty strings. */
648 if (!s || (s[0] == '\0'))
649 return false;
651 front_len = front? strlen(front) : 0;
652 back_len = back? strlen(back) : 0;
654 len = strlen(s);
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;
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;
673 return ret;
677 Find the number of 'c' chars in a string
679 _PUBLIC_ _PURE_ size_t count_chars(const char *s, char c)
681 size_t count = 0;
683 while (*s) {
684 if (*s == c) count++;
685 s ++;
688 return count;
692 * Routine to get hex characters and turn them into a byte array.
693 * the array can be variable length.
694 * - "0xnn" or "0Xnn" is specially catered for.
695 * - The first non-hex-digit character (apart from possibly leading "0x"
696 * finishes the conversion and skips the rest of the input.
697 * - A single hex-digit character at the end of the string is skipped.
699 * valid examples: "0A5D15"; "0x123456"
701 _PUBLIC_ size_t strhex_to_str(char *p, size_t p_len, const char *strhex, size_t strhex_len)
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;
709 /* skip leading 0x prefix */
710 if (strncasecmp(strhex, "0x", 2) == 0) {
711 i += 2; /* skip two chars */
714 for (; i+1 < strhex_len && strhex[i] != 0 && strhex[i+1] != 0; i++) {
715 p1 = strchr(hexchars, toupper((unsigned char)strhex[i]));
716 if (p1 == NULL) {
717 break;
720 i++; /* next hex digit */
722 p2 = strchr(hexchars, toupper((unsigned char)strhex[i]));
723 if (p2 == NULL) {
724 break;
727 /* get the two nybbles */
728 hinybble = PTR_DIFF(p1, hexchars);
729 lonybble = PTR_DIFF(p2, hexchars);
731 if (num_chars >= p_len) {
732 break;
735 p[num_chars] = (hinybble << 4) | lonybble;
736 num_chars++;
738 p1 = NULL;
739 p2 = NULL;
741 return num_chars;
744 /**
745 * Parse a hex string and return a data blob.
747 _PUBLIC_ _PURE_ DATA_BLOB strhex_to_data_blob(TALLOC_CTX *mem_ctx, const char *strhex)
749 DATA_BLOB ret_blob = data_blob_talloc(mem_ctx, NULL, strlen(strhex)/2+1);
751 ret_blob.length = strhex_to_str((char *)ret_blob.data, ret_blob.length,
752 strhex,
753 strlen(strhex));
755 return ret_blob;
760 * Routine to print a buffer as HEX digits, into an allocated string.
762 _PUBLIC_ void hex_encode(const unsigned char *buff_in, size_t len, char **out_hex_buffer)
764 int i;
765 char *hex_buffer;
767 *out_hex_buffer = malloc_array_p(char, (len*2)+1);
768 hex_buffer = *out_hex_buffer;
770 for (i = 0; i < len; i++)
771 slprintf(&hex_buffer[i*2], 3, "%02X", buff_in[i]);
775 * talloc version of hex_encode()
777 _PUBLIC_ char *hex_encode_talloc(TALLOC_CTX *mem_ctx, const unsigned char *buff_in, size_t len)
779 int i;
780 char *hex_buffer;
782 hex_buffer = talloc_array(mem_ctx, char, (len*2)+1);
783 if (!hex_buffer) {
784 return NULL;
787 for (i = 0; i < len; i++)
788 slprintf(&hex_buffer[i*2], 3, "%02X", buff_in[i]);
790 talloc_set_name_const(hex_buffer, hex_buffer);
791 return hex_buffer;
795 varient of strcmp() that handles NULL ptrs
797 _PUBLIC_ int strcmp_safe(const char *s1, const char *s2)
799 if (s1 == s2) {
800 return 0;
802 if (s1 == NULL || s2 == NULL) {
803 return s1?-1:1;
805 return strcmp(s1, s2);
810 return the number of bytes occupied by a buffer in ASCII format
811 the result includes the null termination
812 limited by 'n' bytes
814 _PUBLIC_ size_t ascii_len_n(const char *src, size_t n)
816 size_t len;
818 len = strnlen(src, n);
819 if (len+1 <= n) {
820 len += 1;
823 return len;
827 Set a boolean variable from the text value stored in the passed string.
828 Returns true in success, false if the passed string does not correctly
829 represent a boolean.
832 _PUBLIC_ bool set_boolean(const char *boolean_string, bool *boolean)
834 if (strwicmp(boolean_string, "yes") == 0 ||
835 strwicmp(boolean_string, "true") == 0 ||
836 strwicmp(boolean_string, "on") == 0 ||
837 strwicmp(boolean_string, "1") == 0) {
838 *boolean = true;
839 return true;
840 } else if (strwicmp(boolean_string, "no") == 0 ||
841 strwicmp(boolean_string, "false") == 0 ||
842 strwicmp(boolean_string, "off") == 0 ||
843 strwicmp(boolean_string, "0") == 0) {
844 *boolean = false;
845 return true;
847 return false;
851 return the number of bytes occupied by a buffer in CH_UTF16 format
852 the result includes the null termination
854 _PUBLIC_ size_t utf16_len(const void *buf)
856 size_t len;
858 for (len = 0; SVAL(buf,len); len += 2) ;
860 return len + 2;
864 return the number of bytes occupied by a buffer in CH_UTF16 format
865 the result includes the null termination
866 limited by 'n' bytes
868 _PUBLIC_ size_t utf16_len_n(const void *src, size_t n)
870 size_t len;
872 for (len = 0; (len+2 < n) && SVAL(src, len); len += 2) ;
874 if (len+2 <= n) {
875 len += 2;
878 return len;
882 * @file
883 * @brief String utilities.
886 static bool next_token_internal_talloc(TALLOC_CTX *ctx,
887 const char **ptr,
888 char **pp_buff,
889 const char *sep,
890 bool ltrim)
892 const char *s;
893 const char *saved_s;
894 char *pbuf;
895 bool quoted;
896 size_t len=1;
898 *pp_buff = NULL;
899 if (!ptr) {
900 return(false);
903 s = *ptr;
905 /* default to simple separators */
906 if (!sep) {
907 sep = " \t\n\r";
910 /* find the first non sep char, if left-trimming is requested */
911 if (ltrim) {
912 while (*s && strchr_m(sep,*s)) {
913 s++;
917 /* nothing left? */
918 if (!*s) {
919 return false;
922 /* When restarting we need to go from here. */
923 saved_s = s;
925 /* Work out the length needed. */
926 for (quoted = false; *s &&
927 (quoted || !strchr_m(sep,*s)); s++) {
928 if (*s == '\"') {
929 quoted = !quoted;
930 } else {
931 len++;
935 /* We started with len = 1 so we have space for the nul. */
936 *pp_buff = talloc_array(ctx, char, len);
937 if (!*pp_buff) {
938 return false;
941 /* copy over the token */
942 pbuf = *pp_buff;
943 s = saved_s;
944 for (quoted = false; *s &&
945 (quoted || !strchr_m(sep,*s)); s++) {
946 if ( *s == '\"' ) {
947 quoted = !quoted;
948 } else {
949 *pbuf++ = *s;
953 *ptr = (*s) ? s+1 : s;
954 *pbuf = 0;
956 return true;
959 bool next_token_talloc(TALLOC_CTX *ctx,
960 const char **ptr,
961 char **pp_buff,
962 const char *sep)
964 return next_token_internal_talloc(ctx, ptr, pp_buff, sep, true);
968 * Get the next token from a string, return false if none found. Handles
969 * double-quotes. This version does not trim leading separator characters
970 * before looking for a token.
973 bool next_token_no_ltrim_talloc(TALLOC_CTX *ctx,
974 const char **ptr,
975 char **pp_buff,
976 const char *sep)
978 return next_token_internal_talloc(ctx, ptr, pp_buff, sep, false);
982 * Get the next token from a string, return False if none found.
983 * Handles double-quotes.
985 * Based on a routine by GJC@VILLAGE.COM.
986 * Extensively modified by Andrew.Tridgell@anu.edu.au
988 _PUBLIC_ bool next_token(const char **ptr,char *buff, const char *sep, size_t bufsize)
990 const char *s;
991 bool quoted;
992 size_t len=1;
994 if (!ptr)
995 return false;
997 s = *ptr;
999 /* default to simple separators */
1000 if (!sep)
1001 sep = " \t\n\r";
1003 /* find the first non sep char */
1004 while (*s && strchr_m(sep,*s))
1005 s++;
1007 /* nothing left? */
1008 if (!*s)
1009 return false;
1011 /* copy over the token */
1012 for (quoted = false; len < bufsize && *s && (quoted || !strchr_m(sep,*s)); s++) {
1013 if (*s == '\"') {
1014 quoted = !quoted;
1015 } else {
1016 len++;
1017 *buff++ = *s;
1021 *ptr = (*s) ? s+1 : s;
1022 *buff = 0;
1024 return true;
1027 struct anonymous_shared_header {
1028 union {
1029 size_t length;
1030 uint8_t pad[16];
1031 } u;
1034 /* Map a shared memory buffer of at least nelem counters. */
1035 void *anonymous_shared_allocate(size_t orig_bufsz)
1037 void *ptr;
1038 void *buf;
1039 size_t pagesz = getpagesize();
1040 size_t pagecnt;
1041 size_t bufsz = orig_bufsz;
1042 struct anonymous_shared_header *hdr;
1044 bufsz += sizeof(*hdr);
1046 /* round up to full pages */
1047 pagecnt = bufsz / pagesz;
1048 if (bufsz % pagesz) {
1049 pagecnt += 1;
1051 bufsz = pagesz * pagecnt;
1053 if (orig_bufsz >= bufsz) {
1054 /* integer wrap */
1055 errno = ENOMEM;
1056 return NULL;
1059 #ifdef MAP_ANON
1060 /* BSD */
1061 buf = mmap(NULL, bufsz, PROT_READ|PROT_WRITE, MAP_ANON|MAP_SHARED,
1062 -1 /* fd */, 0 /* offset */);
1063 #else
1064 buf = mmap(NULL, bufsz, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED,
1065 open("/dev/zero", O_RDWR), 0 /* offset */);
1066 #endif
1068 if (buf == MAP_FAILED) {
1069 return NULL;
1072 hdr = (struct anonymous_shared_header *)buf;
1073 hdr->u.length = bufsz;
1075 ptr = (void *)(&hdr[1]);
1077 return ptr;
1080 void *anonymous_shared_resize(void *ptr, size_t new_size, bool maymove)
1082 #ifdef HAVE_MREMAP
1083 void *buf;
1084 size_t pagesz = getpagesize();
1085 size_t pagecnt;
1086 size_t bufsz;
1087 struct anonymous_shared_header *hdr;
1088 int flags = 0;
1090 if (ptr == NULL) {
1091 errno = EINVAL;
1092 return NULL;
1095 hdr = (struct anonymous_shared_header *)ptr;
1096 hdr--;
1097 if (hdr->u.length > (new_size + sizeof(*hdr))) {
1098 errno = EINVAL;
1099 return NULL;
1102 bufsz = new_size + sizeof(*hdr);
1104 /* round up to full pages */
1105 pagecnt = bufsz / pagesz;
1106 if (bufsz % pagesz) {
1107 pagecnt += 1;
1109 bufsz = pagesz * pagecnt;
1111 if (new_size >= bufsz) {
1112 /* integer wrap */
1113 errno = ENOSPC;
1114 return NULL;
1117 if (bufsz <= hdr->u.length) {
1118 return ptr;
1121 if (maymove) {
1122 flags = MREMAP_MAYMOVE;
1125 buf = mremap(hdr, hdr->u.length, bufsz, flags);
1127 if (buf == MAP_FAILED) {
1128 errno = ENOSPC;
1129 return NULL;
1132 hdr = (struct anonymous_shared_header *)buf;
1133 hdr->u.length = bufsz;
1135 ptr = (void *)(&hdr[1]);
1137 return ptr;
1138 #else
1139 errno = ENOSPC;
1140 return NULL;
1141 #endif
1144 void anonymous_shared_free(void *ptr)
1146 struct anonymous_shared_header *hdr;
1148 if (ptr == NULL) {
1149 return;
1152 hdr = (struct anonymous_shared_header *)ptr;
1154 hdr--;
1156 munmap(hdr, hdr->u.length);
1159 #ifdef DEVELOPER
1160 /* used when you want a debugger started at a particular point in the
1161 code. Mostly useful in code that runs as a child process, where
1162 normal gdb attach is harder to organise.
1164 void samba_start_debugger(void)
1166 char *cmd = NULL;
1167 if (asprintf(&cmd, "xterm -e \"gdb --pid %u\"&", getpid()) == -1) {
1168 return;
1170 if (system(cmd) == -1) {
1171 free(cmd);
1172 return;
1174 free(cmd);
1175 sleep(2);
1177 #endif