util: Ensure debugger can be attached to process
[Samba.git] / lib / util / util.c
blobb175b22cf13d664ed081d9d06704109470d00d37
1 /*
2 Unix SMB/CIFS implementation.
3 Samba utility functions
4 Copyright (C) Andrew Tridgell 1992-1998
5 Copyright (C) Jeremy Allison 2001-2002
6 Copyright (C) Simo Sorce 2001-2011
7 Copyright (C) Jim McDonough (jmcd@us.ibm.com) 2003.
8 Copyright (C) James J Myers 2003
9 Copyright (C) Volker Lendecke 2010
10 Copyright (C) Swen Schillig 2019
12 This program is free software; you can redistribute it and/or modify
13 it under the terms of the GNU General Public License as published by
14 the Free Software Foundation; either version 3 of the License, or
15 (at your option) any later version.
17 This program is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 GNU General Public License for more details.
22 You should have received a copy of the GNU General Public License
23 along with this program. If not, see <http://www.gnu.org/licenses/>.
26 #include "replace.h"
27 #include <talloc.h>
28 #include "system/network.h"
29 #include "system/filesys.h"
30 #include "system/locale.h"
31 #include "system/shmem.h"
32 #include "system/passwd.h"
33 #include "system/time.h"
34 #include "system/wait.h"
35 #include "debug.h"
36 #include "samba_util.h"
37 #include "lib/util/select.h"
38 #include <libgen.h>
40 #ifdef HAVE_SYS_PRCTL_H
41 #include <sys/prctl.h>
42 #endif
44 #undef malloc
45 #undef strcasecmp
46 #undef strncasecmp
47 #undef strdup
48 #undef realloc
49 #undef calloc
51 /**
52 * @file
53 * @brief Misc utility functions
56 /**
57 Find a suitable temporary directory. The result should be copied immediately
58 as it may be overwritten by a subsequent call.
59 **/
60 _PUBLIC_ const char *tmpdir(void)
62 char *p;
63 if ((p = getenv("TMPDIR")))
64 return p;
65 return "/tmp";
69 /**
70 Create a tmp file, open it and immediately unlink it.
71 If dir is NULL uses tmpdir()
72 Returns the file descriptor or -1 on error.
73 **/
74 int create_unlink_tmp(const char *dir)
76 size_t len = strlen(dir ? dir : (dir = tmpdir()));
77 char fname[len+25];
78 int fd;
79 mode_t mask;
81 len = snprintf(fname, sizeof(fname), "%s/listenerlock_XXXXXX", dir);
82 if (len >= sizeof(fname)) {
83 errno = ENOMEM;
84 return -1;
86 mask = umask(S_IRWXO | S_IRWXG);
87 fd = mkstemp(fname);
88 umask(mask);
89 if (fd == -1) {
90 return -1;
92 if (unlink(fname) == -1) {
93 int sys_errno = errno;
94 close(fd);
95 errno = sys_errno;
96 return -1;
98 return fd;
103 Check if a file exists - call vfs_file_exist for samba files.
105 _PUBLIC_ bool file_exist(const char *fname)
107 struct stat st;
109 if (stat(fname, &st) != 0) {
110 return false;
113 return ((S_ISREG(st.st_mode)) || (S_ISFIFO(st.st_mode)));
117 Check a files mod time.
120 _PUBLIC_ time_t file_modtime(const char *fname)
122 struct stat st;
124 if (stat(fname,&st) != 0)
125 return(0);
127 return(st.st_mtime);
131 Check file permissions.
134 _PUBLIC_ bool file_check_permissions(const char *fname,
135 uid_t uid,
136 mode_t file_perms,
137 struct stat *pst)
139 int ret;
140 struct stat st;
142 if (pst == NULL) {
143 pst = &st;
146 ZERO_STRUCTP(pst);
148 ret = stat(fname, pst);
149 if (ret != 0) {
150 DEBUG(0, ("stat failed on file '%s': %s\n",
151 fname, strerror(errno)));
152 return false;
155 if (pst->st_uid != uid && !uid_wrapper_enabled()) {
156 DEBUG(0, ("invalid ownership of file '%s': "
157 "owned by uid %u, should be %u\n",
158 fname, (unsigned int)pst->st_uid,
159 (unsigned int)uid));
160 return false;
163 if ((pst->st_mode & 0777) != file_perms) {
164 DEBUG(0, ("invalid permissions on file "
165 "'%s': has 0%o should be 0%o\n", fname,
166 (unsigned int)(pst->st_mode & 0777),
167 (unsigned int)file_perms));
168 return false;
171 return true;
175 Check if a directory exists.
178 _PUBLIC_ bool directory_exist(const char *dname)
180 struct stat st;
181 bool ret;
183 if (stat(dname,&st) != 0) {
184 return false;
187 ret = S_ISDIR(st.st_mode);
188 if(!ret)
189 errno = ENOTDIR;
190 return ret;
194 * Try to create the specified directory if it didn't exist.
195 * A symlink to a directory is also accepted as a valid existing directory.
197 * @retval true if the directory already existed
198 * or was successfully created.
200 _PUBLIC_ bool directory_create_or_exist(const char *dname,
201 mode_t dir_perms)
203 int ret;
204 mode_t old_umask;
206 /* Create directory */
207 old_umask = umask(0);
208 ret = mkdir(dname, dir_perms);
209 if (ret == -1 && errno != EEXIST) {
210 int dbg_level = geteuid() == 0 ? DBGLVL_ERR : DBGLVL_NOTICE;
212 DBG_PREFIX(dbg_level,
213 ("mkdir failed on directory %s: %s\n",
214 dname,
215 strerror(errno)));
216 umask(old_umask);
217 return false;
219 umask(old_umask);
221 if (ret != 0 && errno == EEXIST) {
222 struct stat sbuf;
224 ret = lstat(dname, &sbuf);
225 if (ret != 0) {
226 return false;
229 if (S_ISDIR(sbuf.st_mode)) {
230 return true;
233 if (S_ISLNK(sbuf.st_mode)) {
234 ret = stat(dname, &sbuf);
235 if (ret != 0) {
236 return false;
239 if (S_ISDIR(sbuf.st_mode)) {
240 return true;
244 return false;
247 return true;
250 _PUBLIC_ bool directory_create_or_exists_recursive(
251 const char *dname,
252 mode_t dir_perms)
254 bool ok;
256 ok = directory_create_or_exist(dname, dir_perms);
257 if (!ok) {
258 if (!directory_exist(dname)) {
259 char tmp[PATH_MAX] = {0};
260 char *parent = NULL;
261 size_t n;
263 /* Use the null context */
264 n = strlcpy(tmp, dname, sizeof(tmp));
265 if (n < strlen(dname)) {
266 DBG_ERR("Path too long!\n");
267 return false;
270 parent = dirname(tmp);
271 if (parent == NULL) {
272 DBG_ERR("Failed to create dirname!\n");
273 return false;
276 ok = directory_create_or_exists_recursive(parent,
277 dir_perms);
278 if (!ok) {
279 return false;
282 ok = directory_create_or_exist(dname, dir_perms);
286 return ok;
290 * @brief Try to create a specified directory if it doesn't exist.
292 * The function creates a directory with the given uid and permissions if it
293 * doesn't exist. If it exists it makes sure the uid and permissions are
294 * correct and it will fail if they are different.
296 * @param[in] dname The directory to create.
298 * @param[in] uid The uid the directory needs to belong too.
300 * @param[in] dir_perms The expected permissions of the directory.
302 * @return True on success, false on error.
304 _PUBLIC_ bool directory_create_or_exist_strict(const char *dname,
305 uid_t uid,
306 mode_t dir_perms)
308 struct stat st;
309 bool ok;
310 int rc;
312 ok = directory_create_or_exist(dname, dir_perms);
313 if (!ok) {
314 return false;
317 rc = lstat(dname, &st);
318 if (rc == -1) {
319 DEBUG(0, ("lstat failed on created directory %s: %s\n",
320 dname, strerror(errno)));
321 return false;
324 /* Check ownership and permission on existing directory */
325 if (!S_ISDIR(st.st_mode)) {
326 DEBUG(0, ("directory %s isn't a directory\n",
327 dname));
328 return false;
330 if (st.st_uid != uid && !uid_wrapper_enabled()) {
331 DBG_NOTICE("invalid ownership on directory "
332 "%s\n", dname);
333 return false;
335 if ((st.st_mode & 0777) != dir_perms) {
336 DEBUG(0, ("invalid permissions on directory "
337 "'%s': has 0%o should be 0%o\n", dname,
338 (unsigned int)(st.st_mode & 0777), (unsigned int)dir_perms));
339 return false;
342 return true;
347 Sleep for a specified number of milliseconds.
350 _PUBLIC_ void smb_msleep(unsigned int t)
352 sys_poll_intr(NULL, 0, t);
356 Get my own name, return in talloc'ed storage.
359 _PUBLIC_ char *get_myname(TALLOC_CTX *ctx)
361 char *p;
362 char hostname[HOST_NAME_MAX];
364 /* get my host name */
365 if (gethostname(hostname, sizeof(hostname)) == -1) {
366 DEBUG(0,("gethostname failed\n"));
367 return NULL;
370 /* Ensure null termination. */
371 hostname[sizeof(hostname)-1] = '\0';
373 /* split off any parts after an initial . */
374 p = strchr_m(hostname, '.');
375 if (p) {
376 *p = 0;
379 return talloc_strdup(ctx, hostname);
383 Check if a process exists. Does this work on all unixes?
386 _PUBLIC_ bool process_exists_by_pid(pid_t pid)
388 /* Doing kill with a non-positive pid causes messages to be
389 * sent to places we don't want. */
390 if (pid <= 0) {
391 return false;
393 return(kill(pid,0) == 0 || errno != ESRCH);
397 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
398 is dealt with in posix.c
401 _PUBLIC_ bool fcntl_lock(int fd, int op, off_t offset, off_t count, int type)
403 struct flock lock;
404 int ret;
406 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
408 lock.l_type = type;
409 lock.l_whence = SEEK_SET;
410 lock.l_start = offset;
411 lock.l_len = count;
412 lock.l_pid = 0;
414 ret = fcntl(fd,op,&lock);
416 if (ret == -1 && errno != 0)
417 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
419 /* a lock query */
420 if (op == F_GETLK) {
421 if ((ret != -1) &&
422 (lock.l_type != F_UNLCK) &&
423 (lock.l_pid != 0) &&
424 (lock.l_pid != getpid())) {
425 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
426 return true;
429 /* it must be not locked or locked by me */
430 return false;
433 /* a lock set or unset */
434 if (ret == -1) {
435 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
436 (double)offset,(double)count,op,type,strerror(errno)));
437 return false;
440 /* everything went OK */
441 DEBUG(8,("fcntl_lock: Lock call successful\n"));
443 return true;
446 struct debug_channel_level {
447 int channel;
448 int level;
451 static void debugadd_channel_cb(const char *buf, void *private_data)
453 struct debug_channel_level *dcl =
454 (struct debug_channel_level *)private_data;
456 DEBUGADDC(dcl->channel, dcl->level,("%s", buf));
459 static void debugadd_cb(const char *buf, void *private_data)
461 int *plevel = (int *)private_data;
462 DEBUGADD(*plevel, ("%s", buf));
465 void print_asc_cb(const uint8_t *buf, int len,
466 void (*cb)(const char *buf, void *private_data),
467 void *private_data)
469 int i;
470 char s[2];
471 s[1] = 0;
473 for (i=0; i<len; i++) {
474 s[0] = isprint(buf[i]) ? buf[i] : '.';
475 cb(s, private_data);
479 void print_asc(int level, const uint8_t *buf,int len)
481 print_asc_cb(buf, len, debugadd_cb, &level);
485 * Write dump of binary data to a callback
487 void dump_data_cb(const uint8_t *buf, int len,
488 bool omit_zero_bytes,
489 void (*cb)(const char *buf, void *private_data),
490 void *private_data)
492 int i=0;
493 bool skipped = false;
494 char tmp[16];
496 if (len<=0) return;
498 for (i=0;i<len;) {
500 if (i%16 == 0) {
501 if ((omit_zero_bytes == true) &&
502 (i > 0) &&
503 (len > i+16) &&
504 all_zero(&buf[i], 16))
506 i +=16;
507 continue;
510 if (i<len) {
511 snprintf(tmp, sizeof(tmp), "[%04X] ", i);
512 cb(tmp, private_data);
516 snprintf(tmp, sizeof(tmp), "%02X ", (int)buf[i]);
517 cb(tmp, private_data);
518 i++;
519 if (i%8 == 0) {
520 cb(" ", private_data);
522 if (i%16 == 0) {
524 print_asc_cb(&buf[i-16], 8, cb, private_data);
525 cb(" ", private_data);
526 print_asc_cb(&buf[i-8], 8, cb, private_data);
527 cb("\n", private_data);
529 if ((omit_zero_bytes == true) &&
530 (len > i+16) &&
531 all_zero(&buf[i], 16)) {
532 if (!skipped) {
533 cb("skipping zero buffer bytes\n",
534 private_data);
535 skipped = true;
541 if (i%16) {
542 int n;
543 n = 16 - (i%16);
544 cb(" ", private_data);
545 if (n>8) {
546 cb(" ", private_data);
548 while (n--) {
549 cb(" ", private_data);
551 n = MIN(8,i%16);
552 print_asc_cb(&buf[i-(i%16)], n, cb, private_data);
553 cb(" ", private_data);
554 n = (i%16) - n;
555 if (n>0) {
556 print_asc_cb(&buf[i-n], n, cb, private_data);
558 cb("\n", 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 malloc that aborts with smb_panic on fail or zero size.
622 _PUBLIC_ void *smb_xmalloc(size_t size)
624 void *p;
625 if (size == 0)
626 smb_panic("smb_xmalloc: called with zero size.\n");
627 if ((p = malloc(size)) == NULL)
628 smb_panic("smb_xmalloc: malloc fail.\n");
629 return p;
633 Memdup with smb_panic on fail.
636 _PUBLIC_ void *smb_xmemdup(const void *p, size_t size)
638 void *p2;
639 p2 = smb_xmalloc(size);
640 memcpy(p2, p, size);
641 return p2;
645 strdup that aborts on malloc fail.
648 char *smb_xstrdup(const char *s)
650 #if defined(PARANOID_MALLOC_CHECKER)
651 #ifdef strdup
652 #undef strdup
653 #endif
654 #endif
656 #ifndef HAVE_STRDUP
657 #define strdup rep_strdup
658 #endif
660 char *s1 = strdup(s);
661 #if defined(PARANOID_MALLOC_CHECKER)
662 #ifdef strdup
663 #undef strdup
664 #endif
665 #define strdup(s) __ERROR_DONT_USE_STRDUP_DIRECTLY
666 #endif
667 if (!s1) {
668 smb_panic("smb_xstrdup: malloc failed");
670 return s1;
675 strndup that aborts on malloc fail.
678 char *smb_xstrndup(const char *s, size_t n)
680 #if defined(PARANOID_MALLOC_CHECKER)
681 #ifdef strndup
682 #undef strndup
683 #endif
684 #endif
686 #if (defined(BROKEN_STRNDUP) || !defined(HAVE_STRNDUP))
687 #undef HAVE_STRNDUP
688 #define strndup rep_strndup
689 #endif
691 char *s1 = strndup(s, n);
692 #if defined(PARANOID_MALLOC_CHECKER)
693 #ifdef strndup
694 #undef strndup
695 #endif
696 #define strndup(s,n) __ERROR_DONT_USE_STRNDUP_DIRECTLY
697 #endif
698 if (!s1) {
699 smb_panic("smb_xstrndup: malloc failed");
701 return s1;
707 Like strdup but for memory.
710 _PUBLIC_ void *smb_memdup(const void *p, size_t size)
712 void *p2;
713 if (size == 0)
714 return NULL;
715 p2 = malloc(size);
716 if (!p2)
717 return NULL;
718 memcpy(p2, p, size);
719 return p2;
723 * Write a password to the log file.
725 * @note Only actually does something if DEBUG_PASSWORD was defined during
726 * compile-time.
728 _PUBLIC_ void dump_data_pw(const char *msg, const uint8_t * data, size_t len)
730 #ifdef DEBUG_PASSWORD
731 DEBUG(11, ("%s", msg));
732 if (data != NULL && len > 0)
734 dump_data(11, data, len);
736 #endif
741 * see if a range of memory is all zero. A NULL pointer is considered
742 * to be all zero
744 _PUBLIC_ bool all_zero(const uint8_t *ptr, size_t size)
746 size_t i;
747 if (!ptr) return true;
748 for (i=0;i<size;i++) {
749 if (ptr[i]) return false;
751 return true;
755 realloc an array, checking for integer overflow in the array size
757 _PUBLIC_ void *realloc_array(void *ptr, size_t el_size, unsigned count, bool free_on_fail)
759 #define MAX_MALLOC_SIZE 0x7fffffff
760 if (count == 0 ||
761 count >= MAX_MALLOC_SIZE/el_size) {
762 if (free_on_fail)
763 SAFE_FREE(ptr);
764 return NULL;
766 if (!ptr) {
767 return malloc(el_size * count);
769 return realloc(ptr, el_size * count);
772 /****************************************************************************
773 Type-safe malloc.
774 ****************************************************************************/
776 void *malloc_array(size_t el_size, unsigned int count)
778 return realloc_array(NULL, el_size, count, false);
781 /****************************************************************************
782 Type-safe memalign
783 ****************************************************************************/
785 void *memalign_array(size_t el_size, size_t align, unsigned int count)
787 if (el_size == 0 || count >= MAX_MALLOC_SIZE/el_size) {
788 return NULL;
791 return memalign(align, el_size*count);
794 /****************************************************************************
795 Type-safe calloc.
796 ****************************************************************************/
798 void *calloc_array(size_t size, size_t nmemb)
800 if (nmemb >= MAX_MALLOC_SIZE/size) {
801 return NULL;
803 if (size == 0 || nmemb == 0) {
804 return NULL;
806 return calloc(nmemb, size);
810 Trim the specified elements off the front and back of a string.
812 _PUBLIC_ bool trim_string(char *s, const char *front, const char *back)
814 bool ret = false;
815 size_t front_len;
816 size_t back_len;
817 size_t len;
819 /* Ignore null or empty strings. */
820 if (!s || (s[0] == '\0')) {
821 return false;
823 len = strlen(s);
825 front_len = front? strlen(front) : 0;
826 back_len = back? strlen(back) : 0;
828 if (front_len) {
829 size_t front_trim = 0;
831 while (strncmp(s+front_trim, front, front_len)==0) {
832 front_trim += front_len;
834 if (front_trim > 0) {
835 /* Must use memmove here as src & dest can
836 * easily overlap. Found by valgrind. JRA. */
837 memmove(s, s+front_trim, (len-front_trim)+1);
838 len -= front_trim;
839 ret=true;
843 if (back_len) {
844 while ((len >= back_len) && strncmp(s+len-back_len,back,back_len)==0) {
845 s[len-back_len]='\0';
846 len -= back_len;
847 ret=true;
850 return ret;
854 Find the number of 'c' chars in a string
856 _PUBLIC_ _PURE_ size_t count_chars(const char *s, char c)
858 size_t count = 0;
860 while (*s) {
861 if (*s == c) count++;
862 s ++;
865 return count;
869 * Routine to get hex characters and turn them into a byte array.
870 * the array can be variable length.
871 * - "0xnn" or "0Xnn" is specially catered for.
872 * - The first non-hex-digit character (apart from possibly leading "0x"
873 * finishes the conversion and skips the rest of the input.
874 * - A single hex-digit character at the end of the string is skipped.
876 * valid examples: "0A5D15"; "0x123456"
878 _PUBLIC_ size_t strhex_to_str(char *p, size_t p_len, const char *strhex, size_t strhex_len)
880 size_t i = 0;
881 size_t num_chars = 0;
883 /* skip leading 0x prefix */
884 if (strncasecmp(strhex, "0x", 2) == 0) {
885 i += 2; /* skip two chars */
888 while ((i < strhex_len) && (num_chars < p_len)) {
889 bool ok = hex_byte(&strhex[i], (uint8_t *)&p[num_chars]);
890 if (!ok) {
891 break;
893 i += 2;
894 num_chars += 1;
897 return num_chars;
901 * Parse a hex string and return a data blob.
903 _PUBLIC_ DATA_BLOB strhex_to_data_blob(TALLOC_CTX *mem_ctx, const char *strhex)
905 DATA_BLOB ret_blob = data_blob_talloc(mem_ctx, NULL, strlen(strhex)/2+1);
907 ret_blob.length = strhex_to_str((char *)ret_blob.data, ret_blob.length,
908 strhex,
909 strlen(strhex));
911 return ret_blob;
915 * Parse a hex dump and return a data blob. Hex dump is structured as
916 * is generated from dump_data_cb() elsewhere in this file
919 _PUBLIC_ DATA_BLOB hexdump_to_data_blob(TALLOC_CTX *mem_ctx, const char *hexdump, size_t hexdump_len)
921 DATA_BLOB ret_blob = { 0 };
922 size_t i = 0;
923 size_t char_count = 0;
924 /* hexdump line length is 77 chars long. We then use the ASCII representation of the bytes
925 * at the end of the final line to calculate how many are in that line, minus the extra space
926 * and newline. */
927 size_t hexdump_byte_count = (16 * (hexdump_len / 77));
928 if (hexdump_len % 77) {
929 hexdump_byte_count += ((hexdump_len % 77) - 59 - 2);
932 ret_blob = data_blob_talloc(mem_ctx, NULL, hexdump_byte_count+1);
933 for (; i+1 < hexdump_len && hexdump[i] != 0 && hexdump[i+1] != 0; i++) {
934 if ((i%77) == 0)
935 i += 7; /* Skip the offset at the start of the line */
936 if ((i%77) < 56) { /* position 56 is after both hex chunks */
937 if (hexdump[i] != ' ') {
938 char_count += strhex_to_str((char *)&ret_blob.data[char_count],
939 hexdump_byte_count - char_count,
940 &hexdump[i], 2);
941 i += 2;
942 } else {
943 i++;
945 } else {
946 i++;
949 ret_blob.length = char_count;
951 return ret_blob;
955 * Print a buf in hex. Assumes dst is at least (srclen*2)+1 large.
957 _PUBLIC_ void hex_encode_buf(char *dst, const uint8_t *src, size_t srclen)
959 size_t i;
960 for (i=0; i<srclen; i++) {
961 snprintf(dst + i*2, 3, "%02X", src[i]);
964 * Ensure 0-termination for 0-length buffers
966 dst[srclen*2] = '\0';
970 * talloc version of hex_encode_buf()
972 _PUBLIC_ char *hex_encode_talloc(TALLOC_CTX *mem_ctx, const unsigned char *buff_in, size_t len)
974 char *hex_buffer;
976 hex_buffer = talloc_array(mem_ctx, char, (len*2)+1);
977 if (!hex_buffer) {
978 return NULL;
980 hex_encode_buf(hex_buffer, buff_in, len);
981 talloc_set_name_const(hex_buffer, hex_buffer);
982 return hex_buffer;
986 varient of strcmp() that handles NULL ptrs
988 _PUBLIC_ int strcmp_safe(const char *s1, const char *s2)
990 if (s1 == s2) {
991 return 0;
993 if (s1 == NULL || s2 == NULL) {
994 return s1?-1:1;
996 return strcmp(s1, s2);
1001 return the number of bytes occupied by a buffer in ASCII format
1002 the result includes the null termination
1003 limited by 'n' bytes
1005 _PUBLIC_ size_t ascii_len_n(const char *src, size_t n)
1007 size_t len;
1009 len = strnlen(src, n);
1010 if (len+1 <= n) {
1011 len += 1;
1014 return len;
1017 struct anonymous_shared_header {
1018 union {
1019 size_t length;
1020 uint8_t pad[16];
1021 } u;
1024 /* Map a shared memory buffer of at least nelem counters. */
1025 void *anonymous_shared_allocate(size_t orig_bufsz)
1027 void *ptr;
1028 void *buf;
1029 size_t pagesz = getpagesize();
1030 size_t pagecnt;
1031 size_t bufsz = orig_bufsz;
1032 struct anonymous_shared_header *hdr;
1034 bufsz += sizeof(*hdr);
1036 /* round up to full pages */
1037 pagecnt = bufsz / pagesz;
1038 if (bufsz % pagesz) {
1039 pagecnt += 1;
1041 bufsz = pagesz * pagecnt;
1043 if (orig_bufsz >= bufsz) {
1044 /* integer wrap */
1045 errno = ENOMEM;
1046 return NULL;
1049 #ifdef MAP_ANON
1050 /* BSD */
1051 buf = mmap(NULL, bufsz, PROT_READ|PROT_WRITE, MAP_ANON|MAP_SHARED,
1052 -1 /* fd */, 0 /* offset */);
1053 #else
1055 int saved_errno;
1056 int fd;
1058 fd = open("/dev/zero", O_RDWR);
1059 if (fd == -1) {
1060 return NULL;
1063 buf = mmap(NULL, bufsz, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED,
1064 fd, 0 /* offset */);
1065 saved_errno = errno;
1066 close(fd);
1067 errno = saved_errno;
1069 #endif
1071 if (buf == MAP_FAILED) {
1072 return NULL;
1075 hdr = (struct anonymous_shared_header *)buf;
1076 hdr->u.length = bufsz;
1078 ptr = (void *)(&hdr[1]);
1080 return ptr;
1083 void *anonymous_shared_resize(void *ptr, size_t new_size, bool maymove)
1085 #ifdef HAVE_MREMAP
1086 void *buf;
1087 size_t pagesz = getpagesize();
1088 size_t pagecnt;
1089 size_t bufsz;
1090 struct anonymous_shared_header *hdr;
1091 int flags = 0;
1093 if (ptr == NULL) {
1094 errno = EINVAL;
1095 return NULL;
1098 hdr = (struct anonymous_shared_header *)ptr;
1099 hdr--;
1100 if (hdr->u.length > (new_size + sizeof(*hdr))) {
1101 errno = EINVAL;
1102 return NULL;
1105 bufsz = new_size + sizeof(*hdr);
1107 /* round up to full pages */
1108 pagecnt = bufsz / pagesz;
1109 if (bufsz % pagesz) {
1110 pagecnt += 1;
1112 bufsz = pagesz * pagecnt;
1114 if (new_size >= bufsz) {
1115 /* integer wrap */
1116 errno = ENOSPC;
1117 return NULL;
1120 if (bufsz <= hdr->u.length) {
1121 return ptr;
1124 if (maymove) {
1125 flags = MREMAP_MAYMOVE;
1128 buf = mremap(hdr, hdr->u.length, bufsz, flags);
1130 if (buf == MAP_FAILED) {
1131 errno = ENOSPC;
1132 return NULL;
1135 hdr = (struct anonymous_shared_header *)buf;
1136 hdr->u.length = bufsz;
1138 ptr = (void *)(&hdr[1]);
1140 return ptr;
1141 #else
1142 errno = ENOSPC;
1143 return NULL;
1144 #endif
1147 void anonymous_shared_free(void *ptr)
1149 struct anonymous_shared_header *hdr;
1151 if (ptr == NULL) {
1152 return;
1155 hdr = (struct anonymous_shared_header *)ptr;
1157 hdr--;
1159 munmap(hdr, hdr->u.length);
1162 #ifdef DEVELOPER
1163 /* used when you want a debugger started at a particular point in the
1164 code. Mostly useful in code that runs as a child process, where
1165 normal gdb attach is harder to organise.
1167 void samba_start_debugger(void)
1169 pid_t pid = fork();
1170 if (pid == -1) {
1171 return;
1172 } else if (pid) {
1173 #if defined(HAVE_PRCTL) && defined(PR_SET_PTRACER)
1175 * Make sure the child process can attach a debugger.
1177 prctl(PR_SET_PTRACER, pid, 0, 0, 0);
1178 #endif
1179 sleep(2);
1180 } else {
1181 char *cmd = NULL;
1183 if (asprintf(&cmd, "gdb --pid %u", getppid()) == -1) {
1184 _exit(EXIT_FAILURE);
1187 execlp("xterm", "xterm", "-e", cmd, (char *) NULL);
1188 free(cmd);
1189 _exit(errno);
1192 #endif