s3/lib/ctdbd_conn: assert hdr following read/recv
[Samba.git] / lib / util / util.c
blob3bdeded5c1b6e29095f04ddfacea27235ac4fae8
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 Copyright (C) Swen Schillig 2019
12 This program is free software; you can redistribute it and/or modify
13 it under the terms of the GNU General Public License as published by
14 the Free Software Foundation; either version 3 of the License, or
15 (at your option) any later version.
17 This program is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 GNU General Public License for more details.
22 You should have received a copy of the GNU General Public License
23 along with this program. If not, see <http://www.gnu.org/licenses/>.
26 #include "replace.h"
27 #include <talloc.h>
28 #include "system/network.h"
29 #include "system/filesys.h"
30 #include "system/locale.h"
31 #include "system/shmem.h"
32 #include "system/passwd.h"
33 #include "system/time.h"
34 #include "system/wait.h"
35 #include "debug.h"
36 #include "samba_util.h"
37 #include "lib/util/select.h"
39 #undef malloc
40 #undef strcasecmp
41 #undef strncasecmp
42 #undef strdup
43 #undef realloc
44 #undef calloc
46 /**
47 * @file
48 * @brief Misc utility functions
51 /**
52 * Convert a string to an unsigned long integer
54 * @param nptr pointer to string which is to be converted
55 * @param endptr [optional] reference to remainder of the string
56 * @param base base of the numbering scheme
57 * @param err error occured during conversion
58 * @flags controlling conversion feature
59 * @result result of the conversion as provided by strtoul
61 * The following flags are supported
62 * SMB_STR_STANDARD # raise error if negative or non-numeric
63 * SMB_STR_ALLOW_NEGATIVE # allow strings with a leading "-"
64 * SMB_STR_FULL_STR_CONV # entire string must be converted
65 * SMB_STR_ALLOW_NO_CONVERSION # allow empty strings or non-numeric
66 * SMB_STR_GLIBC_STANDARD # act exactly as the standard glibc strtoul
68 * The following errors are detected
69 * - wrong base
70 * - value overflow
71 * - string with a leading "-" indicating a negative number
72 * - no conversion due to empty string or not representing a number
74 unsigned long int
75 smb_strtoul(const char *nptr, char **endptr, int base, int *err, int flags)
77 unsigned long int val;
78 int saved_errno = errno;
79 char *needle = NULL;
80 char *tmp_endptr = NULL;
82 errno = 0;
83 *err = 0;
85 val = strtoul(nptr, &tmp_endptr, base);
87 if (endptr != NULL) {
88 *endptr = tmp_endptr;
91 if (errno != 0) {
92 *err = errno;
93 errno = saved_errno;
94 return val;
97 if ((flags & SMB_STR_ALLOW_NO_CONVERSION) == 0) {
98 /* got an invalid number-string resulting in no conversion */
99 if (nptr == tmp_endptr) {
100 *err = EINVAL;
101 goto out;
105 if ((flags & SMB_STR_ALLOW_NEGATIVE ) == 0) {
106 /* did we convert a negative "number" ? */
107 needle = strchr(nptr, '-');
108 if (needle != NULL && needle < tmp_endptr) {
109 *err = EINVAL;
110 goto out;
114 if ((flags & SMB_STR_FULL_STR_CONV) != 0) {
115 /* did we convert the entire string ? */
116 if (tmp_endptr[0] != '\0') {
117 *err = EINVAL;
118 goto out;
122 out:
123 errno = saved_errno;
124 return val;
128 * Convert a string to an unsigned long long integer
130 * @param nptr pointer to string which is to be converted
131 * @param endptr [optional] reference to remainder of the string
132 * @param base base of the numbering scheme
133 * @param err error occured during conversion
134 * @flags controlling conversion feature
135 * @result result of the conversion as provided by strtoull
137 * The following flags are supported
138 * SMB_STR_STANDARD # raise error if negative or non-numeric
139 * SMB_STR_ALLOW_NEGATIVE # allow strings with a leading "-"
140 * SMB_STR_FULL_STR_CONV # entire string must be converted
141 * SMB_STR_ALLOW_NO_CONVERSION # allow empty strings or non-numeric
142 * SMB_STR_GLIBC_STANDARD # act exactly as the standard glibc strtoul
144 * The following errors are detected
145 * - wrong base
146 * - value overflow
147 * - string with a leading "-" indicating a negative number
148 * - no conversion due to empty string or not representing a number
150 unsigned long long int
151 smb_strtoull(const char *nptr, char **endptr, int base, int *err, int flags)
153 unsigned long long int val;
154 int saved_errno = errno;
155 char *needle = NULL;
156 char *tmp_endptr = NULL;
158 errno = 0;
159 *err = 0;
161 val = strtoull(nptr, &tmp_endptr, base);
163 if (endptr != NULL) {
164 *endptr = tmp_endptr;
167 if (errno != 0) {
168 *err = errno;
169 errno = saved_errno;
170 return val;
173 if ((flags & SMB_STR_ALLOW_NO_CONVERSION) == 0) {
174 /* got an invalid number-string resulting in no conversion */
175 if (nptr == tmp_endptr) {
176 *err = EINVAL;
177 goto out;
181 if ((flags & SMB_STR_ALLOW_NEGATIVE ) == 0) {
182 /* did we convert a negative "number" ? */
183 needle = strchr(nptr, '-');
184 if (needle != NULL && needle < tmp_endptr) {
185 *err = EINVAL;
186 goto out;
190 if ((flags & SMB_STR_FULL_STR_CONV) != 0) {
191 /* did we convert the entire string ? */
192 if (tmp_endptr[0] != '\0') {
193 *err = EINVAL;
194 goto out;
198 out:
199 errno = saved_errno;
200 return val;
204 Find a suitable temporary directory. The result should be copied immediately
205 as it may be overwritten by a subsequent call.
207 _PUBLIC_ const char *tmpdir(void)
209 char *p;
210 if ((p = getenv("TMPDIR")))
211 return p;
212 return "/tmp";
217 Create a tmp file, open it and immediately unlink it.
218 If dir is NULL uses tmpdir()
219 Returns the file descriptor or -1 on error.
221 int create_unlink_tmp(const char *dir)
223 size_t len = strlen(dir ? dir : (dir = tmpdir()));
224 char fname[len+25];
225 int fd;
226 mode_t mask;
228 len = snprintf(fname, sizeof(fname), "%s/listenerlock_XXXXXX", dir);
229 if (len >= sizeof(fname)) {
230 errno = ENOMEM;
231 return -1;
233 mask = umask(S_IRWXO | S_IRWXG);
234 fd = mkstemp(fname);
235 umask(mask);
236 if (fd == -1) {
237 return -1;
239 if (unlink(fname) == -1) {
240 int sys_errno = errno;
241 close(fd);
242 errno = sys_errno;
243 return -1;
245 return fd;
250 Check if a file exists - call vfs_file_exist for samba files.
252 _PUBLIC_ bool file_exist(const char *fname)
254 struct stat st;
256 if (stat(fname, &st) != 0) {
257 return false;
260 return ((S_ISREG(st.st_mode)) || (S_ISFIFO(st.st_mode)));
264 Check a files mod time.
267 _PUBLIC_ time_t file_modtime(const char *fname)
269 struct stat st;
271 if (stat(fname,&st) != 0)
272 return(0);
274 return(st.st_mtime);
278 Check file permissions.
281 _PUBLIC_ bool file_check_permissions(const char *fname,
282 uid_t uid,
283 mode_t file_perms,
284 struct stat *pst)
286 int ret;
287 struct stat st;
289 if (pst == NULL) {
290 pst = &st;
293 ZERO_STRUCTP(pst);
295 ret = stat(fname, pst);
296 if (ret != 0) {
297 DEBUG(0, ("stat failed on file '%s': %s\n",
298 fname, strerror(errno)));
299 return false;
302 if (pst->st_uid != uid && !uid_wrapper_enabled()) {
303 DEBUG(0, ("invalid ownership of file '%s': "
304 "owned by uid %u, should be %u\n",
305 fname, (unsigned int)pst->st_uid,
306 (unsigned int)uid));
307 return false;
310 if ((pst->st_mode & 0777) != file_perms) {
311 DEBUG(0, ("invalid permissions on file "
312 "'%s': has 0%o should be 0%o\n", fname,
313 (unsigned int)(pst->st_mode & 0777),
314 (unsigned int)file_perms));
315 return false;
318 return true;
322 Check if a directory exists.
325 _PUBLIC_ bool directory_exist(const char *dname)
327 struct stat st;
328 bool ret;
330 if (stat(dname,&st) != 0) {
331 return false;
334 ret = S_ISDIR(st.st_mode);
335 if(!ret)
336 errno = ENOTDIR;
337 return ret;
341 * Try to create the specified directory if it didn't exist.
343 * @retval true if the directory already existed
344 * or was successfully created.
346 _PUBLIC_ bool directory_create_or_exist(const char *dname,
347 mode_t dir_perms)
349 int ret;
350 mode_t old_umask;
352 /* Create directory */
353 old_umask = umask(0);
354 ret = mkdir(dname, dir_perms);
355 if (ret == -1 && errno != EEXIST) {
356 DBG_WARNING("mkdir failed on directory %s: %s\n",
357 dname,
358 strerror(errno));
359 umask(old_umask);
360 return false;
362 umask(old_umask);
364 if (ret != 0 && errno == EEXIST) {
365 struct stat sbuf;
367 ret = lstat(dname, &sbuf);
368 if (ret != 0) {
369 return false;
372 if (!S_ISDIR(sbuf.st_mode)) {
373 return false;
377 return true;
381 * @brief Try to create a specified directory if it doesn't exist.
383 * The function creates a directory with the given uid and permissions if it
384 * doesn't exist. If it exists it makes sure the uid and permissions are
385 * correct and it will fail if they are different.
387 * @param[in] dname The directory to create.
389 * @param[in] uid The uid the directory needs to belong too.
391 * @param[in] dir_perms The expected permissions of the directory.
393 * @return True on success, false on error.
395 _PUBLIC_ bool directory_create_or_exist_strict(const char *dname,
396 uid_t uid,
397 mode_t dir_perms)
399 struct stat st;
400 bool ok;
401 int rc;
403 ok = directory_create_or_exist(dname, dir_perms);
404 if (!ok) {
405 return false;
408 rc = lstat(dname, &st);
409 if (rc == -1) {
410 DEBUG(0, ("lstat failed on created directory %s: %s\n",
411 dname, strerror(errno)));
412 return false;
415 /* Check ownership and permission on existing directory */
416 if (!S_ISDIR(st.st_mode)) {
417 DEBUG(0, ("directory %s isn't a directory\n",
418 dname));
419 return false;
421 if (st.st_uid != uid && !uid_wrapper_enabled()) {
422 DBG_NOTICE("invalid ownership on directory "
423 "%s\n", dname);
424 return false;
426 if ((st.st_mode & 0777) != dir_perms) {
427 DEBUG(0, ("invalid permissions on directory "
428 "'%s': has 0%o should be 0%o\n", dname,
429 (unsigned int)(st.st_mode & 0777), (unsigned int)dir_perms));
430 return false;
433 return true;
438 Sleep for a specified number of milliseconds.
441 _PUBLIC_ void smb_msleep(unsigned int t)
443 sys_poll_intr(NULL, 0, t);
447 Get my own name, return in talloc'ed storage.
450 _PUBLIC_ char *get_myname(TALLOC_CTX *ctx)
452 char *p;
453 char hostname[HOST_NAME_MAX];
455 /* get my host name */
456 if (gethostname(hostname, sizeof(hostname)) == -1) {
457 DEBUG(0,("gethostname failed\n"));
458 return NULL;
461 /* Ensure null termination. */
462 hostname[sizeof(hostname)-1] = '\0';
464 /* split off any parts after an initial . */
465 p = strchr_m(hostname, '.');
466 if (p) {
467 *p = 0;
470 return talloc_strdup(ctx, hostname);
474 Check if a process exists. Does this work on all unixes?
477 _PUBLIC_ bool process_exists_by_pid(pid_t pid)
479 /* Doing kill with a non-positive pid causes messages to be
480 * sent to places we don't want. */
481 if (pid <= 0) {
482 return false;
484 return(kill(pid,0) == 0 || errno != ESRCH);
488 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
489 is dealt with in posix.c
492 _PUBLIC_ bool fcntl_lock(int fd, int op, off_t offset, off_t count, int type)
494 struct flock lock;
495 int ret;
497 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
499 lock.l_type = type;
500 lock.l_whence = SEEK_SET;
501 lock.l_start = offset;
502 lock.l_len = count;
503 lock.l_pid = 0;
505 ret = fcntl(fd,op,&lock);
507 if (ret == -1 && errno != 0)
508 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
510 /* a lock query */
511 if (op == F_GETLK) {
512 if ((ret != -1) &&
513 (lock.l_type != F_UNLCK) &&
514 (lock.l_pid != 0) &&
515 (lock.l_pid != getpid())) {
516 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
517 return true;
520 /* it must be not locked or locked by me */
521 return false;
524 /* a lock set or unset */
525 if (ret == -1) {
526 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
527 (double)offset,(double)count,op,type,strerror(errno)));
528 return false;
531 /* everything went OK */
532 DEBUG(8,("fcntl_lock: Lock call successful\n"));
534 return true;
537 struct debug_channel_level {
538 int channel;
539 int level;
542 static void debugadd_channel_cb(const char *buf, void *private_data)
544 struct debug_channel_level *dcl =
545 (struct debug_channel_level *)private_data;
547 DEBUGADDC(dcl->channel, dcl->level,("%s", buf));
550 static void debugadd_cb(const char *buf, void *private_data)
552 int *plevel = (int *)private_data;
553 DEBUGADD(*plevel, ("%s", buf));
556 void print_asc_cb(const uint8_t *buf, int len,
557 void (*cb)(const char *buf, void *private_data),
558 void *private_data)
560 int i;
561 char s[2];
562 s[1] = 0;
564 for (i=0; i<len; i++) {
565 s[0] = isprint(buf[i]) ? buf[i] : '.';
566 cb(s, private_data);
570 void print_asc(int level, const uint8_t *buf,int len)
572 print_asc_cb(buf, len, debugadd_cb, &level);
576 * Write dump of binary data to a callback
578 void dump_data_cb(const uint8_t *buf, int len,
579 bool omit_zero_bytes,
580 void (*cb)(const char *buf, void *private_data),
581 void *private_data)
583 int i=0;
584 bool skipped = false;
585 char tmp[16];
587 if (len<=0) return;
589 for (i=0;i<len;) {
591 if (i%16 == 0) {
592 if ((omit_zero_bytes == true) &&
593 (i > 0) &&
594 (len > i+16) &&
595 all_zero(&buf[i], 16))
597 i +=16;
598 continue;
601 if (i<len) {
602 snprintf(tmp, sizeof(tmp), "[%04X] ", i);
603 cb(tmp, private_data);
607 snprintf(tmp, sizeof(tmp), "%02X ", (int)buf[i]);
608 cb(tmp, private_data);
609 i++;
610 if (i%8 == 0) {
611 cb(" ", private_data);
613 if (i%16 == 0) {
615 print_asc_cb(&buf[i-16], 8, cb, private_data);
616 cb(" ", private_data);
617 print_asc_cb(&buf[i-8], 8, cb, private_data);
618 cb("\n", private_data);
620 if ((omit_zero_bytes == true) &&
621 (len > i+16) &&
622 all_zero(&buf[i], 16)) {
623 if (!skipped) {
624 cb("skipping zero buffer bytes\n",
625 private_data);
626 skipped = true;
632 if (i%16) {
633 int n;
634 n = 16 - (i%16);
635 cb(" ", private_data);
636 if (n>8) {
637 cb(" ", private_data);
639 while (n--) {
640 cb(" ", private_data);
642 n = MIN(8,i%16);
643 print_asc_cb(&buf[i-(i%16)], n, cb, private_data);
644 cb(" ", private_data);
645 n = (i%16) - n;
646 if (n>0) {
647 print_asc_cb(&buf[i-n], n, cb, private_data);
649 cb("\n", private_data);
655 * Write dump of binary data to the log file.
657 * The data is only written if the log level is at least level.
659 _PUBLIC_ void dump_data(int level, const uint8_t *buf, int len)
661 if (!DEBUGLVL(level)) {
662 return;
664 dump_data_cb(buf, len, false, debugadd_cb, &level);
668 * Write dump of binary data to the log file.
670 * The data is only written if the log level is at least level for
671 * debug class dbgc_class.
673 _PUBLIC_ void dump_data_dbgc(int dbgc_class, int level, const uint8_t *buf, int len)
675 struct debug_channel_level dcl = { dbgc_class, level };
677 if (!DEBUGLVLC(dbgc_class, level)) {
678 return;
680 dump_data_cb(buf, len, false, debugadd_channel_cb, &dcl);
684 * Write dump of binary data to the log file.
686 * The data is only written if the log level is at least level.
687 * 16 zero bytes in a row are omitted
689 _PUBLIC_ void dump_data_skip_zeros(int level, const uint8_t *buf, int len)
691 if (!DEBUGLVL(level)) {
692 return;
694 dump_data_cb(buf, len, true, debugadd_cb, &level);
697 static void fprintf_cb(const char *buf, void *private_data)
699 FILE *f = (FILE *)private_data;
700 fprintf(f, "%s", buf);
703 void dump_data_file(const uint8_t *buf, int len, bool omit_zero_bytes,
704 FILE *f)
706 dump_data_cb(buf, len, omit_zero_bytes, fprintf_cb, f);
710 malloc that aborts with smb_panic on fail or zero size.
713 _PUBLIC_ void *smb_xmalloc(size_t size)
715 void *p;
716 if (size == 0)
717 smb_panic("smb_xmalloc: called with zero size.\n");
718 if ((p = malloc(size)) == NULL)
719 smb_panic("smb_xmalloc: malloc fail.\n");
720 return p;
724 Memdup with smb_panic on fail.
727 _PUBLIC_ void *smb_xmemdup(const void *p, size_t size)
729 void *p2;
730 p2 = smb_xmalloc(size);
731 memcpy(p2, p, size);
732 return p2;
736 strdup that aborts on malloc fail.
739 char *smb_xstrdup(const char *s)
741 #if defined(PARANOID_MALLOC_CHECKER)
742 #ifdef strdup
743 #undef strdup
744 #endif
745 #endif
747 #ifndef HAVE_STRDUP
748 #define strdup rep_strdup
749 #endif
751 char *s1 = strdup(s);
752 #if defined(PARANOID_MALLOC_CHECKER)
753 #ifdef strdup
754 #undef strdup
755 #endif
756 #define strdup(s) __ERROR_DONT_USE_STRDUP_DIRECTLY
757 #endif
758 if (!s1) {
759 smb_panic("smb_xstrdup: malloc failed");
761 return s1;
766 strndup that aborts on malloc fail.
769 char *smb_xstrndup(const char *s, size_t n)
771 #if defined(PARANOID_MALLOC_CHECKER)
772 #ifdef strndup
773 #undef strndup
774 #endif
775 #endif
777 #if (defined(BROKEN_STRNDUP) || !defined(HAVE_STRNDUP))
778 #undef HAVE_STRNDUP
779 #define strndup rep_strndup
780 #endif
782 char *s1 = strndup(s, n);
783 #if defined(PARANOID_MALLOC_CHECKER)
784 #ifdef strndup
785 #undef strndup
786 #endif
787 #define strndup(s,n) __ERROR_DONT_USE_STRNDUP_DIRECTLY
788 #endif
789 if (!s1) {
790 smb_panic("smb_xstrndup: malloc failed");
792 return s1;
798 Like strdup but for memory.
801 _PUBLIC_ void *smb_memdup(const void *p, size_t size)
803 void *p2;
804 if (size == 0)
805 return NULL;
806 p2 = malloc(size);
807 if (!p2)
808 return NULL;
809 memcpy(p2, p, size);
810 return p2;
814 * Write a password to the log file.
816 * @note Only actually does something if DEBUG_PASSWORD was defined during
817 * compile-time.
819 _PUBLIC_ void dump_data_pw(const char *msg, const uint8_t * data, size_t len)
821 #ifdef DEBUG_PASSWORD
822 DEBUG(11, ("%s", msg));
823 if (data != NULL && len > 0)
825 dump_data(11, data, len);
827 #endif
832 * see if a range of memory is all zero. A NULL pointer is considered
833 * to be all zero
835 _PUBLIC_ bool all_zero(const uint8_t *ptr, size_t size)
837 size_t i;
838 if (!ptr) return true;
839 for (i=0;i<size;i++) {
840 if (ptr[i]) return false;
842 return true;
846 realloc an array, checking for integer overflow in the array size
848 _PUBLIC_ void *realloc_array(void *ptr, size_t el_size, unsigned count, bool free_on_fail)
850 #define MAX_MALLOC_SIZE 0x7fffffff
851 if (count == 0 ||
852 count >= MAX_MALLOC_SIZE/el_size) {
853 if (free_on_fail)
854 SAFE_FREE(ptr);
855 return NULL;
857 if (!ptr) {
858 return malloc(el_size * count);
860 return realloc(ptr, el_size * count);
863 /****************************************************************************
864 Type-safe malloc.
865 ****************************************************************************/
867 void *malloc_array(size_t el_size, unsigned int count)
869 return realloc_array(NULL, el_size, count, false);
872 /****************************************************************************
873 Type-safe memalign
874 ****************************************************************************/
876 void *memalign_array(size_t el_size, size_t align, unsigned int count)
878 if (el_size == 0 || count >= MAX_MALLOC_SIZE/el_size) {
879 return NULL;
882 return memalign(align, el_size*count);
885 /****************************************************************************
886 Type-safe calloc.
887 ****************************************************************************/
889 void *calloc_array(size_t size, size_t nmemb)
891 if (nmemb >= MAX_MALLOC_SIZE/size) {
892 return NULL;
894 if (size == 0 || nmemb == 0) {
895 return NULL;
897 return calloc(nmemb, size);
901 Trim the specified elements off the front and back of a string.
903 _PUBLIC_ bool trim_string(char *s, const char *front, const char *back)
905 bool ret = false;
906 size_t front_len;
907 size_t back_len;
908 size_t len;
910 /* Ignore null or empty strings. */
911 if (!s || (s[0] == '\0')) {
912 return false;
914 len = strlen(s);
916 front_len = front? strlen(front) : 0;
917 back_len = back? strlen(back) : 0;
919 if (front_len) {
920 size_t front_trim = 0;
922 while (strncmp(s+front_trim, front, front_len)==0) {
923 front_trim += front_len;
925 if (front_trim > 0) {
926 /* Must use memmove here as src & dest can
927 * easily overlap. Found by valgrind. JRA. */
928 memmove(s, s+front_trim, (len-front_trim)+1);
929 len -= front_trim;
930 ret=true;
934 if (back_len) {
935 while ((len >= back_len) && strncmp(s+len-back_len,back,back_len)==0) {
936 s[len-back_len]='\0';
937 len -= back_len;
938 ret=true;
941 return ret;
945 Find the number of 'c' chars in a string
947 _PUBLIC_ _PURE_ size_t count_chars(const char *s, char c)
949 size_t count = 0;
951 while (*s) {
952 if (*s == c) count++;
953 s ++;
956 return count;
960 * Routine to get hex characters and turn them into a byte array.
961 * the array can be variable length.
962 * - "0xnn" or "0Xnn" is specially catered for.
963 * - The first non-hex-digit character (apart from possibly leading "0x"
964 * finishes the conversion and skips the rest of the input.
965 * - A single hex-digit character at the end of the string is skipped.
967 * valid examples: "0A5D15"; "0x123456"
969 _PUBLIC_ size_t strhex_to_str(char *p, size_t p_len, const char *strhex, size_t strhex_len)
971 size_t i = 0;
972 size_t num_chars = 0;
973 uint8_t lonybble, hinybble;
974 const char *hexchars = "0123456789ABCDEF";
975 char *p1 = NULL, *p2 = NULL;
977 /* skip leading 0x prefix */
978 if (strncasecmp(strhex, "0x", 2) == 0) {
979 i += 2; /* skip two chars */
982 for (; i+1 < strhex_len && strhex[i] != 0 && strhex[i+1] != 0; i++) {
983 p1 = strchr(hexchars, toupper((unsigned char)strhex[i]));
984 if (p1 == NULL) {
985 break;
988 i++; /* next hex digit */
990 p2 = strchr(hexchars, toupper((unsigned char)strhex[i]));
991 if (p2 == NULL) {
992 break;
995 /* get the two nybbles */
996 hinybble = PTR_DIFF(p1, hexchars);
997 lonybble = PTR_DIFF(p2, hexchars);
999 if (num_chars >= p_len) {
1000 break;
1003 p[num_chars] = (hinybble << 4) | lonybble;
1004 num_chars++;
1006 p1 = NULL;
1007 p2 = NULL;
1009 return num_chars;
1013 * Parse a hex string and return a data blob.
1015 _PUBLIC_ _PURE_ DATA_BLOB strhex_to_data_blob(TALLOC_CTX *mem_ctx, const char *strhex)
1017 DATA_BLOB ret_blob = data_blob_talloc(mem_ctx, NULL, strlen(strhex)/2+1);
1019 ret_blob.length = strhex_to_str((char *)ret_blob.data, ret_blob.length,
1020 strhex,
1021 strlen(strhex));
1023 return ret_blob;
1027 * Parse a hex dump and return a data blob. Hex dump is structured as
1028 * is generated from dump_data_cb() elsewhere in this file
1031 _PUBLIC_ _PURE_ DATA_BLOB hexdump_to_data_blob(TALLOC_CTX *mem_ctx, const char *hexdump, size_t hexdump_len)
1033 DATA_BLOB ret_blob = { 0 };
1034 size_t i = 0;
1035 size_t char_count = 0;
1036 /* hexdump line length is 77 chars long. We then use the ASCII representation of the bytes
1037 * at the end of the final line to calculate how many are in that line, minus the extra space
1038 * and newline. */
1039 size_t hexdump_byte_count = (16 * (hexdump_len / 77));
1040 if (hexdump_len % 77) {
1041 hexdump_byte_count += ((hexdump_len % 77) - 59 - 2);
1044 ret_blob = data_blob_talloc(mem_ctx, NULL, hexdump_byte_count+1);
1045 for (; i+1 < hexdump_len && hexdump[i] != 0 && hexdump[i+1] != 0; i++) {
1046 if ((i%77) == 0)
1047 i += 7; /* Skip the offset at the start of the line */
1048 if ((i%77) < 56) { /* position 56 is after both hex chunks */
1049 if (hexdump[i] != ' ') {
1050 char_count += strhex_to_str((char *)&ret_blob.data[char_count],
1051 hexdump_byte_count - char_count,
1052 &hexdump[i], 2);
1053 i += 2;
1054 } else {
1055 i++;
1057 } else {
1058 i++;
1061 ret_blob.length = char_count;
1063 return ret_blob;
1067 * Print a buf in hex. Assumes dst is at least (srclen*2)+1 large.
1069 _PUBLIC_ void hex_encode_buf(char *dst, const uint8_t *src, size_t srclen)
1071 size_t i;
1072 for (i=0; i<srclen; i++) {
1073 snprintf(dst + i*2, 3, "%02X", src[i]);
1076 * Ensure 0-termination for 0-length buffers
1078 dst[srclen*2] = '\0';
1082 * talloc version of hex_encode_buf()
1084 _PUBLIC_ char *hex_encode_talloc(TALLOC_CTX *mem_ctx, const unsigned char *buff_in, size_t len)
1086 char *hex_buffer;
1088 hex_buffer = talloc_array(mem_ctx, char, (len*2)+1);
1089 if (!hex_buffer) {
1090 return NULL;
1092 hex_encode_buf(hex_buffer, buff_in, len);
1093 talloc_set_name_const(hex_buffer, hex_buffer);
1094 return hex_buffer;
1098 varient of strcmp() that handles NULL ptrs
1100 _PUBLIC_ int strcmp_safe(const char *s1, const char *s2)
1102 if (s1 == s2) {
1103 return 0;
1105 if (s1 == NULL || s2 == NULL) {
1106 return s1?-1:1;
1108 return strcmp(s1, s2);
1113 return the number of bytes occupied by a buffer in ASCII format
1114 the result includes the null termination
1115 limited by 'n' bytes
1117 _PUBLIC_ size_t ascii_len_n(const char *src, size_t n)
1119 size_t len;
1121 len = strnlen(src, n);
1122 if (len+1 <= n) {
1123 len += 1;
1126 return len;
1129 struct anonymous_shared_header {
1130 union {
1131 size_t length;
1132 uint8_t pad[16];
1133 } u;
1136 /* Map a shared memory buffer of at least nelem counters. */
1137 void *anonymous_shared_allocate(size_t orig_bufsz)
1139 void *ptr;
1140 void *buf;
1141 size_t pagesz = getpagesize();
1142 size_t pagecnt;
1143 size_t bufsz = orig_bufsz;
1144 struct anonymous_shared_header *hdr;
1146 bufsz += sizeof(*hdr);
1148 /* round up to full pages */
1149 pagecnt = bufsz / pagesz;
1150 if (bufsz % pagesz) {
1151 pagecnt += 1;
1153 bufsz = pagesz * pagecnt;
1155 if (orig_bufsz >= bufsz) {
1156 /* integer wrap */
1157 errno = ENOMEM;
1158 return NULL;
1161 #ifdef MAP_ANON
1162 /* BSD */
1163 buf = mmap(NULL, bufsz, PROT_READ|PROT_WRITE, MAP_ANON|MAP_SHARED,
1164 -1 /* fd */, 0 /* offset */);
1165 #else
1167 int saved_errno;
1168 int fd;
1170 fd = open("/dev/zero", O_RDWR);
1171 if (fd == -1) {
1172 return NULL;
1175 buf = mmap(NULL, bufsz, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED,
1176 fd, 0 /* offset */);
1177 saved_errno = errno;
1178 close(fd);
1179 errno = saved_errno;
1181 #endif
1183 if (buf == MAP_FAILED) {
1184 return NULL;
1187 hdr = (struct anonymous_shared_header *)buf;
1188 hdr->u.length = bufsz;
1190 ptr = (void *)(&hdr[1]);
1192 return ptr;
1195 void *anonymous_shared_resize(void *ptr, size_t new_size, bool maymove)
1197 #ifdef HAVE_MREMAP
1198 void *buf;
1199 size_t pagesz = getpagesize();
1200 size_t pagecnt;
1201 size_t bufsz;
1202 struct anonymous_shared_header *hdr;
1203 int flags = 0;
1205 if (ptr == NULL) {
1206 errno = EINVAL;
1207 return NULL;
1210 hdr = (struct anonymous_shared_header *)ptr;
1211 hdr--;
1212 if (hdr->u.length > (new_size + sizeof(*hdr))) {
1213 errno = EINVAL;
1214 return NULL;
1217 bufsz = new_size + sizeof(*hdr);
1219 /* round up to full pages */
1220 pagecnt = bufsz / pagesz;
1221 if (bufsz % pagesz) {
1222 pagecnt += 1;
1224 bufsz = pagesz * pagecnt;
1226 if (new_size >= bufsz) {
1227 /* integer wrap */
1228 errno = ENOSPC;
1229 return NULL;
1232 if (bufsz <= hdr->u.length) {
1233 return ptr;
1236 if (maymove) {
1237 flags = MREMAP_MAYMOVE;
1240 buf = mremap(hdr, hdr->u.length, bufsz, flags);
1242 if (buf == MAP_FAILED) {
1243 errno = ENOSPC;
1244 return NULL;
1247 hdr = (struct anonymous_shared_header *)buf;
1248 hdr->u.length = bufsz;
1250 ptr = (void *)(&hdr[1]);
1252 return ptr;
1253 #else
1254 errno = ENOSPC;
1255 return NULL;
1256 #endif
1259 void anonymous_shared_free(void *ptr)
1261 struct anonymous_shared_header *hdr;
1263 if (ptr == NULL) {
1264 return;
1267 hdr = (struct anonymous_shared_header *)ptr;
1269 hdr--;
1271 munmap(hdr, hdr->u.length);
1274 #ifdef DEVELOPER
1275 /* used when you want a debugger started at a particular point in the
1276 code. Mostly useful in code that runs as a child process, where
1277 normal gdb attach is harder to organise.
1279 void samba_start_debugger(void)
1281 char *cmd = NULL;
1282 if (asprintf(&cmd, "xterm -e \"gdb --pid %u\"&", getpid()) == -1) {
1283 return;
1285 if (system(cmd) == -1) {
1286 free(cmd);
1287 return;
1289 free(cmd);
1290 sleep(2);
1292 #endif