ctdb-scripts: Move nfslock out of basic_stop() and basic_start()
[samba.git] / lib / util / util.c
blob8c2a74fe5f348331a0971f10666db845f421d923
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>
39 #include <gnutls/gnutls.h>
41 #ifdef HAVE_SYS_PRCTL_H
42 #include <sys/prctl.h>
43 #endif
45 #undef malloc
46 #undef strcasecmp
47 #undef strncasecmp
48 #undef strdup
49 #undef realloc
50 #undef calloc
52 /**
53 * @file
54 * @brief Misc utility functions
57 /**
58 Find a suitable temporary directory. The result should be copied immediately
59 as it may be overwritten by a subsequent call.
60 **/
61 _PUBLIC_ const char *tmpdir(void)
63 char *p;
64 if ((p = getenv("TMPDIR")))
65 return p;
66 return "/tmp";
70 /**
71 Create a tmp file, open it and immediately unlink it.
72 If dir is NULL uses tmpdir()
73 Returns the file descriptor or -1 on error.
74 **/
75 int create_unlink_tmp(const char *dir)
77 size_t len = strlen(dir ? dir : (dir = tmpdir()));
78 char fname[len+25];
79 int fd;
80 mode_t mask;
82 len = snprintf(fname, sizeof(fname), "%s/listenerlock_XXXXXX", dir);
83 if (len >= sizeof(fname)) {
84 errno = ENOMEM;
85 return -1;
87 mask = umask(S_IRWXO | S_IRWXG);
88 fd = mkstemp(fname);
89 umask(mask);
90 if (fd == -1) {
91 return -1;
93 if (unlink(fname) == -1) {
94 int sys_errno = errno;
95 close(fd);
96 errno = sys_errno;
97 return -1;
99 return fd;
104 Check if a file exists - call vfs_file_exist for samba files.
106 _PUBLIC_ bool file_exist(const char *fname)
108 struct stat st;
110 if (stat(fname, &st) != 0) {
111 return false;
114 return ((S_ISREG(st.st_mode)) || (S_ISFIFO(st.st_mode)));
118 Check a files mod time.
121 _PUBLIC_ time_t file_modtime(const char *fname)
123 struct stat st;
125 if (stat(fname,&st) != 0)
126 return(0);
128 return(st.st_mtime);
132 Check file permissions.
135 _PUBLIC_ bool file_check_permissions(const char *fname,
136 uid_t uid,
137 mode_t file_perms,
138 struct stat *pst)
140 int ret;
141 struct stat st;
143 if (pst == NULL) {
144 pst = &st;
147 ZERO_STRUCTP(pst);
149 ret = stat(fname, pst);
150 if (ret != 0) {
151 DEBUG(0, ("stat failed on file '%s': %s\n",
152 fname, strerror(errno)));
153 return false;
156 if (pst->st_uid != uid && !uid_wrapper_enabled()) {
157 DEBUG(0, ("invalid ownership of file '%s': "
158 "owned by uid %u, should be %u\n",
159 fname, (unsigned int)pst->st_uid,
160 (unsigned int)uid));
161 return false;
164 if ((pst->st_mode & 0777) != file_perms) {
165 DEBUG(0, ("invalid permissions on file "
166 "'%s': has 0%o should be 0%o\n", fname,
167 (unsigned int)(pst->st_mode & 0777),
168 (unsigned int)file_perms));
169 return false;
172 return true;
176 Check if a directory exists.
179 _PUBLIC_ bool directory_exist(const char *dname)
181 struct stat st;
182 bool ret;
184 if (stat(dname,&st) != 0) {
185 return false;
188 ret = S_ISDIR(st.st_mode);
189 if(!ret)
190 errno = ENOTDIR;
191 return ret;
195 * Try to create the specified directory if it didn't exist.
196 * A symlink to a directory is also accepted as a valid existing directory.
198 * @retval true if the directory already existed
199 * or was successfully created.
201 _PUBLIC_ bool directory_create_or_exist(const char *dname,
202 mode_t dir_perms)
204 int ret;
205 mode_t old_umask;
207 /* Create directory */
208 old_umask = umask(0);
209 ret = mkdir(dname, dir_perms);
210 if (ret == -1 && errno != EEXIST) {
211 int dbg_level = geteuid() == 0 ? DBGLVL_ERR : DBGLVL_NOTICE;
213 DBG_PREFIX(dbg_level,
214 ("mkdir failed on directory %s: %s\n",
215 dname,
216 strerror(errno)));
217 umask(old_umask);
218 return false;
220 umask(old_umask);
222 if (ret != 0 && errno == EEXIST) {
223 struct stat sbuf;
225 ret = lstat(dname, &sbuf);
226 if (ret != 0) {
227 return false;
230 if (S_ISDIR(sbuf.st_mode)) {
231 return true;
234 if (S_ISLNK(sbuf.st_mode)) {
235 ret = stat(dname, &sbuf);
236 if (ret != 0) {
237 return false;
240 if (S_ISDIR(sbuf.st_mode)) {
241 return true;
245 return false;
248 return true;
251 _PUBLIC_ bool directory_create_or_exists_recursive(
252 const char *dname,
253 mode_t dir_perms)
255 bool ok;
257 ok = directory_create_or_exist(dname, dir_perms);
258 if (!ok) {
259 if (!directory_exist(dname)) {
260 char tmp[PATH_MAX] = {0};
261 char *parent = NULL;
262 size_t n;
264 /* Use the null context */
265 n = strlcpy(tmp, dname, sizeof(tmp));
266 if (n < strlen(dname)) {
267 DBG_ERR("Path too long!\n");
268 return false;
271 parent = dirname(tmp);
272 if (parent == NULL) {
273 DBG_ERR("Failed to create dirname!\n");
274 return false;
277 ok = directory_create_or_exists_recursive(parent,
278 dir_perms);
279 if (!ok) {
280 return false;
283 ok = directory_create_or_exist(dname, dir_perms);
287 return ok;
291 * @brief Try to create a specified directory if it doesn't exist.
293 * The function creates a directory with the given uid and permissions if it
294 * doesn't exist. If it exists it makes sure the uid and permissions are
295 * correct and it will fail if they are different.
297 * @param[in] dname The directory to create.
299 * @param[in] uid The uid the directory needs to belong too.
301 * @param[in] dir_perms The expected permissions of the directory.
303 * @return True on success, false on error.
305 _PUBLIC_ bool directory_create_or_exist_strict(const char *dname,
306 uid_t uid,
307 mode_t dir_perms)
309 struct stat st;
310 bool ok;
311 int rc;
313 ok = directory_create_or_exist(dname, dir_perms);
314 if (!ok) {
315 return false;
318 rc = lstat(dname, &st);
319 if (rc == -1) {
320 DEBUG(0, ("lstat failed on created directory %s: %s\n",
321 dname, strerror(errno)));
322 return false;
325 /* Check ownership and permission on existing directory */
326 if (!S_ISDIR(st.st_mode)) {
327 DEBUG(0, ("directory %s isn't a directory\n",
328 dname));
329 return false;
331 if (st.st_uid != uid && !uid_wrapper_enabled()) {
332 DBG_NOTICE("invalid ownership on directory "
333 "%s\n", dname);
334 return false;
336 if ((st.st_mode & 0777) != dir_perms) {
337 DEBUG(0, ("invalid permissions on directory "
338 "'%s': has 0%o should be 0%o\n", dname,
339 (unsigned int)(st.st_mode & 0777), (unsigned int)dir_perms));
340 return false;
343 return true;
348 Sleep for a specified number of milliseconds.
351 _PUBLIC_ void smb_msleep(unsigned int t)
353 sys_poll_intr(NULL, 0, t);
357 Get my own name, return in talloc'ed storage.
360 _PUBLIC_ char *get_myname(TALLOC_CTX *ctx)
362 char *p;
363 char hostname[HOST_NAME_MAX];
365 /* get my host name */
366 if (gethostname(hostname, sizeof(hostname)) == -1) {
367 DEBUG(0,("gethostname failed\n"));
368 return NULL;
371 /* Ensure null termination. */
372 hostname[sizeof(hostname)-1] = '\0';
374 /* split off any parts after an initial . */
375 p = strchr_m(hostname, '.');
376 if (p) {
377 *p = 0;
380 return talloc_strdup(ctx, hostname);
384 Check if a process exists. Does this work on all unixes?
387 _PUBLIC_ bool process_exists_by_pid(pid_t pid)
389 /* Doing kill with a non-positive pid causes messages to be
390 * sent to places we don't want. */
391 if (pid <= 0) {
392 return false;
394 return(kill(pid,0) == 0 || errno != ESRCH);
398 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
399 is dealt with in posix.c
402 _PUBLIC_ bool fcntl_lock(int fd, int op, off_t offset, off_t count, int type)
404 struct flock lock;
405 int ret;
407 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
409 lock.l_type = type;
410 lock.l_whence = SEEK_SET;
411 lock.l_start = offset;
412 lock.l_len = count;
413 lock.l_pid = 0;
415 ret = fcntl(fd,op,&lock);
417 if (ret == -1 && errno != 0)
418 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
420 /* a lock query */
421 if (op == F_GETLK) {
422 if ((ret != -1) &&
423 (lock.l_type != F_UNLCK) &&
424 (lock.l_pid != 0) &&
425 (lock.l_pid != getpid())) {
426 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
427 return true;
430 /* it must be not locked or locked by me */
431 return false;
434 /* a lock set or unset */
435 if (ret == -1) {
436 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
437 (double)offset,(double)count,op,type,strerror(errno)));
438 return false;
441 /* everything went OK */
442 DEBUG(8,("fcntl_lock: Lock call successful\n"));
444 return true;
447 struct debug_channel_level {
448 int channel;
449 int level;
452 static void debugadd_channel_cb(const char *buf, void *private_data)
454 struct debug_channel_level *dcl =
455 (struct debug_channel_level *)private_data;
457 DEBUGADDC(dcl->channel, dcl->level,("%s", buf));
460 static void debugadd_cb(const char *buf, void *private_data)
462 int *plevel = (int *)private_data;
463 DEBUGADD(*plevel, ("%s", buf));
466 void print_asc_cb(const uint8_t *buf, int len,
467 void (*cb)(const char *buf, void *private_data),
468 void *private_data)
470 int i;
471 char s[2];
472 s[1] = 0;
474 for (i=0; i<len; i++) {
475 s[0] = isprint(buf[i]) ? buf[i] : '.';
476 cb(s, private_data);
480 void print_asc(int level, const uint8_t *buf,int len)
482 print_asc_cb(buf, len, debugadd_cb, &level);
485 static void dump_data_block16(const char *prefix, size_t idx,
486 const uint8_t *buf, size_t len,
487 void (*cb)(const char *buf, void *private_data),
488 void *private_data)
490 char tmp[16];
491 size_t i;
493 SMB_ASSERT(len >= 0 && len <= 16);
495 snprintf(tmp, sizeof(tmp), "%s[%04zX]", prefix, idx);
496 cb(tmp, private_data);
498 for (i=0; i<16; i++) {
499 if (i == 8) {
500 cb(" ", private_data);
502 if (i < len) {
503 snprintf(tmp, sizeof(tmp), " %02X", (int)buf[i]);
504 } else {
505 snprintf(tmp, sizeof(tmp), " ");
507 cb(tmp, private_data);
510 cb(" ", private_data);
512 if (len == 0) {
513 cb("EMPTY BLOCK\n", private_data);
514 return;
517 for (i=0; i<len; i++) {
518 if (i == 8) {
519 cb(" ", private_data);
521 print_asc_cb(&buf[i], 1, cb, private_data);
524 cb("\n", private_data);
528 * Write dump of binary data to a callback
530 void dump_data_cb(const uint8_t *buf, int len,
531 bool omit_zero_bytes,
532 void (*cb)(const char *buf, void *private_data),
533 void *private_data)
535 int i=0;
536 bool skipped = false;
538 if (len<=0) return;
540 for (i=0;i<len;i+=16) {
541 size_t remaining_len = len - i;
542 size_t this_len = MIN(remaining_len, 16);
543 const uint8_t *this_buf = &buf[i];
545 if ((omit_zero_bytes == true) &&
546 (i > 0) && (remaining_len > 16) &&
547 (this_len == 16) && all_zero(this_buf, 16))
549 if (!skipped) {
550 cb("skipping zero buffer bytes\n",
551 private_data);
552 skipped = true;
554 continue;
557 skipped = false;
558 dump_data_block16("", i, this_buf, this_len,
559 cb, private_data);
564 * Write dump of binary data to the log file.
566 * The data is only written if the log level is at least level.
568 _PUBLIC_ void dump_data(int level, const uint8_t *buf, int len)
570 if (!DEBUGLVL(level)) {
571 return;
573 dump_data_cb(buf, len, false, debugadd_cb, &level);
577 * Write dump of binary data to the log file.
579 * The data is only written if the log level is at least level for
580 * debug class dbgc_class.
582 _PUBLIC_ void dump_data_dbgc(int dbgc_class, int level, const uint8_t *buf, int len)
584 struct debug_channel_level dcl = { dbgc_class, level };
586 if (!DEBUGLVLC(dbgc_class, level)) {
587 return;
589 dump_data_cb(buf, len, false, debugadd_channel_cb, &dcl);
593 * Write dump of binary data to the log file.
595 * The data is only written if the log level is at least level.
596 * 16 zero bytes in a row are omitted
598 _PUBLIC_ void dump_data_skip_zeros(int level, const uint8_t *buf, int len)
600 if (!DEBUGLVL(level)) {
601 return;
603 dump_data_cb(buf, len, true, debugadd_cb, &level);
606 static void fprintf_cb(const char *buf, void *private_data)
608 FILE *f = (FILE *)private_data;
609 fprintf(f, "%s", buf);
612 void dump_data_file(const uint8_t *buf, int len, bool omit_zero_bytes,
613 FILE *f)
615 dump_data_cb(buf, len, omit_zero_bytes, fprintf_cb, f);
619 * Write dump of compared binary data to a callback
621 void dump_data_diff_cb(const uint8_t *buf1, size_t len1,
622 const uint8_t *buf2, size_t len2,
623 bool omit_zero_bytes,
624 void (*cb)(const char *buf, void *private_data),
625 void *private_data)
627 size_t len = MAX(len1, len2);
628 size_t i;
629 bool skipped = false;
631 for (i=0; i<len; i+=16) {
632 size_t remaining_len = len - i;
633 size_t remaining_len1 = 0;
634 size_t this_len1 = 0;
635 const uint8_t *this_buf1 = NULL;
636 size_t remaining_len2 = 0;
637 size_t this_len2 = 0;
638 const uint8_t *this_buf2 = NULL;
640 if (i < len1) {
641 remaining_len1 = len1 - i;
642 this_len1 = MIN(remaining_len1, 16);
643 this_buf1 = &buf1[i];
645 if (i < len2) {
646 remaining_len2 = len2 - i;
647 this_len2 = MIN(remaining_len2, 16);
648 this_buf2 = &buf2[i];
651 if ((omit_zero_bytes == true) &&
652 (i > 0) && (remaining_len > 16) &&
653 (this_len1 == 16) && all_zero(this_buf1, 16) &&
654 (this_len2 == 16) && all_zero(this_buf2, 16))
656 if (!skipped) {
657 cb("skipping zero buffer bytes\n",
658 private_data);
659 skipped = true;
661 continue;
664 skipped = false;
666 if ((this_len1 == this_len2) &&
667 (memcmp(this_buf1, this_buf2, this_len1) == 0))
669 dump_data_block16(" ", i, this_buf1, this_len1,
670 cb, private_data);
671 continue;
674 dump_data_block16("-", i, this_buf1, this_len1,
675 cb, private_data);
676 dump_data_block16("+", i, this_buf2, this_len2,
677 cb, private_data);
681 _PUBLIC_ void dump_data_diff(int dbgc_class, int level,
682 bool omit_zero_bytes,
683 const uint8_t *buf1, size_t len1,
684 const uint8_t *buf2, size_t len2)
686 struct debug_channel_level dcl = { dbgc_class, level };
688 if (!DEBUGLVLC(dbgc_class, level)) {
689 return;
691 dump_data_diff_cb(buf1, len1, buf2, len2, true, debugadd_channel_cb, &dcl);
694 _PUBLIC_ void dump_data_file_diff(FILE *f,
695 bool omit_zero_bytes,
696 const uint8_t *buf1, size_t len1,
697 const uint8_t *buf2, size_t len2)
699 dump_data_diff_cb(buf1, len1, buf2, len2, omit_zero_bytes, fprintf_cb, f);
703 malloc that aborts with smb_panic on fail or zero size.
706 _PUBLIC_ void *smb_xmalloc(size_t size)
708 void *p;
709 if (size == 0)
710 smb_panic("smb_xmalloc: called with zero size.\n");
711 if ((p = malloc(size)) == NULL)
712 smb_panic("smb_xmalloc: malloc fail.\n");
713 return p;
717 Memdup with smb_panic on fail.
720 _PUBLIC_ void *smb_xmemdup(const void *p, size_t size)
722 void *p2;
723 p2 = smb_xmalloc(size);
724 memcpy(p2, p, size);
725 return p2;
729 strdup that aborts on malloc fail.
732 char *smb_xstrdup(const char *s)
734 #if defined(PARANOID_MALLOC_CHECKER)
735 #ifdef strdup
736 #undef strdup
737 #endif
738 #endif
740 #ifndef HAVE_STRDUP
741 #define strdup rep_strdup
742 #endif
744 char *s1 = strdup(s);
745 #if defined(PARANOID_MALLOC_CHECKER)
746 #ifdef strdup
747 #undef strdup
748 #endif
749 #define strdup(s) __ERROR_DONT_USE_STRDUP_DIRECTLY
750 #endif
751 if (!s1) {
752 smb_panic("smb_xstrdup: malloc failed");
754 return s1;
759 strndup that aborts on malloc fail.
762 char *smb_xstrndup(const char *s, size_t n)
764 #if defined(PARANOID_MALLOC_CHECKER)
765 #ifdef strndup
766 #undef strndup
767 #endif
768 #endif
770 #if (defined(BROKEN_STRNDUP) || !defined(HAVE_STRNDUP))
771 #undef HAVE_STRNDUP
772 #define strndup rep_strndup
773 #endif
775 char *s1 = strndup(s, n);
776 #if defined(PARANOID_MALLOC_CHECKER)
777 #ifdef strndup
778 #undef strndup
779 #endif
780 #define strndup(s,n) __ERROR_DONT_USE_STRNDUP_DIRECTLY
781 #endif
782 if (!s1) {
783 smb_panic("smb_xstrndup: malloc failed");
785 return s1;
791 Like strdup but for memory.
794 _PUBLIC_ void *smb_memdup(const void *p, size_t size)
796 void *p2;
797 if (size == 0)
798 return NULL;
799 p2 = malloc(size);
800 if (!p2)
801 return NULL;
802 memcpy(p2, p, size);
803 return p2;
807 * Write a password to the log file.
809 * @note Only actually does something if DEBUG_PASSWORD was defined during
810 * compile-time.
812 _PUBLIC_ void dump_data_pw(const char *msg, const uint8_t * data, size_t len)
814 #ifdef DEBUG_PASSWORD
815 DEBUG(11, ("%s", msg));
816 if (data != NULL && len > 0)
818 dump_data(11, data, len);
820 #endif
825 * see if a range of memory is all zero. A NULL pointer is considered
826 * to be all zero
828 _PUBLIC_ bool all_zero(const uint8_t *ptr, size_t size)
830 size_t i;
831 if (!ptr) return true;
832 for (i=0;i<size;i++) {
833 if (ptr[i]) return false;
835 return true;
839 realloc an array, checking for integer overflow in the array size
841 _PUBLIC_ void *realloc_array(void *ptr, size_t el_size, unsigned count, bool free_on_fail)
843 #define MAX_MALLOC_SIZE 0x7fffffff
844 if (count == 0 ||
845 count >= MAX_MALLOC_SIZE/el_size) {
846 if (free_on_fail)
847 SAFE_FREE(ptr);
848 return NULL;
850 if (!ptr) {
851 return malloc(el_size * count);
853 return realloc(ptr, el_size * count);
856 /****************************************************************************
857 Type-safe malloc.
858 ****************************************************************************/
860 void *malloc_array(size_t el_size, unsigned int count)
862 return realloc_array(NULL, el_size, count, false);
865 /****************************************************************************
866 Type-safe memalign
867 ****************************************************************************/
869 void *memalign_array(size_t el_size, size_t align, unsigned int count)
871 if (el_size == 0 || count >= MAX_MALLOC_SIZE/el_size) {
872 return NULL;
875 return memalign(align, el_size*count);
878 /****************************************************************************
879 Type-safe calloc.
880 ****************************************************************************/
882 void *calloc_array(size_t size, size_t nmemb)
884 if (nmemb >= MAX_MALLOC_SIZE/size) {
885 return NULL;
887 if (size == 0 || nmemb == 0) {
888 return NULL;
890 return calloc(nmemb, size);
894 Trim the specified elements off the front and back of a string.
896 _PUBLIC_ bool trim_string(char *s, const char *front, const char *back)
898 bool ret = false;
899 size_t front_len;
900 size_t back_len;
901 size_t len;
903 /* Ignore null or empty strings. */
904 if (!s || (s[0] == '\0')) {
905 return false;
907 len = strlen(s);
909 front_len = front? strlen(front) : 0;
910 back_len = back? strlen(back) : 0;
912 if (front_len) {
913 size_t front_trim = 0;
915 while (strncmp(s+front_trim, front, front_len)==0) {
916 front_trim += front_len;
918 if (front_trim > 0) {
919 /* Must use memmove here as src & dest can
920 * easily overlap. Found by valgrind. JRA. */
921 memmove(s, s+front_trim, (len-front_trim)+1);
922 len -= front_trim;
923 ret=true;
927 if (back_len) {
928 while ((len >= back_len) && strncmp(s+len-back_len,back,back_len)==0) {
929 s[len-back_len]='\0';
930 len -= back_len;
931 ret=true;
934 return ret;
938 Find the number of 'c' chars in a string
940 _PUBLIC_ _PURE_ size_t count_chars(const char *s, char c)
942 size_t count = 0;
944 while (*s) {
945 if (*s == c) count++;
946 s ++;
949 return count;
953 * Routine to get hex characters and turn them into a byte array.
954 * the array can be variable length.
955 * - "0xnn" or "0Xnn" is specially catered for.
956 * - The first non-hex-digit character (apart from possibly leading "0x"
957 * finishes the conversion and skips the rest of the input.
958 * - A single hex-digit character at the end of the string is skipped.
960 * valid examples: "0A5D15"; "0x123456"
962 _PUBLIC_ size_t strhex_to_str(char *p, size_t p_len, const char *strhex, size_t strhex_len)
964 size_t i = 0;
965 size_t num_chars = 0;
967 /* skip leading 0x prefix */
968 if (strncasecmp(strhex, "0x", 2) == 0) {
969 i += 2; /* skip two chars */
972 while ((i < strhex_len) && (num_chars < p_len)) {
973 bool ok = hex_byte(&strhex[i], (uint8_t *)&p[num_chars]);
974 if (!ok) {
975 break;
977 i += 2;
978 num_chars += 1;
981 return num_chars;
985 * Parse a hex string and return a data blob.
987 _PUBLIC_ DATA_BLOB strhex_to_data_blob(TALLOC_CTX *mem_ctx, const char *strhex)
989 DATA_BLOB ret_blob = data_blob_talloc(mem_ctx, NULL, strlen(strhex)/2+1);
991 ret_blob.length = strhex_to_str((char *)ret_blob.data, ret_blob.length,
992 strhex,
993 strlen(strhex));
995 return ret_blob;
999 * Parse a hex dump and return a data blob. Hex dump is structured as
1000 * is generated from dump_data_cb() elsewhere in this file
1003 _PUBLIC_ DATA_BLOB hexdump_to_data_blob(TALLOC_CTX *mem_ctx, const char *hexdump, size_t hexdump_len)
1005 DATA_BLOB ret_blob = { 0 };
1006 size_t i = 0;
1007 size_t char_count = 0;
1008 /* hexdump line length is 77 chars long. We then use the ASCII representation of the bytes
1009 * at the end of the final line to calculate how many are in that line, minus the extra space
1010 * and newline. */
1011 size_t hexdump_byte_count = (16 * (hexdump_len / 77));
1012 if (hexdump_len % 77) {
1013 hexdump_byte_count += ((hexdump_len % 77) - 59 - 2);
1016 ret_blob = data_blob_talloc(mem_ctx, NULL, hexdump_byte_count+1);
1017 for (; i+1 < hexdump_len && hexdump[i] != 0 && hexdump[i+1] != 0; i++) {
1018 if ((i%77) == 0)
1019 i += 7; /* Skip the offset at the start of the line */
1020 if ((i%77) < 56) { /* position 56 is after both hex chunks */
1021 if (hexdump[i] != ' ') {
1022 char_count += strhex_to_str((char *)&ret_blob.data[char_count],
1023 hexdump_byte_count - char_count,
1024 &hexdump[i], 2);
1025 i += 2;
1026 } else {
1027 i++;
1029 } else {
1030 i++;
1033 ret_blob.length = char_count;
1035 return ret_blob;
1039 * Print a buf in hex. Assumes dst is at least (srclen*2)+1 large.
1041 _PUBLIC_ void hex_encode_buf(char *dst, const uint8_t *src, size_t srclen)
1043 size_t i;
1044 for (i=0; i<srclen; i++) {
1045 snprintf(dst + i*2, 3, "%02X", src[i]);
1048 * Ensure 0-termination for 0-length buffers
1050 dst[srclen*2] = '\0';
1054 * talloc version of hex_encode_buf()
1056 _PUBLIC_ char *hex_encode_talloc(TALLOC_CTX *mem_ctx, const unsigned char *buff_in, size_t len)
1058 char *hex_buffer;
1060 hex_buffer = talloc_array(mem_ctx, char, (len*2)+1);
1061 if (!hex_buffer) {
1062 return NULL;
1064 hex_encode_buf(hex_buffer, buff_in, len);
1065 talloc_set_name_const(hex_buffer, hex_buffer);
1066 return hex_buffer;
1070 varient of strcmp() that handles NULL ptrs
1072 _PUBLIC_ int strcmp_safe(const char *s1, const char *s2)
1074 if (s1 == s2) {
1075 return 0;
1077 if (s1 == NULL || s2 == NULL) {
1078 return s1?-1:1;
1080 return strcmp(s1, s2);
1085 return the number of bytes occupied by a buffer in ASCII format
1086 the result includes the null termination
1087 limited by 'n' bytes
1089 _PUBLIC_ size_t ascii_len_n(const char *src, size_t n)
1091 size_t len;
1093 len = strnlen(src, n);
1094 if (len+1 <= n) {
1095 len += 1;
1098 return len;
1101 _PUBLIC_ bool mem_equal_const_time(const void *s1, const void *s2, size_t n)
1103 /* Ensure we won't overflow the unsigned index used by gnutls. */
1104 SMB_ASSERT(n <= UINT_MAX);
1106 return gnutls_memcmp(s1, s2, n) == 0;
1109 struct anonymous_shared_header {
1110 union {
1111 size_t length;
1112 uint8_t pad[16];
1113 } u;
1116 /* Map a shared memory buffer of at least nelem counters. */
1117 void *anonymous_shared_allocate(size_t orig_bufsz)
1119 void *ptr;
1120 void *buf;
1121 size_t pagesz = getpagesize();
1122 size_t pagecnt;
1123 size_t bufsz = orig_bufsz;
1124 struct anonymous_shared_header *hdr;
1126 bufsz += sizeof(*hdr);
1128 /* round up to full pages */
1129 pagecnt = bufsz / pagesz;
1130 if (bufsz % pagesz) {
1131 pagecnt += 1;
1133 bufsz = pagesz * pagecnt;
1135 if (orig_bufsz >= bufsz) {
1136 /* integer wrap */
1137 errno = ENOMEM;
1138 return NULL;
1141 #ifdef MAP_ANON
1142 /* BSD */
1143 buf = mmap(NULL, bufsz, PROT_READ|PROT_WRITE, MAP_ANON|MAP_SHARED,
1144 -1 /* fd */, 0 /* offset */);
1145 #else
1147 int saved_errno;
1148 int fd;
1150 fd = open("/dev/zero", O_RDWR);
1151 if (fd == -1) {
1152 return NULL;
1155 buf = mmap(NULL, bufsz, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED,
1156 fd, 0 /* offset */);
1157 saved_errno = errno;
1158 close(fd);
1159 errno = saved_errno;
1161 #endif
1163 if (buf == MAP_FAILED) {
1164 return NULL;
1167 hdr = (struct anonymous_shared_header *)buf;
1168 hdr->u.length = bufsz;
1170 ptr = (void *)(&hdr[1]);
1172 return ptr;
1175 void *anonymous_shared_resize(void *ptr, size_t new_size, bool maymove)
1177 #ifdef HAVE_MREMAP
1178 void *buf;
1179 size_t pagesz = getpagesize();
1180 size_t pagecnt;
1181 size_t bufsz;
1182 struct anonymous_shared_header *hdr;
1183 int flags = 0;
1185 if (ptr == NULL) {
1186 errno = EINVAL;
1187 return NULL;
1190 hdr = (struct anonymous_shared_header *)ptr;
1191 hdr--;
1192 if (hdr->u.length > (new_size + sizeof(*hdr))) {
1193 errno = EINVAL;
1194 return NULL;
1197 bufsz = new_size + sizeof(*hdr);
1199 /* round up to full pages */
1200 pagecnt = bufsz / pagesz;
1201 if (bufsz % pagesz) {
1202 pagecnt += 1;
1204 bufsz = pagesz * pagecnt;
1206 if (new_size >= bufsz) {
1207 /* integer wrap */
1208 errno = ENOSPC;
1209 return NULL;
1212 if (bufsz <= hdr->u.length) {
1213 return ptr;
1216 if (maymove) {
1217 flags = MREMAP_MAYMOVE;
1220 buf = mremap(hdr, hdr->u.length, bufsz, flags);
1222 if (buf == MAP_FAILED) {
1223 errno = ENOSPC;
1224 return NULL;
1227 hdr = (struct anonymous_shared_header *)buf;
1228 hdr->u.length = bufsz;
1230 ptr = (void *)(&hdr[1]);
1232 return ptr;
1233 #else
1234 errno = ENOSPC;
1235 return NULL;
1236 #endif
1239 void anonymous_shared_free(void *ptr)
1241 struct anonymous_shared_header *hdr;
1243 if (ptr == NULL) {
1244 return;
1247 hdr = (struct anonymous_shared_header *)ptr;
1249 hdr--;
1251 munmap(hdr, hdr->u.length);
1254 #ifdef DEVELOPER
1255 /* used when you want a debugger started at a particular point in the
1256 code. Mostly useful in code that runs as a child process, where
1257 normal gdb attach is harder to organise.
1259 void samba_start_debugger(void)
1261 int ready_pipe[2];
1262 char c;
1263 int ret;
1264 pid_t pid;
1266 ret = pipe(ready_pipe);
1267 SMB_ASSERT(ret == 0);
1269 pid = fork();
1270 SMB_ASSERT(pid >= 0);
1272 if (pid) {
1273 c = 0;
1275 ret = close(ready_pipe[0]);
1276 SMB_ASSERT(ret == 0);
1277 #if defined(HAVE_PRCTL) && defined(PR_SET_PTRACER)
1279 * Make sure the child process can attach a debugger.
1281 * We don't check the error code as the debugger
1282 * will tell us if it can't attach.
1284 (void)prctl(PR_SET_PTRACER, pid, 0, 0, 0);
1285 #endif
1286 ret = write(ready_pipe[1], &c, 1);
1287 SMB_ASSERT(ret == 1);
1289 ret = close(ready_pipe[1]);
1290 SMB_ASSERT(ret == 0);
1292 /* Wait for gdb to attach. */
1293 sleep(2);
1294 } else {
1295 char *cmd = NULL;
1297 ret = close(ready_pipe[1]);
1298 SMB_ASSERT(ret == 0);
1300 ret = read(ready_pipe[0], &c, 1);
1301 SMB_ASSERT(ret == 1);
1303 ret = close(ready_pipe[0]);
1304 SMB_ASSERT(ret == 0);
1306 ret = asprintf(&cmd, "gdb --pid %u", getppid());
1307 SMB_ASSERT(ret != -1);
1309 execlp("xterm", "xterm", "-e", cmd, (char *) NULL);
1310 smb_panic("execlp() failed");
1313 #endif