lib/util: Reduce sum variable to uint8_t
[Samba.git] / lib / util / util.c
blob0747f3d7a1b0a973801b1b3683127cf0fffbfb82
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"
38 #include <libgen.h>
40 #ifdef HAVE_SYS_PRCTL_H
41 #include <sys/prctl.h>
42 #endif
44 #undef malloc
45 #undef strcasecmp
46 #undef strncasecmp
47 #undef strdup
48 #undef realloc
49 #undef calloc
51 /**
52 * @file
53 * @brief Misc utility functions
56 /**
57 Find a suitable temporary directory. The result should be copied immediately
58 as it may be overwritten by a subsequent call.
59 **/
60 _PUBLIC_ const char *tmpdir(void)
62 char *p;
63 if ((p = getenv("TMPDIR")))
64 return p;
65 return "/tmp";
69 /**
70 Create a tmp file, open it and immediately unlink it.
71 If dir is NULL uses tmpdir()
72 Returns the file descriptor or -1 on error.
73 **/
74 int create_unlink_tmp(const char *dir)
76 size_t len = strlen(dir ? dir : (dir = tmpdir()));
77 char fname[len+25];
78 int fd;
79 mode_t mask;
81 len = snprintf(fname, sizeof(fname), "%s/listenerlock_XXXXXX", dir);
82 if (len >= sizeof(fname)) {
83 errno = ENOMEM;
84 return -1;
86 mask = umask(S_IRWXO | S_IRWXG);
87 fd = mkstemp(fname);
88 umask(mask);
89 if (fd == -1) {
90 return -1;
92 if (unlink(fname) == -1) {
93 int sys_errno = errno;
94 close(fd);
95 errno = sys_errno;
96 return -1;
98 return fd;
103 Check if a file exists - call vfs_file_exist for samba files.
105 _PUBLIC_ bool file_exist(const char *fname)
107 struct stat st;
109 if (stat(fname, &st) != 0) {
110 return false;
113 return ((S_ISREG(st.st_mode)) || (S_ISFIFO(st.st_mode)));
117 Check a files mod time.
120 _PUBLIC_ time_t file_modtime(const char *fname)
122 struct stat st;
124 if (stat(fname,&st) != 0)
125 return(0);
127 return(st.st_mtime);
131 Check file permissions.
134 _PUBLIC_ bool file_check_permissions(const char *fname,
135 uid_t uid,
136 mode_t file_perms,
137 struct stat *pst)
139 int ret;
140 struct stat st;
142 if (pst == NULL) {
143 pst = &st;
146 ZERO_STRUCTP(pst);
148 ret = stat(fname, pst);
149 if (ret != 0) {
150 DEBUG(0, ("stat failed on file '%s': %s\n",
151 fname, strerror(errno)));
152 return false;
155 if (pst->st_uid != uid && !uid_wrapper_enabled()) {
156 DEBUG(0, ("invalid ownership of file '%s': "
157 "owned by uid %u, should be %u\n",
158 fname, (unsigned int)pst->st_uid,
159 (unsigned int)uid));
160 return false;
163 if ((pst->st_mode & 0777) != file_perms) {
164 DEBUG(0, ("invalid permissions on file "
165 "'%s': has 0%o should be 0%o\n", fname,
166 (unsigned int)(pst->st_mode & 0777),
167 (unsigned int)file_perms));
168 return false;
171 return true;
175 Check if a directory exists.
178 _PUBLIC_ bool directory_exist(const char *dname)
180 struct stat st;
181 bool ret;
183 if (stat(dname,&st) != 0) {
184 return false;
187 ret = S_ISDIR(st.st_mode);
188 if(!ret)
189 errno = ENOTDIR;
190 return ret;
194 * Try to create the specified directory if it didn't exist.
195 * A symlink to a directory is also accepted as a valid existing directory.
197 * @retval true if the directory already existed
198 * or was successfully created.
200 _PUBLIC_ bool directory_create_or_exist(const char *dname,
201 mode_t dir_perms)
203 int ret;
204 mode_t old_umask;
206 /* Create directory */
207 old_umask = umask(0);
208 ret = mkdir(dname, dir_perms);
209 if (ret == -1 && errno != EEXIST) {
210 int dbg_level = geteuid() == 0 ? DBGLVL_ERR : DBGLVL_NOTICE;
212 DBG_PREFIX(dbg_level,
213 ("mkdir failed on directory %s: %s\n",
214 dname,
215 strerror(errno)));
216 umask(old_umask);
217 return false;
219 umask(old_umask);
221 if (ret != 0 && errno == EEXIST) {
222 struct stat sbuf;
224 ret = lstat(dname, &sbuf);
225 if (ret != 0) {
226 return false;
229 if (S_ISDIR(sbuf.st_mode)) {
230 return true;
233 if (S_ISLNK(sbuf.st_mode)) {
234 ret = stat(dname, &sbuf);
235 if (ret != 0) {
236 return false;
239 if (S_ISDIR(sbuf.st_mode)) {
240 return true;
244 return false;
247 return true;
250 _PUBLIC_ bool directory_create_or_exists_recursive(
251 const char *dname,
252 mode_t dir_perms)
254 bool ok;
256 ok = directory_create_or_exist(dname, dir_perms);
257 if (!ok) {
258 if (!directory_exist(dname)) {
259 char tmp[PATH_MAX] = {0};
260 char *parent = NULL;
261 size_t n;
263 /* Use the null context */
264 n = strlcpy(tmp, dname, sizeof(tmp));
265 if (n < strlen(dname)) {
266 DBG_ERR("Path too long!\n");
267 return false;
270 parent = dirname(tmp);
271 if (parent == NULL) {
272 DBG_ERR("Failed to create dirname!\n");
273 return false;
276 ok = directory_create_or_exists_recursive(parent,
277 dir_perms);
278 if (!ok) {
279 return false;
282 ok = directory_create_or_exist(dname, dir_perms);
286 return ok;
290 * @brief Try to create a specified directory if it doesn't exist.
292 * The function creates a directory with the given uid and permissions if it
293 * doesn't exist. If it exists it makes sure the uid and permissions are
294 * correct and it will fail if they are different.
296 * @param[in] dname The directory to create.
298 * @param[in] uid The uid the directory needs to belong too.
300 * @param[in] dir_perms The expected permissions of the directory.
302 * @return True on success, false on error.
304 _PUBLIC_ bool directory_create_or_exist_strict(const char *dname,
305 uid_t uid,
306 mode_t dir_perms)
308 struct stat st;
309 bool ok;
310 int rc;
312 ok = directory_create_or_exist(dname, dir_perms);
313 if (!ok) {
314 return false;
317 rc = lstat(dname, &st);
318 if (rc == -1) {
319 DEBUG(0, ("lstat failed on created directory %s: %s\n",
320 dname, strerror(errno)));
321 return false;
324 /* Check ownership and permission on existing directory */
325 if (!S_ISDIR(st.st_mode)) {
326 DEBUG(0, ("directory %s isn't a directory\n",
327 dname));
328 return false;
330 if (st.st_uid != uid && !uid_wrapper_enabled()) {
331 DBG_NOTICE("invalid ownership on directory "
332 "%s\n", dname);
333 return false;
335 if ((st.st_mode & 0777) != dir_perms) {
336 DEBUG(0, ("invalid permissions on directory "
337 "'%s': has 0%o should be 0%o\n", dname,
338 (unsigned int)(st.st_mode & 0777), (unsigned int)dir_perms));
339 return false;
342 return true;
347 Sleep for a specified number of milliseconds.
350 _PUBLIC_ void smb_msleep(unsigned int t)
352 sys_poll_intr(NULL, 0, t);
356 Get my own name, return in talloc'ed storage.
359 _PUBLIC_ char *get_myname(TALLOC_CTX *ctx)
361 char *p;
362 char hostname[HOST_NAME_MAX];
364 /* get my host name */
365 if (gethostname(hostname, sizeof(hostname)) == -1) {
366 DEBUG(0,("gethostname failed\n"));
367 return NULL;
370 /* Ensure null termination. */
371 hostname[sizeof(hostname)-1] = '\0';
373 /* split off any parts after an initial . */
374 p = strchr_m(hostname, '.');
375 if (p) {
376 *p = 0;
379 return talloc_strdup(ctx, hostname);
383 Check if a process exists. Does this work on all unixes?
386 _PUBLIC_ bool process_exists_by_pid(pid_t pid)
388 /* Doing kill with a non-positive pid causes messages to be
389 * sent to places we don't want. */
390 if (pid <= 0) {
391 return false;
393 return(kill(pid,0) == 0 || errno != ESRCH);
397 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
398 is dealt with in posix.c
401 _PUBLIC_ bool fcntl_lock(int fd, int op, off_t offset, off_t count, int type)
403 struct flock lock;
404 int ret;
406 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
408 lock.l_type = type;
409 lock.l_whence = SEEK_SET;
410 lock.l_start = offset;
411 lock.l_len = count;
412 lock.l_pid = 0;
414 ret = fcntl(fd,op,&lock);
416 if (ret == -1 && errno != 0)
417 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
419 /* a lock query */
420 if (op == F_GETLK) {
421 if ((ret != -1) &&
422 (lock.l_type != F_UNLCK) &&
423 (lock.l_pid != 0) &&
424 (lock.l_pid != getpid())) {
425 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
426 return true;
429 /* it must be not locked or locked by me */
430 return false;
433 /* a lock set or unset */
434 if (ret == -1) {
435 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
436 (double)offset,(double)count,op,type,strerror(errno)));
437 return false;
440 /* everything went OK */
441 DEBUG(8,("fcntl_lock: Lock call successful\n"));
443 return true;
446 struct debug_channel_level {
447 int channel;
448 int level;
451 static void debugadd_channel_cb(const char *buf, void *private_data)
453 struct debug_channel_level *dcl =
454 (struct debug_channel_level *)private_data;
456 DEBUGADDC(dcl->channel, dcl->level,("%s", buf));
459 static void debugadd_cb(const char *buf, void *private_data)
461 int *plevel = (int *)private_data;
462 DEBUGADD(*plevel, ("%s", buf));
465 void print_asc_cb(const uint8_t *buf, int len,
466 void (*cb)(const char *buf, void *private_data),
467 void *private_data)
469 int i;
470 char s[2];
471 s[1] = 0;
473 for (i=0; i<len; i++) {
474 s[0] = isprint(buf[i]) ? buf[i] : '.';
475 cb(s, private_data);
479 void print_asc(int level, const uint8_t *buf,int len)
481 print_asc_cb(buf, len, debugadd_cb, &level);
484 static void dump_data_block16(const char *prefix, size_t idx,
485 const uint8_t *buf, size_t len,
486 void (*cb)(const char *buf, void *private_data),
487 void *private_data)
489 char tmp[16];
490 size_t i;
492 SMB_ASSERT(len >= 0 && len <= 16);
494 snprintf(tmp, sizeof(tmp), "%s[%04zX]", prefix, idx);
495 cb(tmp, private_data);
497 for (i=0; i<16; i++) {
498 if (i == 8) {
499 cb(" ", private_data);
501 if (i < len) {
502 snprintf(tmp, sizeof(tmp), " %02X", (int)buf[i]);
503 } else {
504 snprintf(tmp, sizeof(tmp), " ");
506 cb(tmp, private_data);
509 cb(" ", private_data);
511 if (len == 0) {
512 cb("EMPTY BLOCK\n", private_data);
513 return;
516 for (i=0; i<len; i++) {
517 if (i == 8) {
518 cb(" ", private_data);
520 print_asc_cb(&buf[i], 1, cb, private_data);
523 cb("\n", private_data);
527 * Write dump of binary data to a callback
529 void dump_data_cb(const uint8_t *buf, int len,
530 bool omit_zero_bytes,
531 void (*cb)(const char *buf, void *private_data),
532 void *private_data)
534 int i=0;
535 bool skipped = false;
537 if (len<=0) return;
539 for (i=0;i<len;i+=16) {
540 size_t remaining_len = len - i;
541 size_t this_len = MIN(remaining_len, 16);
542 const uint8_t *this_buf = &buf[i];
544 if ((omit_zero_bytes == true) &&
545 (i > 0) && (remaining_len > 16) &&
546 (this_len == 16) && all_zero(this_buf, 16))
548 if (!skipped) {
549 cb("skipping zero buffer bytes\n",
550 private_data);
551 skipped = true;
553 continue;
556 skipped = false;
557 dump_data_block16("", i, this_buf, this_len,
558 cb, private_data);
563 * Write dump of binary data to the log file.
565 * The data is only written if the log level is at least level.
567 _PUBLIC_ void dump_data(int level, const uint8_t *buf, int len)
569 if (!DEBUGLVL(level)) {
570 return;
572 dump_data_cb(buf, len, false, debugadd_cb, &level);
576 * Write dump of binary data to the log file.
578 * The data is only written if the log level is at least level for
579 * debug class dbgc_class.
581 _PUBLIC_ void dump_data_dbgc(int dbgc_class, int level, const uint8_t *buf, int len)
583 struct debug_channel_level dcl = { dbgc_class, level };
585 if (!DEBUGLVLC(dbgc_class, level)) {
586 return;
588 dump_data_cb(buf, len, false, debugadd_channel_cb, &dcl);
592 * Write dump of binary data to the log file.
594 * The data is only written if the log level is at least level.
595 * 16 zero bytes in a row are omitted
597 _PUBLIC_ void dump_data_skip_zeros(int level, const uint8_t *buf, int len)
599 if (!DEBUGLVL(level)) {
600 return;
602 dump_data_cb(buf, len, true, debugadd_cb, &level);
605 static void fprintf_cb(const char *buf, void *private_data)
607 FILE *f = (FILE *)private_data;
608 fprintf(f, "%s", buf);
611 void dump_data_file(const uint8_t *buf, int len, bool omit_zero_bytes,
612 FILE *f)
614 dump_data_cb(buf, len, omit_zero_bytes, fprintf_cb, f);
618 * Write dump of compared binary data to a callback
620 void dump_data_diff_cb(const uint8_t *buf1, size_t len1,
621 const uint8_t *buf2, size_t len2,
622 bool omit_zero_bytes,
623 void (*cb)(const char *buf, void *private_data),
624 void *private_data)
626 size_t len = MAX(len1, len2);
627 size_t i;
628 bool skipped = false;
630 for (i=0; i<len; i+=16) {
631 size_t remaining_len = len - i;
632 size_t remaining_len1 = 0;
633 size_t this_len1 = 0;
634 const uint8_t *this_buf1 = NULL;
635 size_t remaining_len2 = 0;
636 size_t this_len2 = 0;
637 const uint8_t *this_buf2 = NULL;
639 if (i < len1) {
640 remaining_len1 = len1 - i;
641 this_len1 = MIN(remaining_len1, 16);
642 this_buf1 = &buf1[i];
644 if (i < len2) {
645 remaining_len2 = len2 - i;
646 this_len2 = MIN(remaining_len2, 16);
647 this_buf2 = &buf2[i];
650 if ((omit_zero_bytes == true) &&
651 (i > 0) && (remaining_len > 16) &&
652 (this_len1 == 16) && all_zero(this_buf1, 16) &&
653 (this_len2 == 16) && all_zero(this_buf2, 16))
655 if (!skipped) {
656 cb("skipping zero buffer bytes\n",
657 private_data);
658 skipped = true;
660 continue;
663 skipped = false;
665 if ((this_len1 == this_len2) &&
666 (memcmp(this_buf1, this_buf2, this_len1) == 0))
668 dump_data_block16(" ", i, this_buf1, this_len1,
669 cb, private_data);
670 continue;
673 dump_data_block16("-", i, this_buf1, this_len1,
674 cb, private_data);
675 dump_data_block16("+", i, this_buf2, this_len2,
676 cb, private_data);
680 _PUBLIC_ void dump_data_diff(int dbgc_class, int level,
681 bool omit_zero_bytes,
682 const uint8_t *buf1, size_t len1,
683 const uint8_t *buf2, size_t len2)
685 struct debug_channel_level dcl = { dbgc_class, level };
687 if (!DEBUGLVLC(dbgc_class, level)) {
688 return;
690 dump_data_diff_cb(buf1, len1, buf2, len2, true, debugadd_channel_cb, &dcl);
693 _PUBLIC_ void dump_data_file_diff(FILE *f,
694 bool omit_zero_bytes,
695 const uint8_t *buf1, size_t len1,
696 const uint8_t *buf2, size_t len2)
698 dump_data_diff_cb(buf1, len1, buf2, len2, omit_zero_bytes, fprintf_cb, f);
702 malloc that aborts with smb_panic on fail or zero size.
705 _PUBLIC_ void *smb_xmalloc(size_t size)
707 void *p;
708 if (size == 0)
709 smb_panic("smb_xmalloc: called with zero size.\n");
710 if ((p = malloc(size)) == NULL)
711 smb_panic("smb_xmalloc: malloc fail.\n");
712 return p;
716 Memdup with smb_panic on fail.
719 _PUBLIC_ void *smb_xmemdup(const void *p, size_t size)
721 void *p2;
722 p2 = smb_xmalloc(size);
723 memcpy(p2, p, size);
724 return p2;
728 strdup that aborts on malloc fail.
731 char *smb_xstrdup(const char *s)
733 #if defined(PARANOID_MALLOC_CHECKER)
734 #ifdef strdup
735 #undef strdup
736 #endif
737 #endif
739 #ifndef HAVE_STRDUP
740 #define strdup rep_strdup
741 #endif
743 char *s1 = strdup(s);
744 #if defined(PARANOID_MALLOC_CHECKER)
745 #ifdef strdup
746 #undef strdup
747 #endif
748 #define strdup(s) __ERROR_DONT_USE_STRDUP_DIRECTLY
749 #endif
750 if (!s1) {
751 smb_panic("smb_xstrdup: malloc failed");
753 return s1;
758 strndup that aborts on malloc fail.
761 char *smb_xstrndup(const char *s, size_t n)
763 #if defined(PARANOID_MALLOC_CHECKER)
764 #ifdef strndup
765 #undef strndup
766 #endif
767 #endif
769 #if (defined(BROKEN_STRNDUP) || !defined(HAVE_STRNDUP))
770 #undef HAVE_STRNDUP
771 #define strndup rep_strndup
772 #endif
774 char *s1 = strndup(s, n);
775 #if defined(PARANOID_MALLOC_CHECKER)
776 #ifdef strndup
777 #undef strndup
778 #endif
779 #define strndup(s,n) __ERROR_DONT_USE_STRNDUP_DIRECTLY
780 #endif
781 if (!s1) {
782 smb_panic("smb_xstrndup: malloc failed");
784 return s1;
790 Like strdup but for memory.
793 _PUBLIC_ void *smb_memdup(const void *p, size_t size)
795 void *p2;
796 if (size == 0)
797 return NULL;
798 p2 = malloc(size);
799 if (!p2)
800 return NULL;
801 memcpy(p2, p, size);
802 return p2;
806 * Write a password to the log file.
808 * @note Only actually does something if DEBUG_PASSWORD was defined during
809 * compile-time.
811 _PUBLIC_ void dump_data_pw(const char *msg, const uint8_t * data, size_t len)
813 #ifdef DEBUG_PASSWORD
814 DEBUG(11, ("%s", msg));
815 if (data != NULL && len > 0)
817 dump_data(11, data, len);
819 #endif
824 * see if a range of memory is all zero. A NULL pointer is considered
825 * to be all zero
827 _PUBLIC_ bool all_zero(const uint8_t *ptr, size_t size)
829 size_t i;
830 if (!ptr) return true;
831 for (i=0;i<size;i++) {
832 if (ptr[i]) return false;
834 return true;
838 realloc an array, checking for integer overflow in the array size
840 _PUBLIC_ void *realloc_array(void *ptr, size_t el_size, unsigned count, bool free_on_fail)
842 #define MAX_MALLOC_SIZE 0x7fffffff
843 if (count == 0 ||
844 count >= MAX_MALLOC_SIZE/el_size) {
845 if (free_on_fail)
846 SAFE_FREE(ptr);
847 return NULL;
849 if (!ptr) {
850 return malloc(el_size * count);
852 return realloc(ptr, el_size * count);
855 /****************************************************************************
856 Type-safe malloc.
857 ****************************************************************************/
859 void *malloc_array(size_t el_size, unsigned int count)
861 return realloc_array(NULL, el_size, count, false);
864 /****************************************************************************
865 Type-safe memalign
866 ****************************************************************************/
868 void *memalign_array(size_t el_size, size_t align, unsigned int count)
870 if (el_size == 0 || count >= MAX_MALLOC_SIZE/el_size) {
871 return NULL;
874 return memalign(align, el_size*count);
877 /****************************************************************************
878 Type-safe calloc.
879 ****************************************************************************/
881 void *calloc_array(size_t size, size_t nmemb)
883 if (nmemb >= MAX_MALLOC_SIZE/size) {
884 return NULL;
886 if (size == 0 || nmemb == 0) {
887 return NULL;
889 return calloc(nmemb, size);
893 Trim the specified elements off the front and back of a string.
895 _PUBLIC_ bool trim_string(char *s, const char *front, const char *back)
897 bool ret = false;
898 size_t front_len;
899 size_t back_len;
900 size_t len;
902 /* Ignore null or empty strings. */
903 if (!s || (s[0] == '\0')) {
904 return false;
906 len = strlen(s);
908 front_len = front? strlen(front) : 0;
909 back_len = back? strlen(back) : 0;
911 if (front_len) {
912 size_t front_trim = 0;
914 while (strncmp(s+front_trim, front, front_len)==0) {
915 front_trim += front_len;
917 if (front_trim > 0) {
918 /* Must use memmove here as src & dest can
919 * easily overlap. Found by valgrind. JRA. */
920 memmove(s, s+front_trim, (len-front_trim)+1);
921 len -= front_trim;
922 ret=true;
926 if (back_len) {
927 while ((len >= back_len) && strncmp(s+len-back_len,back,back_len)==0) {
928 s[len-back_len]='\0';
929 len -= back_len;
930 ret=true;
933 return ret;
937 Find the number of 'c' chars in a string
939 _PUBLIC_ _PURE_ size_t count_chars(const char *s, char c)
941 size_t count = 0;
943 while (*s) {
944 if (*s == c) count++;
945 s ++;
948 return count;
952 * Routine to get hex characters and turn them into a byte array.
953 * the array can be variable length.
954 * - "0xnn" or "0Xnn" is specially catered for.
955 * - The first non-hex-digit character (apart from possibly leading "0x"
956 * finishes the conversion and skips the rest of the input.
957 * - A single hex-digit character at the end of the string is skipped.
959 * valid examples: "0A5D15"; "0x123456"
961 _PUBLIC_ size_t strhex_to_str(char *p, size_t p_len, const char *strhex, size_t strhex_len)
963 size_t i = 0;
964 size_t num_chars = 0;
966 /* skip leading 0x prefix */
967 if (strncasecmp(strhex, "0x", 2) == 0) {
968 i += 2; /* skip two chars */
971 while ((i < strhex_len) && (num_chars < p_len)) {
972 bool ok = hex_byte(&strhex[i], (uint8_t *)&p[num_chars]);
973 if (!ok) {
974 break;
976 i += 2;
977 num_chars += 1;
980 return num_chars;
984 * Parse a hex string and return a data blob.
986 _PUBLIC_ DATA_BLOB strhex_to_data_blob(TALLOC_CTX *mem_ctx, const char *strhex)
988 DATA_BLOB ret_blob = data_blob_talloc(mem_ctx, NULL, strlen(strhex)/2+1);
990 ret_blob.length = strhex_to_str((char *)ret_blob.data, ret_blob.length,
991 strhex,
992 strlen(strhex));
994 return ret_blob;
998 * Parse a hex dump and return a data blob. Hex dump is structured as
999 * is generated from dump_data_cb() elsewhere in this file
1002 _PUBLIC_ DATA_BLOB hexdump_to_data_blob(TALLOC_CTX *mem_ctx, const char *hexdump, size_t hexdump_len)
1004 DATA_BLOB ret_blob = { 0 };
1005 size_t i = 0;
1006 size_t char_count = 0;
1007 /* hexdump line length is 77 chars long. We then use the ASCII representation of the bytes
1008 * at the end of the final line to calculate how many are in that line, minus the extra space
1009 * and newline. */
1010 size_t hexdump_byte_count = (16 * (hexdump_len / 77));
1011 if (hexdump_len % 77) {
1012 hexdump_byte_count += ((hexdump_len % 77) - 59 - 2);
1015 ret_blob = data_blob_talloc(mem_ctx, NULL, hexdump_byte_count+1);
1016 for (; i+1 < hexdump_len && hexdump[i] != 0 && hexdump[i+1] != 0; i++) {
1017 if ((i%77) == 0)
1018 i += 7; /* Skip the offset at the start of the line */
1019 if ((i%77) < 56) { /* position 56 is after both hex chunks */
1020 if (hexdump[i] != ' ') {
1021 char_count += strhex_to_str((char *)&ret_blob.data[char_count],
1022 hexdump_byte_count - char_count,
1023 &hexdump[i], 2);
1024 i += 2;
1025 } else {
1026 i++;
1028 } else {
1029 i++;
1032 ret_blob.length = char_count;
1034 return ret_blob;
1038 * Print a buf in hex. Assumes dst is at least (srclen*2)+1 large.
1040 _PUBLIC_ void hex_encode_buf(char *dst, const uint8_t *src, size_t srclen)
1042 size_t i;
1043 for (i=0; i<srclen; i++) {
1044 snprintf(dst + i*2, 3, "%02X", src[i]);
1047 * Ensure 0-termination for 0-length buffers
1049 dst[srclen*2] = '\0';
1053 * talloc version of hex_encode_buf()
1055 _PUBLIC_ char *hex_encode_talloc(TALLOC_CTX *mem_ctx, const unsigned char *buff_in, size_t len)
1057 char *hex_buffer;
1059 hex_buffer = talloc_array(mem_ctx, char, (len*2)+1);
1060 if (!hex_buffer) {
1061 return NULL;
1063 hex_encode_buf(hex_buffer, buff_in, len);
1064 talloc_set_name_const(hex_buffer, hex_buffer);
1065 return hex_buffer;
1069 varient of strcmp() that handles NULL ptrs
1071 _PUBLIC_ int strcmp_safe(const char *s1, const char *s2)
1073 if (s1 == s2) {
1074 return 0;
1076 if (s1 == NULL || s2 == NULL) {
1077 return s1?-1:1;
1079 return strcmp(s1, s2);
1084 return the number of bytes occupied by a buffer in ASCII format
1085 the result includes the null termination
1086 limited by 'n' bytes
1088 _PUBLIC_ size_t ascii_len_n(const char *src, size_t n)
1090 size_t len;
1092 len = strnlen(src, n);
1093 if (len+1 <= n) {
1094 len += 1;
1097 return len;
1100 _PUBLIC_ bool mem_equal_const_time(const void *s1, const void *s2, size_t n)
1102 const uint8_t *p1 = s1, *p2 = s2;
1103 size_t i = 0;
1104 uint8_t sum = 0;
1106 for (i = 0; i < n; i++) {
1107 sum |= (p1[i] ^ p2[i]);
1110 return sum == 0;
1113 struct anonymous_shared_header {
1114 union {
1115 size_t length;
1116 uint8_t pad[16];
1117 } u;
1120 /* Map a shared memory buffer of at least nelem counters. */
1121 void *anonymous_shared_allocate(size_t orig_bufsz)
1123 void *ptr;
1124 void *buf;
1125 size_t pagesz = getpagesize();
1126 size_t pagecnt;
1127 size_t bufsz = orig_bufsz;
1128 struct anonymous_shared_header *hdr;
1130 bufsz += sizeof(*hdr);
1132 /* round up to full pages */
1133 pagecnt = bufsz / pagesz;
1134 if (bufsz % pagesz) {
1135 pagecnt += 1;
1137 bufsz = pagesz * pagecnt;
1139 if (orig_bufsz >= bufsz) {
1140 /* integer wrap */
1141 errno = ENOMEM;
1142 return NULL;
1145 #ifdef MAP_ANON
1146 /* BSD */
1147 buf = mmap(NULL, bufsz, PROT_READ|PROT_WRITE, MAP_ANON|MAP_SHARED,
1148 -1 /* fd */, 0 /* offset */);
1149 #else
1151 int saved_errno;
1152 int fd;
1154 fd = open("/dev/zero", O_RDWR);
1155 if (fd == -1) {
1156 return NULL;
1159 buf = mmap(NULL, bufsz, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED,
1160 fd, 0 /* offset */);
1161 saved_errno = errno;
1162 close(fd);
1163 errno = saved_errno;
1165 #endif
1167 if (buf == MAP_FAILED) {
1168 return NULL;
1171 hdr = (struct anonymous_shared_header *)buf;
1172 hdr->u.length = bufsz;
1174 ptr = (void *)(&hdr[1]);
1176 return ptr;
1179 void *anonymous_shared_resize(void *ptr, size_t new_size, bool maymove)
1181 #ifdef HAVE_MREMAP
1182 void *buf;
1183 size_t pagesz = getpagesize();
1184 size_t pagecnt;
1185 size_t bufsz;
1186 struct anonymous_shared_header *hdr;
1187 int flags = 0;
1189 if (ptr == NULL) {
1190 errno = EINVAL;
1191 return NULL;
1194 hdr = (struct anonymous_shared_header *)ptr;
1195 hdr--;
1196 if (hdr->u.length > (new_size + sizeof(*hdr))) {
1197 errno = EINVAL;
1198 return NULL;
1201 bufsz = new_size + sizeof(*hdr);
1203 /* round up to full pages */
1204 pagecnt = bufsz / pagesz;
1205 if (bufsz % pagesz) {
1206 pagecnt += 1;
1208 bufsz = pagesz * pagecnt;
1210 if (new_size >= bufsz) {
1211 /* integer wrap */
1212 errno = ENOSPC;
1213 return NULL;
1216 if (bufsz <= hdr->u.length) {
1217 return ptr;
1220 if (maymove) {
1221 flags = MREMAP_MAYMOVE;
1224 buf = mremap(hdr, hdr->u.length, bufsz, flags);
1226 if (buf == MAP_FAILED) {
1227 errno = ENOSPC;
1228 return NULL;
1231 hdr = (struct anonymous_shared_header *)buf;
1232 hdr->u.length = bufsz;
1234 ptr = (void *)(&hdr[1]);
1236 return ptr;
1237 #else
1238 errno = ENOSPC;
1239 return NULL;
1240 #endif
1243 void anonymous_shared_free(void *ptr)
1245 struct anonymous_shared_header *hdr;
1247 if (ptr == NULL) {
1248 return;
1251 hdr = (struct anonymous_shared_header *)ptr;
1253 hdr--;
1255 munmap(hdr, hdr->u.length);
1258 #ifdef DEVELOPER
1259 /* used when you want a debugger started at a particular point in the
1260 code. Mostly useful in code that runs as a child process, where
1261 normal gdb attach is harder to organise.
1263 void samba_start_debugger(void)
1265 int ready_pipe[2];
1266 char c;
1267 int ret;
1268 pid_t pid;
1270 ret = pipe(ready_pipe);
1271 SMB_ASSERT(ret == 0);
1273 pid = fork();
1274 SMB_ASSERT(pid >= 0);
1276 if (pid) {
1277 c = 0;
1279 ret = close(ready_pipe[0]);
1280 SMB_ASSERT(ret == 0);
1281 #if defined(HAVE_PRCTL) && defined(PR_SET_PTRACER)
1283 * Make sure the child process can attach a debugger.
1285 * We don't check the error code as the debugger
1286 * will tell us if it can't attach.
1288 (void)prctl(PR_SET_PTRACER, pid, 0, 0, 0);
1289 #endif
1290 ret = write(ready_pipe[1], &c, 1);
1291 SMB_ASSERT(ret == 1);
1293 ret = close(ready_pipe[1]);
1294 SMB_ASSERT(ret == 0);
1296 /* Wait for gdb to attach. */
1297 sleep(2);
1298 } else {
1299 char *cmd = NULL;
1301 ret = close(ready_pipe[1]);
1302 SMB_ASSERT(ret == 0);
1304 ret = read(ready_pipe[0], &c, 1);
1305 SMB_ASSERT(ret == 1);
1307 ret = close(ready_pipe[0]);
1308 SMB_ASSERT(ret == 0);
1310 ret = asprintf(&cmd, "gdb --pid %u", getppid());
1311 SMB_ASSERT(ret != -1);
1313 execlp("xterm", "xterm", "-e", cmd, (char *) NULL);
1314 smb_panic("execlp() failed");
1317 #endif