s3: tests: Add new test_stream_dir_rename.sh test.
[Samba.git] / lib / util / util.c
blobecb32a9acafdb3acece697c92193e1834f7afa2e
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 <tevent.h>
29 #include "system/network.h"
30 #include "system/filesys.h"
31 #include "system/locale.h"
32 #include "system/shmem.h"
33 #include "system/passwd.h"
34 #include "system/time.h"
35 #include "system/wait.h"
36 #include "debug.h"
37 #include "samba_util.h"
38 #include "lib/util/select.h"
39 #include <libgen.h>
40 #include <gnutls/gnutls.h>
42 #ifdef HAVE_SYS_PRCTL_H
43 #include <sys/prctl.h>
44 #endif
46 #undef malloc
47 #undef strcasecmp
48 #undef strncasecmp
49 #undef strdup
50 #undef realloc
51 #undef calloc
53 /**
54 * @file
55 * @brief Misc utility functions
58 /**
59 Find a suitable temporary directory. The result should be copied immediately
60 as it may be overwritten by a subsequent call.
61 **/
62 _PUBLIC_ const char *tmpdir(void)
64 char *p;
65 if ((p = getenv("TMPDIR")))
66 return p;
67 return "/tmp";
71 /**
72 Create a tmp file, open it and immediately unlink it.
73 If dir is NULL uses tmpdir()
74 Returns the file descriptor or -1 on error.
75 **/
76 int create_unlink_tmp(const char *dir)
78 size_t len = strlen(dir ? dir : (dir = tmpdir()));
79 char fname[len+25];
80 int fd;
81 mode_t mask;
83 len = snprintf(fname, sizeof(fname), "%s/listenerlock_XXXXXX", dir);
84 if (len >= sizeof(fname)) {
85 errno = ENOMEM;
86 return -1;
88 mask = umask(S_IRWXO | S_IRWXG);
89 fd = mkstemp(fname);
90 umask(mask);
91 if (fd == -1) {
92 return -1;
94 if (unlink(fname) == -1) {
95 int sys_errno = errno;
96 close(fd);
97 errno = sys_errno;
98 return -1;
100 return fd;
105 Check if a file exists - call vfs_file_exist for samba files.
107 _PUBLIC_ bool file_exist(const char *fname)
109 struct stat st;
111 if (stat(fname, &st) != 0) {
112 return false;
115 return ((S_ISREG(st.st_mode)) || (S_ISFIFO(st.st_mode)));
119 * @brief Return a files modification time.
121 * @param fname The name of the file.
123 * @param mt A pointer to store the modification time.
125 * @return 0 on success, errno otherwise.
127 _PUBLIC_ int file_modtime(const char *fname, struct timespec *mt)
129 struct stat st = {0};
131 if (stat(fname, &st) != 0) {
132 return errno;
135 *mt = get_mtimespec(&st);
136 return 0;
140 Check file permissions.
143 _PUBLIC_ bool file_check_permissions(const char *fname,
144 uid_t uid,
145 mode_t file_perms,
146 struct stat *pst)
148 int ret;
149 struct stat st;
151 if (pst == NULL) {
152 pst = &st;
155 ZERO_STRUCTP(pst);
157 ret = stat(fname, pst);
158 if (ret != 0) {
159 DEBUG(0, ("stat failed on file '%s': %s\n",
160 fname, strerror(errno)));
161 return false;
164 if (pst->st_uid != uid && !uid_wrapper_enabled()) {
165 DEBUG(0, ("invalid ownership of file '%s': "
166 "owned by uid %u, should be %u\n",
167 fname, (unsigned int)pst->st_uid,
168 (unsigned int)uid));
169 return false;
172 if ((pst->st_mode & 0777) != file_perms) {
173 DEBUG(0, ("invalid permissions on file "
174 "'%s': has 0%o should be 0%o\n", fname,
175 (unsigned int)(pst->st_mode & 0777),
176 (unsigned int)file_perms));
177 return false;
180 return true;
184 Check if a directory exists.
187 _PUBLIC_ bool directory_exist(const char *dname)
189 struct stat st;
190 bool ret;
192 if (stat(dname,&st) != 0) {
193 return false;
196 ret = S_ISDIR(st.st_mode);
197 if(!ret)
198 errno = ENOTDIR;
199 return ret;
203 * Try to create the specified directory if it didn't exist.
204 * A symlink to a directory is also accepted as a valid existing directory.
206 * @retval true if the directory already existed
207 * or was successfully created.
209 _PUBLIC_ bool directory_create_or_exist(const char *dname,
210 mode_t dir_perms)
212 int ret;
213 mode_t old_umask;
215 /* Create directory */
216 old_umask = umask(0);
217 ret = mkdir(dname, dir_perms);
218 if (ret == -1 && errno != EEXIST) {
219 int dbg_level = geteuid() == 0 ? DBGLVL_ERR : DBGLVL_NOTICE;
221 DBG_PREFIX(dbg_level,
222 ("mkdir failed on directory %s: %s\n",
223 dname,
224 strerror(errno)));
225 umask(old_umask);
226 return false;
228 umask(old_umask);
230 if (ret != 0 && errno == EEXIST) {
231 struct stat sbuf;
233 ret = lstat(dname, &sbuf);
234 if (ret != 0) {
235 return false;
238 if (S_ISDIR(sbuf.st_mode)) {
239 return true;
242 if (S_ISLNK(sbuf.st_mode)) {
243 ret = stat(dname, &sbuf);
244 if (ret != 0) {
245 return false;
248 if (S_ISDIR(sbuf.st_mode)) {
249 return true;
253 return false;
256 return true;
259 _PUBLIC_ bool directory_create_or_exists_recursive(
260 const char *dname,
261 mode_t dir_perms)
263 bool ok;
265 ok = directory_create_or_exist(dname, dir_perms);
266 if (!ok) {
267 if (!directory_exist(dname)) {
268 char tmp[PATH_MAX] = {0};
269 char *parent = NULL;
270 size_t n;
272 /* Use the null context */
273 n = strlcpy(tmp, dname, sizeof(tmp));
274 if (n < strlen(dname)) {
275 DBG_ERR("Path too long!\n");
276 return false;
279 parent = dirname(tmp);
280 if (parent == NULL) {
281 DBG_ERR("Failed to create dirname!\n");
282 return false;
285 ok = directory_create_or_exists_recursive(parent,
286 dir_perms);
287 if (!ok) {
288 return false;
291 ok = directory_create_or_exist(dname, dir_perms);
295 return ok;
299 * @brief Try to create a specified directory if it doesn't exist.
301 * The function creates a directory with the given uid and permissions if it
302 * doesn't exist. If it exists it makes sure the uid and permissions are
303 * correct and it will fail if they are different.
305 * @param[in] dname The directory to create.
307 * @param[in] uid The uid the directory needs to belong too.
309 * @param[in] dir_perms The expected permissions of the directory.
311 * @return True on success, false on error.
313 _PUBLIC_ bool directory_create_or_exist_strict(const char *dname,
314 uid_t uid,
315 mode_t dir_perms)
317 struct stat st;
318 bool ok;
319 int rc;
321 ok = directory_create_or_exist(dname, dir_perms);
322 if (!ok) {
323 return false;
326 rc = lstat(dname, &st);
327 if (rc == -1) {
328 DEBUG(0, ("lstat failed on created directory %s: %s\n",
329 dname, strerror(errno)));
330 return false;
333 /* Check ownership and permission on existing directory */
334 if (!S_ISDIR(st.st_mode)) {
335 DEBUG(0, ("directory %s isn't a directory\n",
336 dname));
337 return false;
339 if (st.st_uid != uid && !uid_wrapper_enabled()) {
340 DBG_NOTICE("invalid ownership on directory "
341 "%s\n", dname);
342 return false;
344 if ((st.st_mode & 0777) != dir_perms) {
345 DEBUG(0, ("invalid permissions on directory "
346 "'%s': has 0%o should be 0%o\n", dname,
347 (unsigned int)(st.st_mode & 0777), (unsigned int)dir_perms));
348 return false;
351 return true;
356 Sleep for a specified number of milliseconds.
359 _PUBLIC_ void smb_msleep(unsigned int t)
361 sys_poll_intr(NULL, 0, t);
365 Get my own name, return in talloc'ed storage.
368 _PUBLIC_ char *get_myname(TALLOC_CTX *ctx)
370 char *p;
371 char hostname[HOST_NAME_MAX];
373 /* get my host name */
374 if (gethostname(hostname, sizeof(hostname)) == -1) {
375 DEBUG(0,("gethostname failed\n"));
376 return NULL;
379 /* Ensure null termination. */
380 hostname[sizeof(hostname)-1] = '\0';
382 /* split off any parts after an initial . */
383 p = strchr_m(hostname, '.');
384 if (p) {
385 *p = 0;
388 return talloc_strdup(ctx, hostname);
392 Check if a process exists. Does this work on all unixes?
395 _PUBLIC_ bool process_exists_by_pid(pid_t pid)
397 /* Doing kill with a non-positive pid causes messages to be
398 * sent to places we don't want. */
399 if (pid <= 0) {
400 return false;
402 return(kill(pid,0) == 0 || errno != ESRCH);
406 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
407 is dealt with in posix.c
410 _PUBLIC_ bool fcntl_lock(int fd, int op, off_t offset, off_t count, int type)
412 struct flock lock;
413 int ret;
415 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
417 lock.l_type = type;
418 lock.l_whence = SEEK_SET;
419 lock.l_start = offset;
420 lock.l_len = count;
421 lock.l_pid = 0;
423 ret = fcntl(fd,op,&lock);
425 if (ret == -1 && errno != 0)
426 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
428 /* a lock query */
429 if (op == F_GETLK) {
430 if ((ret != -1) &&
431 (lock.l_type != F_UNLCK) &&
432 (lock.l_pid != 0) &&
433 (lock.l_pid != tevent_cached_getpid())) {
434 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
435 return true;
438 /* it must be not locked or locked by me */
439 return false;
442 /* a lock set or unset */
443 if (ret == -1) {
444 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
445 (double)offset,(double)count,op,type,strerror(errno)));
446 return false;
449 /* everything went OK */
450 DEBUG(8,("fcntl_lock: Lock call successful\n"));
452 return true;
455 struct debug_channel_level {
456 int channel;
457 int level;
460 static void debugadd_channel_cb(const char *buf, void *private_data)
462 struct debug_channel_level *dcl =
463 (struct debug_channel_level *)private_data;
465 DEBUGADDC(dcl->channel, dcl->level,("%s", buf));
468 static void debugadd_cb(const char *buf, void *private_data)
470 int *plevel = (int *)private_data;
471 DEBUGADD(*plevel, ("%s", buf));
474 void print_asc_cb(const uint8_t *buf, int len,
475 void (*cb)(const char *buf, void *private_data),
476 void *private_data)
478 int i;
479 char s[2];
480 s[1] = 0;
482 for (i=0; i<len; i++) {
483 s[0] = isprint(buf[i]) ? buf[i] : '.';
484 cb(s, private_data);
488 void print_asc(int level, const uint8_t *buf,int len)
490 print_asc_cb(buf, len, debugadd_cb, &level);
493 static void dump_data_block16(const char *prefix, size_t idx,
494 const uint8_t *buf, size_t len,
495 void (*cb)(const char *buf, void *private_data),
496 void *private_data)
498 char tmp[16];
499 size_t i;
501 SMB_ASSERT(len >= 0 && len <= 16);
503 snprintf(tmp, sizeof(tmp), "%s[%04zX]", prefix, idx);
504 cb(tmp, private_data);
506 for (i=0; i<16; i++) {
507 if (i == 8) {
508 cb(" ", private_data);
510 if (i < len) {
511 snprintf(tmp, sizeof(tmp), " %02X", (int)buf[i]);
512 } else {
513 snprintf(tmp, sizeof(tmp), " ");
515 cb(tmp, private_data);
518 cb(" ", private_data);
520 if (len == 0) {
521 cb("EMPTY BLOCK\n", private_data);
522 return;
525 for (i=0; i<len; i++) {
526 if (i == 8) {
527 cb(" ", private_data);
529 print_asc_cb(&buf[i], 1, cb, private_data);
532 cb("\n", private_data);
536 * Write dump of binary data to a callback
538 void dump_data_cb(const uint8_t *buf, int len,
539 bool omit_zero_bytes,
540 void (*cb)(const char *buf, void *private_data),
541 void *private_data)
543 int i=0;
544 bool skipped = false;
546 if (len<=0) return;
548 for (i=0;i<len;i+=16) {
549 size_t remaining_len = len - i;
550 size_t this_len = MIN(remaining_len, 16);
551 const uint8_t *this_buf = &buf[i];
553 if ((omit_zero_bytes == true) &&
554 (i > 0) && (remaining_len > 16) &&
555 (this_len == 16) && all_zero(this_buf, 16))
557 if (!skipped) {
558 cb("skipping zero buffer bytes\n",
559 private_data);
560 skipped = true;
562 continue;
565 skipped = false;
566 dump_data_block16("", i, this_buf, this_len,
567 cb, private_data);
572 * Write dump of binary data to the log file.
574 * The data is only written if the log level is at least level.
576 _PUBLIC_ void dump_data(int level, const uint8_t *buf, int len)
578 if (!DEBUGLVL(level)) {
579 return;
581 dump_data_cb(buf, len, false, debugadd_cb, &level);
585 * Write dump of binary data to the log file.
587 * The data is only written if the log level is at least level for
588 * debug class dbgc_class.
590 _PUBLIC_ void dump_data_dbgc(int dbgc_class, int level, const uint8_t *buf, int len)
592 struct debug_channel_level dcl = { dbgc_class, level };
594 if (!DEBUGLVLC(dbgc_class, level)) {
595 return;
597 dump_data_cb(buf, len, false, debugadd_channel_cb, &dcl);
601 * Write dump of binary data to the log file.
603 * The data is only written if the log level is at least level.
604 * 16 zero bytes in a row are omitted
606 _PUBLIC_ void dump_data_skip_zeros(int level, const uint8_t *buf, int len)
608 if (!DEBUGLVL(level)) {
609 return;
611 dump_data_cb(buf, len, true, debugadd_cb, &level);
614 static void fprintf_cb(const char *buf, void *private_data)
616 FILE *f = (FILE *)private_data;
617 fprintf(f, "%s", buf);
620 void dump_data_file(const uint8_t *buf, int len, bool omit_zero_bytes,
621 FILE *f)
623 dump_data_cb(buf, len, omit_zero_bytes, fprintf_cb, f);
627 * Write dump of compared binary data to a callback
629 void dump_data_diff_cb(const uint8_t *buf1, size_t len1,
630 const uint8_t *buf2, size_t len2,
631 bool omit_zero_bytes,
632 void (*cb)(const char *buf, void *private_data),
633 void *private_data)
635 size_t len = MAX(len1, len2);
636 size_t i;
637 bool skipped = false;
639 for (i=0; i<len; i+=16) {
640 size_t remaining_len = len - i;
641 size_t remaining_len1 = 0;
642 size_t this_len1 = 0;
643 const uint8_t *this_buf1 = NULL;
644 size_t remaining_len2 = 0;
645 size_t this_len2 = 0;
646 const uint8_t *this_buf2 = NULL;
648 if (i < len1) {
649 remaining_len1 = len1 - i;
650 this_len1 = MIN(remaining_len1, 16);
651 this_buf1 = &buf1[i];
653 if (i < len2) {
654 remaining_len2 = len2 - i;
655 this_len2 = MIN(remaining_len2, 16);
656 this_buf2 = &buf2[i];
659 if ((omit_zero_bytes == true) &&
660 (i > 0) && (remaining_len > 16) &&
661 (this_len1 == 16) && all_zero(this_buf1, 16) &&
662 (this_len2 == 16) && all_zero(this_buf2, 16))
664 if (!skipped) {
665 cb("skipping zero buffer bytes\n",
666 private_data);
667 skipped = true;
669 continue;
672 skipped = false;
674 if ((this_len1 == this_len2) &&
675 (memcmp(this_buf1, this_buf2, this_len1) == 0))
677 dump_data_block16(" ", i, this_buf1, this_len1,
678 cb, private_data);
679 continue;
682 dump_data_block16("-", i, this_buf1, this_len1,
683 cb, private_data);
684 dump_data_block16("+", i, this_buf2, this_len2,
685 cb, private_data);
689 _PUBLIC_ void dump_data_diff(int dbgc_class, int level,
690 bool omit_zero_bytes,
691 const uint8_t *buf1, size_t len1,
692 const uint8_t *buf2, size_t len2)
694 struct debug_channel_level dcl = { dbgc_class, level };
696 if (!DEBUGLVLC(dbgc_class, level)) {
697 return;
699 dump_data_diff_cb(buf1, len1, buf2, len2, true, debugadd_channel_cb, &dcl);
702 _PUBLIC_ void dump_data_file_diff(FILE *f,
703 bool omit_zero_bytes,
704 const uint8_t *buf1, size_t len1,
705 const uint8_t *buf2, size_t len2)
707 dump_data_diff_cb(buf1, len1, buf2, len2, omit_zero_bytes, fprintf_cb, f);
711 malloc that aborts with smb_panic on fail or zero size.
714 _PUBLIC_ void *smb_xmalloc(size_t size)
716 void *p;
717 if (size == 0)
718 smb_panic("smb_xmalloc: called with zero size.\n");
719 if ((p = malloc(size)) == NULL)
720 smb_panic("smb_xmalloc: malloc fail.\n");
721 return p;
725 Memdup with smb_panic on fail.
728 _PUBLIC_ void *smb_xmemdup(const void *p, size_t size)
730 void *p2;
731 p2 = smb_xmalloc(size);
732 memcpy(p2, p, size);
733 return p2;
737 strdup that aborts on malloc fail.
740 char *smb_xstrdup(const char *s)
742 #if defined(PARANOID_MALLOC_CHECKER)
743 #ifdef strdup
744 #undef strdup
745 #endif
746 #endif
748 #ifndef HAVE_STRDUP
749 #define strdup rep_strdup
750 #endif
752 char *s1 = strdup(s);
753 #if defined(PARANOID_MALLOC_CHECKER)
754 #ifdef strdup
755 #undef strdup
756 #endif
757 #define strdup(s) __ERROR_DONT_USE_STRDUP_DIRECTLY
758 #endif
759 if (!s1) {
760 smb_panic("smb_xstrdup: malloc failed");
762 return s1;
767 strndup that aborts on malloc fail.
770 char *smb_xstrndup(const char *s, size_t n)
772 #if defined(PARANOID_MALLOC_CHECKER)
773 #ifdef strndup
774 #undef strndup
775 #endif
776 #endif
778 #if (defined(BROKEN_STRNDUP) || !defined(HAVE_STRNDUP))
779 #undef HAVE_STRNDUP
780 #define strndup rep_strndup
781 #endif
783 char *s1 = strndup(s, n);
784 #if defined(PARANOID_MALLOC_CHECKER)
785 #ifdef strndup
786 #undef strndup
787 #endif
788 #define strndup(s,n) __ERROR_DONT_USE_STRNDUP_DIRECTLY
789 #endif
790 if (!s1) {
791 smb_panic("smb_xstrndup: malloc failed");
793 return s1;
799 Like strdup but for memory.
802 _PUBLIC_ void *smb_memdup(const void *p, size_t size)
804 void *p2;
805 if (size == 0)
806 return NULL;
807 p2 = malloc(size);
808 if (!p2)
809 return NULL;
810 memcpy(p2, p, size);
811 return p2;
815 * Write a password to the log file.
817 * @note Only actually does something if DEBUG_PASSWORD was defined during
818 * compile-time.
820 _PUBLIC_ void dump_data_pw(const char *msg, const uint8_t * data, size_t len)
822 #ifdef DEBUG_PASSWORD
823 DEBUG(11, ("%s", msg));
824 if (data != NULL && len > 0)
826 dump_data(11, data, len);
828 #endif
833 * see if a range of memory is all zero. A NULL pointer is considered
834 * to be all zero
836 _PUBLIC_ bool all_zero(const uint8_t *ptr, size_t size)
838 size_t i;
839 if (!ptr) return true;
840 for (i=0;i<size;i++) {
841 if (ptr[i]) return false;
843 return true;
847 realloc an array, checking for integer overflow in the array size
849 _PUBLIC_ void *realloc_array(void *ptr, size_t el_size, unsigned count, bool free_on_fail)
851 #define MAX_MALLOC_SIZE 0x7fffffff
852 if (count == 0 ||
853 count >= MAX_MALLOC_SIZE/el_size) {
854 if (free_on_fail)
855 SAFE_FREE(ptr);
856 return NULL;
858 if (!ptr) {
859 return malloc(el_size * count);
861 return realloc(ptr, el_size * count);
864 /****************************************************************************
865 Type-safe malloc.
866 ****************************************************************************/
868 void *malloc_array(size_t el_size, unsigned int count)
870 return realloc_array(NULL, el_size, count, false);
873 /****************************************************************************
874 Type-safe memalign
875 ****************************************************************************/
877 void *memalign_array(size_t el_size, size_t align, unsigned int count)
879 if (el_size == 0 || count >= MAX_MALLOC_SIZE/el_size) {
880 return NULL;
883 return memalign(align, el_size*count);
886 /****************************************************************************
887 Type-safe calloc.
888 ****************************************************************************/
890 void *calloc_array(size_t size, size_t nmemb)
892 if (nmemb >= MAX_MALLOC_SIZE/size) {
893 return NULL;
895 if (size == 0 || nmemb == 0) {
896 return NULL;
898 return calloc(nmemb, size);
902 Trim the specified elements off the front and back of a string.
904 _PUBLIC_ bool trim_string(char *s, const char *front, const char *back)
906 bool ret = false;
907 size_t front_len;
908 size_t back_len;
909 size_t len;
911 /* Ignore null or empty strings. */
912 if (!s || (s[0] == '\0')) {
913 return false;
915 len = strlen(s);
917 front_len = front? strlen(front) : 0;
918 back_len = back? strlen(back) : 0;
920 if (front_len) {
921 size_t front_trim = 0;
923 while (strncmp(s+front_trim, front, front_len)==0) {
924 front_trim += front_len;
926 if (front_trim > 0) {
927 /* Must use memmove here as src & dest can
928 * easily overlap. Found by valgrind. JRA. */
929 memmove(s, s+front_trim, (len-front_trim)+1);
930 len -= front_trim;
931 ret=true;
935 if (back_len) {
936 while ((len >= back_len) && strncmp(s+len-back_len,back,back_len)==0) {
937 s[len-back_len]='\0';
938 len -= back_len;
939 ret=true;
942 return ret;
946 Find the number of 'c' chars in a string
948 _PUBLIC_ _PURE_ size_t count_chars(const char *s, char c)
950 size_t count = 0;
952 while (*s) {
953 if (*s == c) count++;
954 s ++;
957 return count;
961 * Routine to get hex characters and turn them into a byte array.
962 * the array can be variable length.
963 * - "0xnn" or "0Xnn" is specially catered for.
964 * - The first non-hex-digit character (apart from possibly leading "0x"
965 * finishes the conversion and skips the rest of the input.
966 * - A single hex-digit character at the end of the string is skipped.
968 * valid examples: "0A5D15"; "0x123456"
970 _PUBLIC_ size_t strhex_to_str(char *p, size_t p_len, const char *strhex, size_t strhex_len)
972 size_t i = 0;
973 size_t num_chars = 0;
975 /* skip leading 0x prefix */
976 if (strncasecmp(strhex, "0x", 2) == 0) {
977 i += 2; /* skip two chars */
980 while ((i < strhex_len) && (num_chars < p_len)) {
981 bool ok = hex_byte(&strhex[i], (uint8_t *)&p[num_chars]);
982 if (!ok) {
983 break;
985 i += 2;
986 num_chars += 1;
989 return num_chars;
993 * Parse a hex string and return a data blob.
995 _PUBLIC_ DATA_BLOB strhex_to_data_blob(TALLOC_CTX *mem_ctx, const char *strhex)
997 DATA_BLOB ret_blob = data_blob_talloc(mem_ctx, NULL, strlen(strhex)/2+1);
999 ret_blob.length = strhex_to_str((char *)ret_blob.data, ret_blob.length,
1000 strhex,
1001 strlen(strhex));
1003 return ret_blob;
1007 * Parse a hex dump and return a data blob. Hex dump is structured as
1008 * is generated from dump_data_cb() elsewhere in this file
1011 _PUBLIC_ DATA_BLOB hexdump_to_data_blob(TALLOC_CTX *mem_ctx, const char *hexdump, size_t hexdump_len)
1013 DATA_BLOB ret_blob = { 0 };
1014 size_t i = 0;
1015 size_t char_count = 0;
1016 /* hexdump line length is 77 chars long. We then use the ASCII representation of the bytes
1017 * at the end of the final line to calculate how many are in that line, minus the extra space
1018 * and newline. */
1019 size_t hexdump_byte_count = (16 * (hexdump_len / 77));
1020 if (hexdump_len % 77) {
1021 hexdump_byte_count += ((hexdump_len % 77) - 59 - 2);
1024 ret_blob = data_blob_talloc(mem_ctx, NULL, hexdump_byte_count+1);
1025 for (; i+1 < hexdump_len && hexdump[i] != 0 && hexdump[i+1] != 0; i++) {
1026 if ((i%77) == 0)
1027 i += 7; /* Skip the offset at the start of the line */
1028 if ((i%77) < 56) { /* position 56 is after both hex chunks */
1029 if (hexdump[i] != ' ') {
1030 char_count += strhex_to_str((char *)&ret_blob.data[char_count],
1031 hexdump_byte_count - char_count,
1032 &hexdump[i], 2);
1033 i += 2;
1034 } else {
1035 i++;
1037 } else {
1038 i++;
1041 ret_blob.length = char_count;
1043 return ret_blob;
1047 * Print a buf in hex. Assumes dst is at least (srclen*2)+1 large.
1049 _PUBLIC_ void hex_encode_buf(char *dst, const uint8_t *src, size_t srclen)
1051 size_t i;
1052 for (i=0; i<srclen; i++) {
1053 snprintf(dst + i*2, 3, "%02X", src[i]);
1056 * Ensure 0-termination for 0-length buffers
1058 dst[srclen*2] = '\0';
1062 * talloc version of hex_encode_buf()
1064 _PUBLIC_ char *hex_encode_talloc(TALLOC_CTX *mem_ctx, const unsigned char *buff_in, size_t len)
1066 char *hex_buffer;
1068 hex_buffer = talloc_array(mem_ctx, char, (len*2)+1);
1069 if (!hex_buffer) {
1070 return NULL;
1072 hex_encode_buf(hex_buffer, buff_in, len);
1073 talloc_set_name_const(hex_buffer, hex_buffer);
1074 return hex_buffer;
1078 varient of strcmp() that handles NULL ptrs
1080 _PUBLIC_ int strcmp_safe(const char *s1, const char *s2)
1082 if (s1 == s2) {
1083 return 0;
1085 if (s1 == NULL || s2 == NULL) {
1086 return s1?-1:1;
1088 return strcmp(s1, s2);
1093 return the number of bytes occupied by a buffer in ASCII format
1094 the result includes the null termination
1095 limited by 'n' bytes
1097 _PUBLIC_ size_t ascii_len_n(const char *src, size_t n)
1099 size_t len;
1101 len = strnlen(src, n);
1102 if (len+1 <= n) {
1103 len += 1;
1106 return len;
1109 _PUBLIC_ bool mem_equal_const_time(const void *s1, const void *s2, size_t n)
1111 /* Ensure we won't overflow the unsigned index used by gnutls. */
1112 SMB_ASSERT(n <= UINT_MAX);
1114 return gnutls_memcmp(s1, s2, n) == 0;
1117 struct anonymous_shared_header {
1118 union {
1119 size_t length;
1120 uint8_t pad[16];
1121 } u;
1124 /* Map a shared memory buffer of at least nelem counters. */
1125 void *anonymous_shared_allocate(size_t orig_bufsz)
1127 void *ptr;
1128 void *buf;
1129 size_t pagesz = getpagesize();
1130 size_t pagecnt;
1131 size_t bufsz = orig_bufsz;
1132 struct anonymous_shared_header *hdr;
1134 bufsz += sizeof(*hdr);
1136 /* round up to full pages */
1137 pagecnt = bufsz / pagesz;
1138 if (bufsz % pagesz) {
1139 pagecnt += 1;
1141 bufsz = pagesz * pagecnt;
1143 if (orig_bufsz >= bufsz) {
1144 /* integer wrap */
1145 errno = ENOMEM;
1146 return NULL;
1149 #ifdef MAP_ANON
1150 /* BSD */
1151 buf = mmap(NULL, bufsz, PROT_READ|PROT_WRITE, MAP_ANON|MAP_SHARED,
1152 -1 /* fd */, 0 /* offset */);
1153 #else
1155 int saved_errno;
1156 int fd;
1158 fd = open("/dev/zero", O_RDWR);
1159 if (fd == -1) {
1160 return NULL;
1163 buf = mmap(NULL, bufsz, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED,
1164 fd, 0 /* offset */);
1165 saved_errno = errno;
1166 close(fd);
1167 errno = saved_errno;
1169 #endif
1171 if (buf == MAP_FAILED) {
1172 return NULL;
1175 hdr = (struct anonymous_shared_header *)buf;
1176 hdr->u.length = bufsz;
1178 ptr = (void *)(&hdr[1]);
1180 return ptr;
1183 void *anonymous_shared_resize(void *ptr, size_t new_size, bool maymove)
1185 #ifdef HAVE_MREMAP
1186 void *buf;
1187 size_t pagesz = getpagesize();
1188 size_t pagecnt;
1189 size_t bufsz;
1190 struct anonymous_shared_header *hdr;
1191 int flags = 0;
1193 if (ptr == NULL) {
1194 errno = EINVAL;
1195 return NULL;
1198 hdr = (struct anonymous_shared_header *)ptr;
1199 hdr--;
1200 if (hdr->u.length > (new_size + sizeof(*hdr))) {
1201 errno = EINVAL;
1202 return NULL;
1205 bufsz = new_size + sizeof(*hdr);
1207 /* round up to full pages */
1208 pagecnt = bufsz / pagesz;
1209 if (bufsz % pagesz) {
1210 pagecnt += 1;
1212 bufsz = pagesz * pagecnt;
1214 if (new_size >= bufsz) {
1215 /* integer wrap */
1216 errno = ENOSPC;
1217 return NULL;
1220 if (bufsz <= hdr->u.length) {
1221 return ptr;
1224 if (maymove) {
1225 flags = MREMAP_MAYMOVE;
1228 buf = mremap(hdr, hdr->u.length, bufsz, flags);
1230 if (buf == MAP_FAILED) {
1231 errno = ENOSPC;
1232 return NULL;
1235 hdr = (struct anonymous_shared_header *)buf;
1236 hdr->u.length = bufsz;
1238 ptr = (void *)(&hdr[1]);
1240 return ptr;
1241 #else
1242 errno = ENOSPC;
1243 return NULL;
1244 #endif
1247 void anonymous_shared_free(void *ptr)
1249 struct anonymous_shared_header *hdr;
1251 if (ptr == NULL) {
1252 return;
1255 hdr = (struct anonymous_shared_header *)ptr;
1257 hdr--;
1259 munmap(hdr, hdr->u.length);
1262 #ifdef DEVELOPER
1263 /* used when you want a debugger started at a particular point in the
1264 code. Mostly useful in code that runs as a child process, where
1265 normal gdb attach is harder to organise.
1267 void samba_start_debugger(void)
1269 int ready_pipe[2];
1270 char c;
1271 int ret;
1272 pid_t pid;
1274 ret = pipe(ready_pipe);
1275 SMB_ASSERT(ret == 0);
1277 pid = fork();
1278 SMB_ASSERT(pid >= 0);
1280 if (pid) {
1281 c = 0;
1283 ret = close(ready_pipe[0]);
1284 SMB_ASSERT(ret == 0);
1285 #if defined(HAVE_PRCTL) && defined(PR_SET_PTRACER)
1287 * Make sure the child process can attach a debugger.
1289 * We don't check the error code as the debugger
1290 * will tell us if it can't attach.
1292 (void)prctl(PR_SET_PTRACER, pid, 0, 0, 0);
1293 #endif
1294 ret = write(ready_pipe[1], &c, 1);
1295 SMB_ASSERT(ret == 1);
1297 ret = close(ready_pipe[1]);
1298 SMB_ASSERT(ret == 0);
1300 /* Wait for gdb to attach. */
1301 sleep(2);
1302 } else {
1303 char *cmd = NULL;
1305 ret = close(ready_pipe[1]);
1306 SMB_ASSERT(ret == 0);
1308 ret = read(ready_pipe[0], &c, 1);
1309 SMB_ASSERT(ret == 1);
1311 ret = close(ready_pipe[0]);
1312 SMB_ASSERT(ret == 0);
1314 ret = asprintf(&cmd, "gdb --pid %u", getppid());
1315 SMB_ASSERT(ret != -1);
1317 execlp("xterm", "xterm", "-e", cmd, (char *) NULL);
1318 smb_panic("execlp() failed");
1321 #endif