s3: smbd: Move check_fsp_open() and check_fsp() to smb1_reply.c
[Samba.git] / lib / util / util.c
blob02d1cbfda17f46d2d645a0ac481cd141be495eb9
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 Check a files mod time.
122 _PUBLIC_ time_t file_modtime(const char *fname)
124 struct stat st;
126 if (stat(fname,&st) != 0)
127 return(0);
129 return(st.st_mtime);
133 Check file permissions.
136 _PUBLIC_ bool file_check_permissions(const char *fname,
137 uid_t uid,
138 mode_t file_perms,
139 struct stat *pst)
141 int ret;
142 struct stat st;
144 if (pst == NULL) {
145 pst = &st;
148 ZERO_STRUCTP(pst);
150 ret = stat(fname, pst);
151 if (ret != 0) {
152 DEBUG(0, ("stat failed on file '%s': %s\n",
153 fname, strerror(errno)));
154 return false;
157 if (pst->st_uid != uid && !uid_wrapper_enabled()) {
158 DEBUG(0, ("invalid ownership of file '%s': "
159 "owned by uid %u, should be %u\n",
160 fname, (unsigned int)pst->st_uid,
161 (unsigned int)uid));
162 return false;
165 if ((pst->st_mode & 0777) != file_perms) {
166 DEBUG(0, ("invalid permissions on file "
167 "'%s': has 0%o should be 0%o\n", fname,
168 (unsigned int)(pst->st_mode & 0777),
169 (unsigned int)file_perms));
170 return false;
173 return true;
177 Check if a directory exists.
180 _PUBLIC_ bool directory_exist(const char *dname)
182 struct stat st;
183 bool ret;
185 if (stat(dname,&st) != 0) {
186 return false;
189 ret = S_ISDIR(st.st_mode);
190 if(!ret)
191 errno = ENOTDIR;
192 return ret;
196 * Try to create the specified directory if it didn't exist.
197 * A symlink to a directory is also accepted as a valid existing directory.
199 * @retval true if the directory already existed
200 * or was successfully created.
202 _PUBLIC_ bool directory_create_or_exist(const char *dname,
203 mode_t dir_perms)
205 int ret;
206 mode_t old_umask;
208 /* Create directory */
209 old_umask = umask(0);
210 ret = mkdir(dname, dir_perms);
211 if (ret == -1 && errno != EEXIST) {
212 int dbg_level = geteuid() == 0 ? DBGLVL_ERR : DBGLVL_NOTICE;
214 DBG_PREFIX(dbg_level,
215 ("mkdir failed on directory %s: %s\n",
216 dname,
217 strerror(errno)));
218 umask(old_umask);
219 return false;
221 umask(old_umask);
223 if (ret != 0 && errno == EEXIST) {
224 struct stat sbuf;
226 ret = lstat(dname, &sbuf);
227 if (ret != 0) {
228 return false;
231 if (S_ISDIR(sbuf.st_mode)) {
232 return true;
235 if (S_ISLNK(sbuf.st_mode)) {
236 ret = stat(dname, &sbuf);
237 if (ret != 0) {
238 return false;
241 if (S_ISDIR(sbuf.st_mode)) {
242 return true;
246 return false;
249 return true;
252 _PUBLIC_ bool directory_create_or_exists_recursive(
253 const char *dname,
254 mode_t dir_perms)
256 bool ok;
258 ok = directory_create_or_exist(dname, dir_perms);
259 if (!ok) {
260 if (!directory_exist(dname)) {
261 char tmp[PATH_MAX] = {0};
262 char *parent = NULL;
263 size_t n;
265 /* Use the null context */
266 n = strlcpy(tmp, dname, sizeof(tmp));
267 if (n < strlen(dname)) {
268 DBG_ERR("Path too long!\n");
269 return false;
272 parent = dirname(tmp);
273 if (parent == NULL) {
274 DBG_ERR("Failed to create dirname!\n");
275 return false;
278 ok = directory_create_or_exists_recursive(parent,
279 dir_perms);
280 if (!ok) {
281 return false;
284 ok = directory_create_or_exist(dname, dir_perms);
288 return ok;
292 * @brief Try to create a specified directory if it doesn't exist.
294 * The function creates a directory with the given uid and permissions if it
295 * doesn't exist. If it exists it makes sure the uid and permissions are
296 * correct and it will fail if they are different.
298 * @param[in] dname The directory to create.
300 * @param[in] uid The uid the directory needs to belong too.
302 * @param[in] dir_perms The expected permissions of the directory.
304 * @return True on success, false on error.
306 _PUBLIC_ bool directory_create_or_exist_strict(const char *dname,
307 uid_t uid,
308 mode_t dir_perms)
310 struct stat st;
311 bool ok;
312 int rc;
314 ok = directory_create_or_exist(dname, dir_perms);
315 if (!ok) {
316 return false;
319 rc = lstat(dname, &st);
320 if (rc == -1) {
321 DEBUG(0, ("lstat failed on created directory %s: %s\n",
322 dname, strerror(errno)));
323 return false;
326 /* Check ownership and permission on existing directory */
327 if (!S_ISDIR(st.st_mode)) {
328 DEBUG(0, ("directory %s isn't a directory\n",
329 dname));
330 return false;
332 if (st.st_uid != uid && !uid_wrapper_enabled()) {
333 DBG_NOTICE("invalid ownership on directory "
334 "%s\n", dname);
335 return false;
337 if ((st.st_mode & 0777) != dir_perms) {
338 DEBUG(0, ("invalid permissions on directory "
339 "'%s': has 0%o should be 0%o\n", dname,
340 (unsigned int)(st.st_mode & 0777), (unsigned int)dir_perms));
341 return false;
344 return true;
349 Sleep for a specified number of milliseconds.
352 _PUBLIC_ void smb_msleep(unsigned int t)
354 sys_poll_intr(NULL, 0, t);
358 Get my own name, return in talloc'ed storage.
361 _PUBLIC_ char *get_myname(TALLOC_CTX *ctx)
363 char *p;
364 char hostname[HOST_NAME_MAX];
366 /* get my host name */
367 if (gethostname(hostname, sizeof(hostname)) == -1) {
368 DEBUG(0,("gethostname failed\n"));
369 return NULL;
372 /* Ensure null termination. */
373 hostname[sizeof(hostname)-1] = '\0';
375 /* split off any parts after an initial . */
376 p = strchr_m(hostname, '.');
377 if (p) {
378 *p = 0;
381 return talloc_strdup(ctx, hostname);
385 Check if a process exists. Does this work on all unixes?
388 _PUBLIC_ bool process_exists_by_pid(pid_t pid)
390 /* Doing kill with a non-positive pid causes messages to be
391 * sent to places we don't want. */
392 if (pid <= 0) {
393 return false;
395 return(kill(pid,0) == 0 || errno != ESRCH);
399 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
400 is dealt with in posix.c
403 _PUBLIC_ bool fcntl_lock(int fd, int op, off_t offset, off_t count, int type)
405 struct flock lock;
406 int ret;
408 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
410 lock.l_type = type;
411 lock.l_whence = SEEK_SET;
412 lock.l_start = offset;
413 lock.l_len = count;
414 lock.l_pid = 0;
416 ret = fcntl(fd,op,&lock);
418 if (ret == -1 && errno != 0)
419 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
421 /* a lock query */
422 if (op == F_GETLK) {
423 if ((ret != -1) &&
424 (lock.l_type != F_UNLCK) &&
425 (lock.l_pid != 0) &&
426 (lock.l_pid != tevent_cached_getpid())) {
427 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
428 return true;
431 /* it must be not locked or locked by me */
432 return false;
435 /* a lock set or unset */
436 if (ret == -1) {
437 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
438 (double)offset,(double)count,op,type,strerror(errno)));
439 return false;
442 /* everything went OK */
443 DEBUG(8,("fcntl_lock: Lock call successful\n"));
445 return true;
448 struct debug_channel_level {
449 int channel;
450 int level;
453 static void debugadd_channel_cb(const char *buf, void *private_data)
455 struct debug_channel_level *dcl =
456 (struct debug_channel_level *)private_data;
458 DEBUGADDC(dcl->channel, dcl->level,("%s", buf));
461 static void debugadd_cb(const char *buf, void *private_data)
463 int *plevel = (int *)private_data;
464 DEBUGADD(*plevel, ("%s", buf));
467 void print_asc_cb(const uint8_t *buf, int len,
468 void (*cb)(const char *buf, void *private_data),
469 void *private_data)
471 int i;
472 char s[2];
473 s[1] = 0;
475 for (i=0; i<len; i++) {
476 s[0] = isprint(buf[i]) ? buf[i] : '.';
477 cb(s, private_data);
481 void print_asc(int level, const uint8_t *buf,int len)
483 print_asc_cb(buf, len, debugadd_cb, &level);
486 static void dump_data_block16(const char *prefix, size_t idx,
487 const uint8_t *buf, size_t len,
488 void (*cb)(const char *buf, void *private_data),
489 void *private_data)
491 char tmp[16];
492 size_t i;
494 SMB_ASSERT(len >= 0 && len <= 16);
496 snprintf(tmp, sizeof(tmp), "%s[%04zX]", prefix, idx);
497 cb(tmp, private_data);
499 for (i=0; i<16; i++) {
500 if (i == 8) {
501 cb(" ", private_data);
503 if (i < len) {
504 snprintf(tmp, sizeof(tmp), " %02X", (int)buf[i]);
505 } else {
506 snprintf(tmp, sizeof(tmp), " ");
508 cb(tmp, private_data);
511 cb(" ", private_data);
513 if (len == 0) {
514 cb("EMPTY BLOCK\n", private_data);
515 return;
518 for (i=0; i<len; i++) {
519 if (i == 8) {
520 cb(" ", private_data);
522 print_asc_cb(&buf[i], 1, cb, private_data);
525 cb("\n", private_data);
529 * Write dump of binary data to a callback
531 void dump_data_cb(const uint8_t *buf, int len,
532 bool omit_zero_bytes,
533 void (*cb)(const char *buf, void *private_data),
534 void *private_data)
536 int i=0;
537 bool skipped = false;
539 if (len<=0) return;
541 for (i=0;i<len;i+=16) {
542 size_t remaining_len = len - i;
543 size_t this_len = MIN(remaining_len, 16);
544 const uint8_t *this_buf = &buf[i];
546 if ((omit_zero_bytes == true) &&
547 (i > 0) && (remaining_len > 16) &&
548 (this_len == 16) && all_zero(this_buf, 16))
550 if (!skipped) {
551 cb("skipping zero buffer bytes\n",
552 private_data);
553 skipped = true;
555 continue;
558 skipped = false;
559 dump_data_block16("", i, this_buf, this_len,
560 cb, private_data);
565 * Write dump of binary data to the log file.
567 * The data is only written if the log level is at least level.
569 _PUBLIC_ void dump_data(int level, const uint8_t *buf, int len)
571 if (!DEBUGLVL(level)) {
572 return;
574 dump_data_cb(buf, len, false, debugadd_cb, &level);
578 * Write dump of binary data to the log file.
580 * The data is only written if the log level is at least level for
581 * debug class dbgc_class.
583 _PUBLIC_ void dump_data_dbgc(int dbgc_class, int level, const uint8_t *buf, int len)
585 struct debug_channel_level dcl = { dbgc_class, level };
587 if (!DEBUGLVLC(dbgc_class, level)) {
588 return;
590 dump_data_cb(buf, len, false, debugadd_channel_cb, &dcl);
594 * Write dump of binary data to the log file.
596 * The data is only written if the log level is at least level.
597 * 16 zero bytes in a row are omitted
599 _PUBLIC_ void dump_data_skip_zeros(int level, const uint8_t *buf, int len)
601 if (!DEBUGLVL(level)) {
602 return;
604 dump_data_cb(buf, len, true, debugadd_cb, &level);
607 static void fprintf_cb(const char *buf, void *private_data)
609 FILE *f = (FILE *)private_data;
610 fprintf(f, "%s", buf);
613 void dump_data_file(const uint8_t *buf, int len, bool omit_zero_bytes,
614 FILE *f)
616 dump_data_cb(buf, len, omit_zero_bytes, fprintf_cb, f);
620 * Write dump of compared binary data to a callback
622 void dump_data_diff_cb(const uint8_t *buf1, size_t len1,
623 const uint8_t *buf2, size_t len2,
624 bool omit_zero_bytes,
625 void (*cb)(const char *buf, void *private_data),
626 void *private_data)
628 size_t len = MAX(len1, len2);
629 size_t i;
630 bool skipped = false;
632 for (i=0; i<len; i+=16) {
633 size_t remaining_len = len - i;
634 size_t remaining_len1 = 0;
635 size_t this_len1 = 0;
636 const uint8_t *this_buf1 = NULL;
637 size_t remaining_len2 = 0;
638 size_t this_len2 = 0;
639 const uint8_t *this_buf2 = NULL;
641 if (i < len1) {
642 remaining_len1 = len1 - i;
643 this_len1 = MIN(remaining_len1, 16);
644 this_buf1 = &buf1[i];
646 if (i < len2) {
647 remaining_len2 = len2 - i;
648 this_len2 = MIN(remaining_len2, 16);
649 this_buf2 = &buf2[i];
652 if ((omit_zero_bytes == true) &&
653 (i > 0) && (remaining_len > 16) &&
654 (this_len1 == 16) && all_zero(this_buf1, 16) &&
655 (this_len2 == 16) && all_zero(this_buf2, 16))
657 if (!skipped) {
658 cb("skipping zero buffer bytes\n",
659 private_data);
660 skipped = true;
662 continue;
665 skipped = false;
667 if ((this_len1 == this_len2) &&
668 (memcmp(this_buf1, this_buf2, this_len1) == 0))
670 dump_data_block16(" ", i, this_buf1, this_len1,
671 cb, private_data);
672 continue;
675 dump_data_block16("-", i, this_buf1, this_len1,
676 cb, private_data);
677 dump_data_block16("+", i, this_buf2, this_len2,
678 cb, private_data);
682 _PUBLIC_ void dump_data_diff(int dbgc_class, int level,
683 bool omit_zero_bytes,
684 const uint8_t *buf1, size_t len1,
685 const uint8_t *buf2, size_t len2)
687 struct debug_channel_level dcl = { dbgc_class, level };
689 if (!DEBUGLVLC(dbgc_class, level)) {
690 return;
692 dump_data_diff_cb(buf1, len1, buf2, len2, true, debugadd_channel_cb, &dcl);
695 _PUBLIC_ void dump_data_file_diff(FILE *f,
696 bool omit_zero_bytes,
697 const uint8_t *buf1, size_t len1,
698 const uint8_t *buf2, size_t len2)
700 dump_data_diff_cb(buf1, len1, buf2, len2, omit_zero_bytes, fprintf_cb, f);
704 malloc that aborts with smb_panic on fail or zero size.
707 _PUBLIC_ void *smb_xmalloc(size_t size)
709 void *p;
710 if (size == 0)
711 smb_panic("smb_xmalloc: called with zero size.\n");
712 if ((p = malloc(size)) == NULL)
713 smb_panic("smb_xmalloc: malloc fail.\n");
714 return p;
718 Memdup with smb_panic on fail.
721 _PUBLIC_ void *smb_xmemdup(const void *p, size_t size)
723 void *p2;
724 p2 = smb_xmalloc(size);
725 memcpy(p2, p, size);
726 return p2;
730 strdup that aborts on malloc fail.
733 char *smb_xstrdup(const char *s)
735 #if defined(PARANOID_MALLOC_CHECKER)
736 #ifdef strdup
737 #undef strdup
738 #endif
739 #endif
741 #ifndef HAVE_STRDUP
742 #define strdup rep_strdup
743 #endif
745 char *s1 = strdup(s);
746 #if defined(PARANOID_MALLOC_CHECKER)
747 #ifdef strdup
748 #undef strdup
749 #endif
750 #define strdup(s) __ERROR_DONT_USE_STRDUP_DIRECTLY
751 #endif
752 if (!s1) {
753 smb_panic("smb_xstrdup: malloc failed");
755 return s1;
760 strndup that aborts on malloc fail.
763 char *smb_xstrndup(const char *s, size_t n)
765 #if defined(PARANOID_MALLOC_CHECKER)
766 #ifdef strndup
767 #undef strndup
768 #endif
769 #endif
771 #if (defined(BROKEN_STRNDUP) || !defined(HAVE_STRNDUP))
772 #undef HAVE_STRNDUP
773 #define strndup rep_strndup
774 #endif
776 char *s1 = strndup(s, n);
777 #if defined(PARANOID_MALLOC_CHECKER)
778 #ifdef strndup
779 #undef strndup
780 #endif
781 #define strndup(s,n) __ERROR_DONT_USE_STRNDUP_DIRECTLY
782 #endif
783 if (!s1) {
784 smb_panic("smb_xstrndup: malloc failed");
786 return s1;
792 Like strdup but for memory.
795 _PUBLIC_ void *smb_memdup(const void *p, size_t size)
797 void *p2;
798 if (size == 0)
799 return NULL;
800 p2 = malloc(size);
801 if (!p2)
802 return NULL;
803 memcpy(p2, p, size);
804 return p2;
808 * Write a password to the log file.
810 * @note Only actually does something if DEBUG_PASSWORD was defined during
811 * compile-time.
813 _PUBLIC_ void dump_data_pw(const char *msg, const uint8_t * data, size_t len)
815 #ifdef DEBUG_PASSWORD
816 DEBUG(11, ("%s", msg));
817 if (data != NULL && len > 0)
819 dump_data(11, data, len);
821 #endif
826 * see if a range of memory is all zero. A NULL pointer is considered
827 * to be all zero
829 _PUBLIC_ bool all_zero(const uint8_t *ptr, size_t size)
831 size_t i;
832 if (!ptr) return true;
833 for (i=0;i<size;i++) {
834 if (ptr[i]) return false;
836 return true;
840 realloc an array, checking for integer overflow in the array size
842 _PUBLIC_ void *realloc_array(void *ptr, size_t el_size, unsigned count, bool free_on_fail)
844 #define MAX_MALLOC_SIZE 0x7fffffff
845 if (count == 0 ||
846 count >= MAX_MALLOC_SIZE/el_size) {
847 if (free_on_fail)
848 SAFE_FREE(ptr);
849 return NULL;
851 if (!ptr) {
852 return malloc(el_size * count);
854 return realloc(ptr, el_size * count);
857 /****************************************************************************
858 Type-safe malloc.
859 ****************************************************************************/
861 void *malloc_array(size_t el_size, unsigned int count)
863 return realloc_array(NULL, el_size, count, false);
866 /****************************************************************************
867 Type-safe memalign
868 ****************************************************************************/
870 void *memalign_array(size_t el_size, size_t align, unsigned int count)
872 if (el_size == 0 || count >= MAX_MALLOC_SIZE/el_size) {
873 return NULL;
876 return memalign(align, el_size*count);
879 /****************************************************************************
880 Type-safe calloc.
881 ****************************************************************************/
883 void *calloc_array(size_t size, size_t nmemb)
885 if (nmemb >= MAX_MALLOC_SIZE/size) {
886 return NULL;
888 if (size == 0 || nmemb == 0) {
889 return NULL;
891 return calloc(nmemb, size);
895 Trim the specified elements off the front and back of a string.
897 _PUBLIC_ bool trim_string(char *s, const char *front, const char *back)
899 bool ret = false;
900 size_t front_len;
901 size_t back_len;
902 size_t len;
904 /* Ignore null or empty strings. */
905 if (!s || (s[0] == '\0')) {
906 return false;
908 len = strlen(s);
910 front_len = front? strlen(front) : 0;
911 back_len = back? strlen(back) : 0;
913 if (front_len) {
914 size_t front_trim = 0;
916 while (strncmp(s+front_trim, front, front_len)==0) {
917 front_trim += front_len;
919 if (front_trim > 0) {
920 /* Must use memmove here as src & dest can
921 * easily overlap. Found by valgrind. JRA. */
922 memmove(s, s+front_trim, (len-front_trim)+1);
923 len -= front_trim;
924 ret=true;
928 if (back_len) {
929 while ((len >= back_len) && strncmp(s+len-back_len,back,back_len)==0) {
930 s[len-back_len]='\0';
931 len -= back_len;
932 ret=true;
935 return ret;
939 Find the number of 'c' chars in a string
941 _PUBLIC_ _PURE_ size_t count_chars(const char *s, char c)
943 size_t count = 0;
945 while (*s) {
946 if (*s == c) count++;
947 s ++;
950 return count;
954 * Routine to get hex characters and turn them into a byte array.
955 * the array can be variable length.
956 * - "0xnn" or "0Xnn" is specially catered for.
957 * - The first non-hex-digit character (apart from possibly leading "0x"
958 * finishes the conversion and skips the rest of the input.
959 * - A single hex-digit character at the end of the string is skipped.
961 * valid examples: "0A5D15"; "0x123456"
963 _PUBLIC_ size_t strhex_to_str(char *p, size_t p_len, const char *strhex, size_t strhex_len)
965 size_t i = 0;
966 size_t num_chars = 0;
968 /* skip leading 0x prefix */
969 if (strncasecmp(strhex, "0x", 2) == 0) {
970 i += 2; /* skip two chars */
973 while ((i < strhex_len) && (num_chars < p_len)) {
974 bool ok = hex_byte(&strhex[i], (uint8_t *)&p[num_chars]);
975 if (!ok) {
976 break;
978 i += 2;
979 num_chars += 1;
982 return num_chars;
986 * Parse a hex string and return a data blob.
988 _PUBLIC_ DATA_BLOB strhex_to_data_blob(TALLOC_CTX *mem_ctx, const char *strhex)
990 DATA_BLOB ret_blob = data_blob_talloc(mem_ctx, NULL, strlen(strhex)/2+1);
992 ret_blob.length = strhex_to_str((char *)ret_blob.data, ret_blob.length,
993 strhex,
994 strlen(strhex));
996 return ret_blob;
1000 * Parse a hex dump and return a data blob. Hex dump is structured as
1001 * is generated from dump_data_cb() elsewhere in this file
1004 _PUBLIC_ DATA_BLOB hexdump_to_data_blob(TALLOC_CTX *mem_ctx, const char *hexdump, size_t hexdump_len)
1006 DATA_BLOB ret_blob = { 0 };
1007 size_t i = 0;
1008 size_t char_count = 0;
1009 /* hexdump line length is 77 chars long. We then use the ASCII representation of the bytes
1010 * at the end of the final line to calculate how many are in that line, minus the extra space
1011 * and newline. */
1012 size_t hexdump_byte_count = (16 * (hexdump_len / 77));
1013 if (hexdump_len % 77) {
1014 hexdump_byte_count += ((hexdump_len % 77) - 59 - 2);
1017 ret_blob = data_blob_talloc(mem_ctx, NULL, hexdump_byte_count+1);
1018 for (; i+1 < hexdump_len && hexdump[i] != 0 && hexdump[i+1] != 0; i++) {
1019 if ((i%77) == 0)
1020 i += 7; /* Skip the offset at the start of the line */
1021 if ((i%77) < 56) { /* position 56 is after both hex chunks */
1022 if (hexdump[i] != ' ') {
1023 char_count += strhex_to_str((char *)&ret_blob.data[char_count],
1024 hexdump_byte_count - char_count,
1025 &hexdump[i], 2);
1026 i += 2;
1027 } else {
1028 i++;
1030 } else {
1031 i++;
1034 ret_blob.length = char_count;
1036 return ret_blob;
1040 * Print a buf in hex. Assumes dst is at least (srclen*2)+1 large.
1042 _PUBLIC_ void hex_encode_buf(char *dst, const uint8_t *src, size_t srclen)
1044 size_t i;
1045 for (i=0; i<srclen; i++) {
1046 snprintf(dst + i*2, 3, "%02X", src[i]);
1049 * Ensure 0-termination for 0-length buffers
1051 dst[srclen*2] = '\0';
1055 * talloc version of hex_encode_buf()
1057 _PUBLIC_ char *hex_encode_talloc(TALLOC_CTX *mem_ctx, const unsigned char *buff_in, size_t len)
1059 char *hex_buffer;
1061 hex_buffer = talloc_array(mem_ctx, char, (len*2)+1);
1062 if (!hex_buffer) {
1063 return NULL;
1065 hex_encode_buf(hex_buffer, buff_in, len);
1066 talloc_set_name_const(hex_buffer, hex_buffer);
1067 return hex_buffer;
1071 varient of strcmp() that handles NULL ptrs
1073 _PUBLIC_ int strcmp_safe(const char *s1, const char *s2)
1075 if (s1 == s2) {
1076 return 0;
1078 if (s1 == NULL || s2 == NULL) {
1079 return s1?-1:1;
1081 return strcmp(s1, s2);
1086 return the number of bytes occupied by a buffer in ASCII format
1087 the result includes the null termination
1088 limited by 'n' bytes
1090 _PUBLIC_ size_t ascii_len_n(const char *src, size_t n)
1092 size_t len;
1094 len = strnlen(src, n);
1095 if (len+1 <= n) {
1096 len += 1;
1099 return len;
1102 _PUBLIC_ bool mem_equal_const_time(const void *s1, const void *s2, size_t n)
1104 /* Ensure we won't overflow the unsigned index used by gnutls. */
1105 SMB_ASSERT(n <= UINT_MAX);
1107 return gnutls_memcmp(s1, s2, n) == 0;
1110 struct anonymous_shared_header {
1111 union {
1112 size_t length;
1113 uint8_t pad[16];
1114 } u;
1117 /* Map a shared memory buffer of at least nelem counters. */
1118 void *anonymous_shared_allocate(size_t orig_bufsz)
1120 void *ptr;
1121 void *buf;
1122 size_t pagesz = getpagesize();
1123 size_t pagecnt;
1124 size_t bufsz = orig_bufsz;
1125 struct anonymous_shared_header *hdr;
1127 bufsz += sizeof(*hdr);
1129 /* round up to full pages */
1130 pagecnt = bufsz / pagesz;
1131 if (bufsz % pagesz) {
1132 pagecnt += 1;
1134 bufsz = pagesz * pagecnt;
1136 if (orig_bufsz >= bufsz) {
1137 /* integer wrap */
1138 errno = ENOMEM;
1139 return NULL;
1142 #ifdef MAP_ANON
1143 /* BSD */
1144 buf = mmap(NULL, bufsz, PROT_READ|PROT_WRITE, MAP_ANON|MAP_SHARED,
1145 -1 /* fd */, 0 /* offset */);
1146 #else
1148 int saved_errno;
1149 int fd;
1151 fd = open("/dev/zero", O_RDWR);
1152 if (fd == -1) {
1153 return NULL;
1156 buf = mmap(NULL, bufsz, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED,
1157 fd, 0 /* offset */);
1158 saved_errno = errno;
1159 close(fd);
1160 errno = saved_errno;
1162 #endif
1164 if (buf == MAP_FAILED) {
1165 return NULL;
1168 hdr = (struct anonymous_shared_header *)buf;
1169 hdr->u.length = bufsz;
1171 ptr = (void *)(&hdr[1]);
1173 return ptr;
1176 void *anonymous_shared_resize(void *ptr, size_t new_size, bool maymove)
1178 #ifdef HAVE_MREMAP
1179 void *buf;
1180 size_t pagesz = getpagesize();
1181 size_t pagecnt;
1182 size_t bufsz;
1183 struct anonymous_shared_header *hdr;
1184 int flags = 0;
1186 if (ptr == NULL) {
1187 errno = EINVAL;
1188 return NULL;
1191 hdr = (struct anonymous_shared_header *)ptr;
1192 hdr--;
1193 if (hdr->u.length > (new_size + sizeof(*hdr))) {
1194 errno = EINVAL;
1195 return NULL;
1198 bufsz = new_size + sizeof(*hdr);
1200 /* round up to full pages */
1201 pagecnt = bufsz / pagesz;
1202 if (bufsz % pagesz) {
1203 pagecnt += 1;
1205 bufsz = pagesz * pagecnt;
1207 if (new_size >= bufsz) {
1208 /* integer wrap */
1209 errno = ENOSPC;
1210 return NULL;
1213 if (bufsz <= hdr->u.length) {
1214 return ptr;
1217 if (maymove) {
1218 flags = MREMAP_MAYMOVE;
1221 buf = mremap(hdr, hdr->u.length, bufsz, flags);
1223 if (buf == MAP_FAILED) {
1224 errno = ENOSPC;
1225 return NULL;
1228 hdr = (struct anonymous_shared_header *)buf;
1229 hdr->u.length = bufsz;
1231 ptr = (void *)(&hdr[1]);
1233 return ptr;
1234 #else
1235 errno = ENOSPC;
1236 return NULL;
1237 #endif
1240 void anonymous_shared_free(void *ptr)
1242 struct anonymous_shared_header *hdr;
1244 if (ptr == NULL) {
1245 return;
1248 hdr = (struct anonymous_shared_header *)ptr;
1250 hdr--;
1252 munmap(hdr, hdr->u.length);
1255 #ifdef DEVELOPER
1256 /* used when you want a debugger started at a particular point in the
1257 code. Mostly useful in code that runs as a child process, where
1258 normal gdb attach is harder to organise.
1260 void samba_start_debugger(void)
1262 int ready_pipe[2];
1263 char c;
1264 int ret;
1265 pid_t pid;
1267 ret = pipe(ready_pipe);
1268 SMB_ASSERT(ret == 0);
1270 pid = fork();
1271 SMB_ASSERT(pid >= 0);
1273 if (pid) {
1274 c = 0;
1276 ret = close(ready_pipe[0]);
1277 SMB_ASSERT(ret == 0);
1278 #if defined(HAVE_PRCTL) && defined(PR_SET_PTRACER)
1280 * Make sure the child process can attach a debugger.
1282 * We don't check the error code as the debugger
1283 * will tell us if it can't attach.
1285 (void)prctl(PR_SET_PTRACER, pid, 0, 0, 0);
1286 #endif
1287 ret = write(ready_pipe[1], &c, 1);
1288 SMB_ASSERT(ret == 1);
1290 ret = close(ready_pipe[1]);
1291 SMB_ASSERT(ret == 0);
1293 /* Wait for gdb to attach. */
1294 sleep(2);
1295 } else {
1296 char *cmd = NULL;
1298 ret = close(ready_pipe[1]);
1299 SMB_ASSERT(ret == 0);
1301 ret = read(ready_pipe[0], &c, 1);
1302 SMB_ASSERT(ret == 1);
1304 ret = close(ready_pipe[0]);
1305 SMB_ASSERT(ret == 0);
1307 ret = asprintf(&cmd, "gdb --pid %u", getppid());
1308 SMB_ASSERT(ret != -1);
1310 execlp("xterm", "xterm", "-e", cmd, (char *) NULL);
1311 smb_panic("execlp() failed");
1314 #endif