lib:util: Move debug message for mkdir failing to log level 1
[Samba.git] / lib / util / util.c
blobb8eed3ca28c526de78807cf2936d0618538d794b
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
11 This program is free software; you can redistribute it and/or modify
12 it under the terms of the GNU General Public License as published by
13 the Free Software Foundation; either version 3 of the License, or
14 (at your option) any later version.
16 This program is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 GNU General Public License for more details.
21 You should have received a copy of the GNU General Public License
22 along with this program. If not, see <http://www.gnu.org/licenses/>.
25 #include "replace.h"
26 #include <talloc.h>
27 #include "system/network.h"
28 #include "system/filesys.h"
29 #include "system/locale.h"
30 #include "system/shmem.h"
31 #include "system/passwd.h"
32 #include "system/time.h"
33 #include "system/wait.h"
34 #include "debug.h"
35 #include "samba_util.h"
36 #include "lib/util/select.h"
38 #undef malloc
39 #undef strcasecmp
40 #undef strncasecmp
41 #undef strdup
42 #undef realloc
43 #undef calloc
45 /**
46 * @file
47 * @brief Misc utility functions
50 /**
51 * Convert a string to an unsigned long integer
53 * @param nptr pointer to string which is to be converted
54 * @param endptr [optional] reference to remainder of the string
55 * @param base base of the numbering scheme
56 * @param err error occured during conversion
57 * @result result of the conversion as provided by strtoul
59 * The following errors are detected
60 * - wrong base
61 * - value overflow
62 * - string with a leading "-" indicating a negative number
64 unsigned long int
65 strtoul_err(const char *nptr, char **endptr, int base, int *err)
67 unsigned long int val;
68 int saved_errno = errno;
69 char *needle = NULL;
70 char *tmp_endptr = NULL;
72 errno = 0;
73 *err = 0;
75 val = strtoul(nptr, &tmp_endptr, base);
77 if (endptr != NULL) {
78 *endptr = tmp_endptr;
81 if (errno != 0) {
82 *err = errno;
83 errno = saved_errno;
84 return val;
87 /* did we convert a negative "number" ? */
88 needle = strchr(nptr, '-');
89 if (needle != NULL && needle < tmp_endptr) {
90 *err = EINVAL;
93 errno = saved_errno;
94 return val;
97 /**
98 * Convert a string to an unsigned long long integer
100 * @param nptr pointer to string which is to be converted
101 * @param endptr [optional] reference to remainder of the string
102 * @param base base of the numbering scheme
103 * @param err error occured during conversion
104 * @result result of the conversion as provided by strtoull
106 * The following errors are detected
107 * - wrong base
108 * - value overflow
109 * - string with a leading "-" indicating a negative number
111 unsigned long long int
112 strtoull_err(const char *nptr, char **endptr, int base, int *err)
114 unsigned long long int val;
115 int saved_errno = errno;
116 char *needle = NULL;
117 char *tmp_endptr = NULL;
119 errno = 0;
120 *err = 0;
122 val = strtoull(nptr, &tmp_endptr, base);
124 if (endptr != NULL) {
125 *endptr = tmp_endptr;
128 if (errno != 0) {
129 *err = errno;
130 errno = saved_errno;
131 return val;
134 /* did we convert a negative "number" ? */
135 needle = strchr(nptr, '-');
136 if (needle != NULL && needle < tmp_endptr) {
137 *err = EINVAL;
140 errno = saved_errno;
141 return val;
145 Find a suitable temporary directory. The result should be copied immediately
146 as it may be overwritten by a subsequent call.
148 _PUBLIC_ const char *tmpdir(void)
150 char *p;
151 if ((p = getenv("TMPDIR")))
152 return p;
153 return "/tmp";
158 Create a tmp file, open it and immediately unlink it.
159 If dir is NULL uses tmpdir()
160 Returns the file descriptor or -1 on error.
162 int create_unlink_tmp(const char *dir)
164 size_t len = strlen(dir ? dir : (dir = tmpdir()));
165 char fname[len+25];
166 int fd;
167 mode_t mask;
169 len = snprintf(fname, sizeof(fname), "%s/listenerlock_XXXXXX", dir);
170 if (len >= sizeof(fname)) {
171 errno = ENOMEM;
172 return -1;
174 mask = umask(S_IRWXO | S_IRWXG);
175 fd = mkstemp(fname);
176 umask(mask);
177 if (fd == -1) {
178 return -1;
180 if (unlink(fname) == -1) {
181 int sys_errno = errno;
182 close(fd);
183 errno = sys_errno;
184 return -1;
186 return fd;
191 Check if a file exists - call vfs_file_exist for samba files.
193 _PUBLIC_ bool file_exist(const char *fname)
195 struct stat st;
197 if (stat(fname, &st) != 0) {
198 return false;
201 return ((S_ISREG(st.st_mode)) || (S_ISFIFO(st.st_mode)));
205 Check a files mod time.
208 _PUBLIC_ time_t file_modtime(const char *fname)
210 struct stat st;
212 if (stat(fname,&st) != 0)
213 return(0);
215 return(st.st_mtime);
219 Check file permissions.
222 _PUBLIC_ bool file_check_permissions(const char *fname,
223 uid_t uid,
224 mode_t file_perms,
225 struct stat *pst)
227 int ret;
228 struct stat st;
230 if (pst == NULL) {
231 pst = &st;
234 ZERO_STRUCTP(pst);
236 ret = stat(fname, pst);
237 if (ret != 0) {
238 DEBUG(0, ("stat failed on file '%s': %s\n",
239 fname, strerror(errno)));
240 return false;
243 if (pst->st_uid != uid && !uid_wrapper_enabled()) {
244 DEBUG(0, ("invalid ownership of file '%s': "
245 "owned by uid %u, should be %u\n",
246 fname, (unsigned int)pst->st_uid,
247 (unsigned int)uid));
248 return false;
251 if ((pst->st_mode & 0777) != file_perms) {
252 DEBUG(0, ("invalid permissions on file "
253 "'%s': has 0%o should be 0%o\n", fname,
254 (unsigned int)(pst->st_mode & 0777),
255 (unsigned int)file_perms));
256 return false;
259 return true;
263 Check if a directory exists.
266 _PUBLIC_ bool directory_exist(const char *dname)
268 struct stat st;
269 bool ret;
271 if (stat(dname,&st) != 0) {
272 return false;
275 ret = S_ISDIR(st.st_mode);
276 if(!ret)
277 errno = ENOTDIR;
278 return ret;
282 * Try to create the specified directory if it didn't exist.
284 * @retval true if the directory already existed
285 * or was successfully created.
287 _PUBLIC_ bool directory_create_or_exist(const char *dname,
288 mode_t dir_perms)
290 int ret;
291 mode_t old_umask;
293 /* Create directory */
294 old_umask = umask(0);
295 ret = mkdir(dname, dir_perms);
296 if (ret == -1 && errno != EEXIST) {
297 DBG_WARNING("mkdir failed on directory %s: %s\n",
298 dname,
299 strerror(errno));
300 umask(old_umask);
301 return false;
303 umask(old_umask);
305 if (ret != 0 && errno == EEXIST) {
306 struct stat sbuf;
308 ret = lstat(dname, &sbuf);
309 if (ret != 0) {
310 return false;
313 if (!S_ISDIR(sbuf.st_mode)) {
314 return false;
318 return true;
322 * @brief Try to create a specified directory if it doesn't exist.
324 * The function creates a directory with the given uid and permissions if it
325 * doesn't exist. If it exists it makes sure the uid and permissions are
326 * correct and it will fail if they are different.
328 * @param[in] dname The directory to create.
330 * @param[in] uid The uid the directory needs to belong too.
332 * @param[in] dir_perms The expected permissions of the directory.
334 * @return True on success, false on error.
336 _PUBLIC_ bool directory_create_or_exist_strict(const char *dname,
337 uid_t uid,
338 mode_t dir_perms)
340 struct stat st;
341 bool ok;
342 int rc;
344 ok = directory_create_or_exist(dname, dir_perms);
345 if (!ok) {
346 return false;
349 rc = lstat(dname, &st);
350 if (rc == -1) {
351 DEBUG(0, ("lstat failed on created directory %s: %s\n",
352 dname, strerror(errno)));
353 return false;
356 /* Check ownership and permission on existing directory */
357 if (!S_ISDIR(st.st_mode)) {
358 DEBUG(0, ("directory %s isn't a directory\n",
359 dname));
360 return false;
362 if (st.st_uid != uid && !uid_wrapper_enabled()) {
363 DBG_NOTICE("invalid ownership on directory "
364 "%s\n", dname);
365 return false;
367 if ((st.st_mode & 0777) != dir_perms) {
368 DEBUG(0, ("invalid permissions on directory "
369 "'%s': has 0%o should be 0%o\n", dname,
370 (unsigned int)(st.st_mode & 0777), (unsigned int)dir_perms));
371 return false;
374 return true;
379 Sleep for a specified number of milliseconds.
382 _PUBLIC_ void smb_msleep(unsigned int t)
384 sys_poll_intr(NULL, 0, t);
388 Get my own name, return in talloc'ed storage.
391 _PUBLIC_ char *get_myname(TALLOC_CTX *ctx)
393 char *p;
394 char hostname[HOST_NAME_MAX];
396 /* get my host name */
397 if (gethostname(hostname, sizeof(hostname)) == -1) {
398 DEBUG(0,("gethostname failed\n"));
399 return NULL;
402 /* Ensure null termination. */
403 hostname[sizeof(hostname)-1] = '\0';
405 /* split off any parts after an initial . */
406 p = strchr_m(hostname, '.');
407 if (p) {
408 *p = 0;
411 return talloc_strdup(ctx, hostname);
415 Check if a process exists. Does this work on all unixes?
418 _PUBLIC_ bool process_exists_by_pid(pid_t pid)
420 /* Doing kill with a non-positive pid causes messages to be
421 * sent to places we don't want. */
422 if (pid <= 0) {
423 return false;
425 return(kill(pid,0) == 0 || errno != ESRCH);
429 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
430 is dealt with in posix.c
433 _PUBLIC_ bool fcntl_lock(int fd, int op, off_t offset, off_t count, int type)
435 struct flock lock;
436 int ret;
438 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
440 lock.l_type = type;
441 lock.l_whence = SEEK_SET;
442 lock.l_start = offset;
443 lock.l_len = count;
444 lock.l_pid = 0;
446 ret = fcntl(fd,op,&lock);
448 if (ret == -1 && errno != 0)
449 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
451 /* a lock query */
452 if (op == F_GETLK) {
453 if ((ret != -1) &&
454 (lock.l_type != F_UNLCK) &&
455 (lock.l_pid != 0) &&
456 (lock.l_pid != getpid())) {
457 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
458 return true;
461 /* it must be not locked or locked by me */
462 return false;
465 /* a lock set or unset */
466 if (ret == -1) {
467 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
468 (double)offset,(double)count,op,type,strerror(errno)));
469 return false;
472 /* everything went OK */
473 DEBUG(8,("fcntl_lock: Lock call successful\n"));
475 return true;
478 struct debug_channel_level {
479 int channel;
480 int level;
483 static void debugadd_channel_cb(const char *buf, void *private_data)
485 struct debug_channel_level *dcl =
486 (struct debug_channel_level *)private_data;
488 DEBUGADDC(dcl->channel, dcl->level,("%s", buf));
491 static void debugadd_cb(const char *buf, void *private_data)
493 int *plevel = (int *)private_data;
494 DEBUGADD(*plevel, ("%s", buf));
497 void print_asc_cb(const uint8_t *buf, int len,
498 void (*cb)(const char *buf, void *private_data),
499 void *private_data)
501 int i;
502 char s[2];
503 s[1] = 0;
505 for (i=0; i<len; i++) {
506 s[0] = isprint(buf[i]) ? buf[i] : '.';
507 cb(s, private_data);
511 void print_asc(int level, const uint8_t *buf,int len)
513 print_asc_cb(buf, len, debugadd_cb, &level);
517 * Write dump of binary data to a callback
519 void dump_data_cb(const uint8_t *buf, int len,
520 bool omit_zero_bytes,
521 void (*cb)(const char *buf, void *private_data),
522 void *private_data)
524 int i=0;
525 bool skipped = false;
526 char tmp[16];
528 if (len<=0) return;
530 for (i=0;i<len;) {
532 if (i%16 == 0) {
533 if ((omit_zero_bytes == true) &&
534 (i > 0) &&
535 (len > i+16) &&
536 all_zero(&buf[i], 16))
538 i +=16;
539 continue;
542 if (i<len) {
543 snprintf(tmp, sizeof(tmp), "[%04X] ", i);
544 cb(tmp, private_data);
548 snprintf(tmp, sizeof(tmp), "%02X ", (int)buf[i]);
549 cb(tmp, private_data);
550 i++;
551 if (i%8 == 0) {
552 cb(" ", private_data);
554 if (i%16 == 0) {
556 print_asc_cb(&buf[i-16], 8, cb, private_data);
557 cb(" ", private_data);
558 print_asc_cb(&buf[i-8], 8, cb, private_data);
559 cb("\n", private_data);
561 if ((omit_zero_bytes == true) &&
562 (len > i+16) &&
563 all_zero(&buf[i], 16)) {
564 if (!skipped) {
565 cb("skipping zero buffer bytes\n",
566 private_data);
567 skipped = true;
573 if (i%16) {
574 int n;
575 n = 16 - (i%16);
576 cb(" ", private_data);
577 if (n>8) {
578 cb(" ", private_data);
580 while (n--) {
581 cb(" ", private_data);
583 n = MIN(8,i%16);
584 print_asc_cb(&buf[i-(i%16)], n, cb, private_data);
585 cb(" ", private_data);
586 n = (i%16) - n;
587 if (n>0) {
588 print_asc_cb(&buf[i-n], n, cb, private_data);
590 cb("\n", private_data);
596 * Write dump of binary data to the log file.
598 * The data is only written if the log level is at least level.
600 _PUBLIC_ void dump_data(int level, const uint8_t *buf, int len)
602 if (!DEBUGLVL(level)) {
603 return;
605 dump_data_cb(buf, len, false, debugadd_cb, &level);
609 * Write dump of binary data to the log file.
611 * The data is only written if the log level is at least level for
612 * debug class dbgc_class.
614 _PUBLIC_ void dump_data_dbgc(int dbgc_class, int level, const uint8_t *buf, int len)
616 struct debug_channel_level dcl = { dbgc_class, level };
618 if (!DEBUGLVLC(dbgc_class, level)) {
619 return;
621 dump_data_cb(buf, len, false, debugadd_channel_cb, &dcl);
625 * Write dump of binary data to the log file.
627 * The data is only written if the log level is at least level.
628 * 16 zero bytes in a row are omitted
630 _PUBLIC_ void dump_data_skip_zeros(int level, const uint8_t *buf, int len)
632 if (!DEBUGLVL(level)) {
633 return;
635 dump_data_cb(buf, len, true, debugadd_cb, &level);
638 static void fprintf_cb(const char *buf, void *private_data)
640 FILE *f = (FILE *)private_data;
641 fprintf(f, "%s", buf);
644 void dump_data_file(const uint8_t *buf, int len, bool omit_zero_bytes,
645 FILE *f)
647 dump_data_cb(buf, len, omit_zero_bytes, fprintf_cb, f);
651 malloc that aborts with smb_panic on fail or zero size.
654 _PUBLIC_ void *smb_xmalloc(size_t size)
656 void *p;
657 if (size == 0)
658 smb_panic("smb_xmalloc: called with zero size.\n");
659 if ((p = malloc(size)) == NULL)
660 smb_panic("smb_xmalloc: malloc fail.\n");
661 return p;
665 Memdup with smb_panic on fail.
668 _PUBLIC_ void *smb_xmemdup(const void *p, size_t size)
670 void *p2;
671 p2 = smb_xmalloc(size);
672 memcpy(p2, p, size);
673 return p2;
677 strdup that aborts on malloc fail.
680 char *smb_xstrdup(const char *s)
682 #if defined(PARANOID_MALLOC_CHECKER)
683 #ifdef strdup
684 #undef strdup
685 #endif
686 #endif
688 #ifndef HAVE_STRDUP
689 #define strdup rep_strdup
690 #endif
692 char *s1 = strdup(s);
693 #if defined(PARANOID_MALLOC_CHECKER)
694 #ifdef strdup
695 #undef strdup
696 #endif
697 #define strdup(s) __ERROR_DONT_USE_STRDUP_DIRECTLY
698 #endif
699 if (!s1) {
700 smb_panic("smb_xstrdup: malloc failed");
702 return s1;
707 strndup that aborts on malloc fail.
710 char *smb_xstrndup(const char *s, size_t n)
712 #if defined(PARANOID_MALLOC_CHECKER)
713 #ifdef strndup
714 #undef strndup
715 #endif
716 #endif
718 #if (defined(BROKEN_STRNDUP) || !defined(HAVE_STRNDUP))
719 #undef HAVE_STRNDUP
720 #define strndup rep_strndup
721 #endif
723 char *s1 = strndup(s, n);
724 #if defined(PARANOID_MALLOC_CHECKER)
725 #ifdef strndup
726 #undef strndup
727 #endif
728 #define strndup(s,n) __ERROR_DONT_USE_STRNDUP_DIRECTLY
729 #endif
730 if (!s1) {
731 smb_panic("smb_xstrndup: malloc failed");
733 return s1;
739 Like strdup but for memory.
742 _PUBLIC_ void *smb_memdup(const void *p, size_t size)
744 void *p2;
745 if (size == 0)
746 return NULL;
747 p2 = malloc(size);
748 if (!p2)
749 return NULL;
750 memcpy(p2, p, size);
751 return p2;
755 * Write a password to the log file.
757 * @note Only actually does something if DEBUG_PASSWORD was defined during
758 * compile-time.
760 _PUBLIC_ void dump_data_pw(const char *msg, const uint8_t * data, size_t len)
762 #ifdef DEBUG_PASSWORD
763 DEBUG(11, ("%s", msg));
764 if (data != NULL && len > 0)
766 dump_data(11, data, len);
768 #endif
773 * see if a range of memory is all zero. A NULL pointer is considered
774 * to be all zero
776 _PUBLIC_ bool all_zero(const uint8_t *ptr, size_t size)
778 size_t i;
779 if (!ptr) return true;
780 for (i=0;i<size;i++) {
781 if (ptr[i]) return false;
783 return true;
787 realloc an array, checking for integer overflow in the array size
789 _PUBLIC_ void *realloc_array(void *ptr, size_t el_size, unsigned count, bool free_on_fail)
791 #define MAX_MALLOC_SIZE 0x7fffffff
792 if (count == 0 ||
793 count >= MAX_MALLOC_SIZE/el_size) {
794 if (free_on_fail)
795 SAFE_FREE(ptr);
796 return NULL;
798 if (!ptr) {
799 return malloc(el_size * count);
801 return realloc(ptr, el_size * count);
804 /****************************************************************************
805 Type-safe malloc.
806 ****************************************************************************/
808 void *malloc_array(size_t el_size, unsigned int count)
810 return realloc_array(NULL, el_size, count, false);
813 /****************************************************************************
814 Type-safe memalign
815 ****************************************************************************/
817 void *memalign_array(size_t el_size, size_t align, unsigned int count)
819 if (el_size == 0 || count >= MAX_MALLOC_SIZE/el_size) {
820 return NULL;
823 return memalign(align, el_size*count);
826 /****************************************************************************
827 Type-safe calloc.
828 ****************************************************************************/
830 void *calloc_array(size_t size, size_t nmemb)
832 if (nmemb >= MAX_MALLOC_SIZE/size) {
833 return NULL;
835 if (size == 0 || nmemb == 0) {
836 return NULL;
838 return calloc(nmemb, size);
842 Trim the specified elements off the front and back of a string.
844 _PUBLIC_ bool trim_string(char *s, const char *front, const char *back)
846 bool ret = false;
847 size_t front_len;
848 size_t back_len;
849 size_t len;
851 /* Ignore null or empty strings. */
852 if (!s || (s[0] == '\0')) {
853 return false;
855 len = strlen(s);
857 front_len = front? strlen(front) : 0;
858 back_len = back? strlen(back) : 0;
860 if (front_len) {
861 size_t front_trim = 0;
863 while (strncmp(s+front_trim, front, front_len)==0) {
864 front_trim += front_len;
866 if (front_trim > 0) {
867 /* Must use memmove here as src & dest can
868 * easily overlap. Found by valgrind. JRA. */
869 memmove(s, s+front_trim, (len-front_trim)+1);
870 len -= front_trim;
871 ret=true;
875 if (back_len) {
876 while ((len >= back_len) && strncmp(s+len-back_len,back,back_len)==0) {
877 s[len-back_len]='\0';
878 len -= back_len;
879 ret=true;
882 return ret;
886 Find the number of 'c' chars in a string
888 _PUBLIC_ _PURE_ size_t count_chars(const char *s, char c)
890 size_t count = 0;
892 while (*s) {
893 if (*s == c) count++;
894 s ++;
897 return count;
901 * Routine to get hex characters and turn them into a byte array.
902 * the array can be variable length.
903 * - "0xnn" or "0Xnn" is specially catered for.
904 * - The first non-hex-digit character (apart from possibly leading "0x"
905 * finishes the conversion and skips the rest of the input.
906 * - A single hex-digit character at the end of the string is skipped.
908 * valid examples: "0A5D15"; "0x123456"
910 _PUBLIC_ size_t strhex_to_str(char *p, size_t p_len, const char *strhex, size_t strhex_len)
912 size_t i = 0;
913 size_t num_chars = 0;
914 uint8_t lonybble, hinybble;
915 const char *hexchars = "0123456789ABCDEF";
916 char *p1 = NULL, *p2 = NULL;
918 /* skip leading 0x prefix */
919 if (strncasecmp(strhex, "0x", 2) == 0) {
920 i += 2; /* skip two chars */
923 for (; i+1 < strhex_len && strhex[i] != 0 && strhex[i+1] != 0; i++) {
924 p1 = strchr(hexchars, toupper((unsigned char)strhex[i]));
925 if (p1 == NULL) {
926 break;
929 i++; /* next hex digit */
931 p2 = strchr(hexchars, toupper((unsigned char)strhex[i]));
932 if (p2 == NULL) {
933 break;
936 /* get the two nybbles */
937 hinybble = PTR_DIFF(p1, hexchars);
938 lonybble = PTR_DIFF(p2, hexchars);
940 if (num_chars >= p_len) {
941 break;
944 p[num_chars] = (hinybble << 4) | lonybble;
945 num_chars++;
947 p1 = NULL;
948 p2 = NULL;
950 return num_chars;
954 * Parse a hex string and return a data blob.
956 _PUBLIC_ _PURE_ DATA_BLOB strhex_to_data_blob(TALLOC_CTX *mem_ctx, const char *strhex)
958 DATA_BLOB ret_blob = data_blob_talloc(mem_ctx, NULL, strlen(strhex)/2+1);
960 ret_blob.length = strhex_to_str((char *)ret_blob.data, ret_blob.length,
961 strhex,
962 strlen(strhex));
964 return ret_blob;
968 * Parse a hex dump and return a data blob. Hex dump is structured as
969 * is generated from dump_data_cb() elsewhere in this file
972 _PUBLIC_ _PURE_ DATA_BLOB hexdump_to_data_blob(TALLOC_CTX *mem_ctx, const char *hexdump, size_t hexdump_len)
974 DATA_BLOB ret_blob = { 0 };
975 size_t i = 0;
976 size_t char_count = 0;
977 /* hexdump line length is 77 chars long. We then use the ASCII representation of the bytes
978 * at the end of the final line to calculate how many are in that line, minus the extra space
979 * and newline. */
980 size_t hexdump_byte_count = (16 * (hexdump_len / 77));
981 if (hexdump_len % 77) {
982 hexdump_byte_count += ((hexdump_len % 77) - 59 - 2);
985 ret_blob = data_blob_talloc(mem_ctx, NULL, hexdump_byte_count+1);
986 for (; i+1 < hexdump_len && hexdump[i] != 0 && hexdump[i+1] != 0; i++) {
987 if ((i%77) == 0)
988 i += 7; /* Skip the offset at the start of the line */
989 if ((i%77) < 56) { /* position 56 is after both hex chunks */
990 if (hexdump[i] != ' ') {
991 char_count += strhex_to_str((char *)&ret_blob.data[char_count],
992 hexdump_byte_count - char_count,
993 &hexdump[i], 2);
994 i += 2;
995 } else {
996 i++;
998 } else {
999 i++;
1002 ret_blob.length = char_count;
1004 return ret_blob;
1008 * Print a buf in hex. Assumes dst is at least (srclen*2)+1 large.
1010 _PUBLIC_ void hex_encode_buf(char *dst, const uint8_t *src, size_t srclen)
1012 size_t i;
1013 for (i=0; i<srclen; i++) {
1014 snprintf(dst + i*2, 3, "%02X", src[i]);
1017 * Ensure 0-termination for 0-length buffers
1019 dst[srclen*2] = '\0';
1023 * talloc version of hex_encode_buf()
1025 _PUBLIC_ char *hex_encode_talloc(TALLOC_CTX *mem_ctx, const unsigned char *buff_in, size_t len)
1027 char *hex_buffer;
1029 hex_buffer = talloc_array(mem_ctx, char, (len*2)+1);
1030 if (!hex_buffer) {
1031 return NULL;
1033 hex_encode_buf(hex_buffer, buff_in, len);
1034 talloc_set_name_const(hex_buffer, hex_buffer);
1035 return hex_buffer;
1039 varient of strcmp() that handles NULL ptrs
1041 _PUBLIC_ int strcmp_safe(const char *s1, const char *s2)
1043 if (s1 == s2) {
1044 return 0;
1046 if (s1 == NULL || s2 == NULL) {
1047 return s1?-1:1;
1049 return strcmp(s1, s2);
1054 return the number of bytes occupied by a buffer in ASCII format
1055 the result includes the null termination
1056 limited by 'n' bytes
1058 _PUBLIC_ size_t ascii_len_n(const char *src, size_t n)
1060 size_t len;
1062 len = strnlen(src, n);
1063 if (len+1 <= n) {
1064 len += 1;
1067 return len;
1070 struct anonymous_shared_header {
1071 union {
1072 size_t length;
1073 uint8_t pad[16];
1074 } u;
1077 /* Map a shared memory buffer of at least nelem counters. */
1078 void *anonymous_shared_allocate(size_t orig_bufsz)
1080 void *ptr;
1081 void *buf;
1082 size_t pagesz = getpagesize();
1083 size_t pagecnt;
1084 size_t bufsz = orig_bufsz;
1085 struct anonymous_shared_header *hdr;
1087 bufsz += sizeof(*hdr);
1089 /* round up to full pages */
1090 pagecnt = bufsz / pagesz;
1091 if (bufsz % pagesz) {
1092 pagecnt += 1;
1094 bufsz = pagesz * pagecnt;
1096 if (orig_bufsz >= bufsz) {
1097 /* integer wrap */
1098 errno = ENOMEM;
1099 return NULL;
1102 #ifdef MAP_ANON
1103 /* BSD */
1104 buf = mmap(NULL, bufsz, PROT_READ|PROT_WRITE, MAP_ANON|MAP_SHARED,
1105 -1 /* fd */, 0 /* offset */);
1106 #else
1108 int saved_errno;
1109 int fd;
1111 fd = open("/dev/zero", O_RDWR);
1112 if (fd == -1) {
1113 return NULL;
1116 buf = mmap(NULL, bufsz, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED,
1117 fd, 0 /* offset */);
1118 saved_errno = errno;
1119 close(fd);
1120 errno = saved_errno;
1122 #endif
1124 if (buf == MAP_FAILED) {
1125 return NULL;
1128 hdr = (struct anonymous_shared_header *)buf;
1129 hdr->u.length = bufsz;
1131 ptr = (void *)(&hdr[1]);
1133 return ptr;
1136 void *anonymous_shared_resize(void *ptr, size_t new_size, bool maymove)
1138 #ifdef HAVE_MREMAP
1139 void *buf;
1140 size_t pagesz = getpagesize();
1141 size_t pagecnt;
1142 size_t bufsz;
1143 struct anonymous_shared_header *hdr;
1144 int flags = 0;
1146 if (ptr == NULL) {
1147 errno = EINVAL;
1148 return NULL;
1151 hdr = (struct anonymous_shared_header *)ptr;
1152 hdr--;
1153 if (hdr->u.length > (new_size + sizeof(*hdr))) {
1154 errno = EINVAL;
1155 return NULL;
1158 bufsz = new_size + sizeof(*hdr);
1160 /* round up to full pages */
1161 pagecnt = bufsz / pagesz;
1162 if (bufsz % pagesz) {
1163 pagecnt += 1;
1165 bufsz = pagesz * pagecnt;
1167 if (new_size >= bufsz) {
1168 /* integer wrap */
1169 errno = ENOSPC;
1170 return NULL;
1173 if (bufsz <= hdr->u.length) {
1174 return ptr;
1177 if (maymove) {
1178 flags = MREMAP_MAYMOVE;
1181 buf = mremap(hdr, hdr->u.length, bufsz, flags);
1183 if (buf == MAP_FAILED) {
1184 errno = ENOSPC;
1185 return NULL;
1188 hdr = (struct anonymous_shared_header *)buf;
1189 hdr->u.length = bufsz;
1191 ptr = (void *)(&hdr[1]);
1193 return ptr;
1194 #else
1195 errno = ENOSPC;
1196 return NULL;
1197 #endif
1200 void anonymous_shared_free(void *ptr)
1202 struct anonymous_shared_header *hdr;
1204 if (ptr == NULL) {
1205 return;
1208 hdr = (struct anonymous_shared_header *)ptr;
1210 hdr--;
1212 munmap(hdr, hdr->u.length);
1215 #ifdef DEVELOPER
1216 /* used when you want a debugger started at a particular point in the
1217 code. Mostly useful in code that runs as a child process, where
1218 normal gdb attach is harder to organise.
1220 void samba_start_debugger(void)
1222 char *cmd = NULL;
1223 if (asprintf(&cmd, "xterm -e \"gdb --pid %u\"&", getpid()) == -1) {
1224 return;
1226 if (system(cmd) == -1) {
1227 free(cmd);
1228 return;
1230 free(cmd);
1231 sleep(2);
1233 #endif