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/>.
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"
35 #include "samba_util.h"
36 #include "lib/util/select.h"
47 * @brief Misc utility functions
51 Find a suitable temporary directory. The result should be copied immediately
52 as it may be overwritten by a subsequent call.
54 _PUBLIC_ const char *tmpdir(void)
57 if ((p = getenv("TMPDIR")))
64 Create a tmp file, open it and immediately unlink it.
65 If dir is NULL uses tmpdir()
66 Returns the file descriptor or -1 on error.
68 int create_unlink_tmp(const char *dir)
70 size_t len = strlen(dir ? dir : (dir = tmpdir()));
75 len = snprintf(fname, sizeof(fname), "%s/listenerlock_XXXXXX", dir);
76 if (len >= sizeof(fname)) {
80 mask = umask(S_IRWXO | S_IRWXG);
86 if (unlink(fname) == -1) {
87 int sys_errno = errno;
97 Check if a file exists - call vfs_file_exist for samba files.
99 _PUBLIC_ bool file_exist(const char *fname)
103 if (stat(fname, &st) != 0) {
107 return ((S_ISREG(st.st_mode)) || (S_ISFIFO(st.st_mode)));
111 Check a files mod time.
114 _PUBLIC_ time_t file_modtime(const char *fname)
118 if (stat(fname,&st) != 0)
125 Check file permissions.
128 _PUBLIC_ bool file_check_permissions(const char *fname,
142 ret = stat(fname, pst);
144 DEBUG(0, ("stat failed on file '%s': %s\n",
145 fname, strerror(errno)));
149 if (pst->st_uid != uid && !uid_wrapper_enabled()) {
150 DEBUG(0, ("invalid ownership of file '%s': "
151 "owned by uid %u, should be %u\n",
152 fname, (unsigned int)pst->st_uid,
157 if ((pst->st_mode & 0777) != file_perms) {
158 DEBUG(0, ("invalid permissions on file "
159 "'%s': has 0%o should be 0%o\n", fname,
160 (unsigned int)(pst->st_mode & 0777),
161 (unsigned int)file_perms));
169 Check if a directory exists.
172 _PUBLIC_ bool directory_exist(const char *dname)
177 if (stat(dname,&st) != 0) {
181 ret = S_ISDIR(st.st_mode);
188 * Try to create the specified directory if it didn't exist.
190 * @retval true if the directory already existed
191 * or was successfully created.
193 _PUBLIC_ bool directory_create_or_exist(const char *dname,
200 ret = lstat(dname, &st);
205 if (errno != ENOENT) {
206 DBG_WARNING("lstat failed on directory %s: %s\n",
207 dname, strerror(errno));
211 /* Create directory */
212 old_umask = umask(0);
213 ret = mkdir(dname, dir_perms);
214 if (ret == -1 && errno != EEXIST) {
215 DEBUG(0, ("mkdir failed on directory "
223 ret = lstat(dname, &st);
225 DEBUG(0, ("lstat failed on created directory %s: %s\n",
226 dname, strerror(errno)));
234 * @brief Try to create a specified directory if it doesn't exist.
236 * The function creates a directory with the given uid and permissions if it
237 * doesn't exist. If it exists it makes sure the uid and permissions are
238 * correct and it will fail if they are different.
240 * @param[in] dname The directory to create.
242 * @param[in] uid The uid the directory needs to belong too.
244 * @param[in] dir_perms The expected permissions of the directory.
246 * @return True on success, false on error.
248 _PUBLIC_ bool directory_create_or_exist_strict(const char *dname,
256 ok = directory_create_or_exist(dname, dir_perms);
261 rc = lstat(dname, &st);
263 DEBUG(0, ("lstat failed on created directory %s: %s\n",
264 dname, strerror(errno)));
268 /* Check ownership and permission on existing directory */
269 if (!S_ISDIR(st.st_mode)) {
270 DEBUG(0, ("directory %s isn't a directory\n",
274 if (st.st_uid != uid && !uid_wrapper_enabled()) {
275 DBG_NOTICE("invalid ownership on directory "
279 if ((st.st_mode & 0777) != dir_perms) {
280 DEBUG(0, ("invalid permissions on directory "
281 "'%s': has 0%o should be 0%o\n", dname,
282 (unsigned int)(st.st_mode & 0777), (unsigned int)dir_perms));
291 Sleep for a specified number of milliseconds.
294 _PUBLIC_ void smb_msleep(unsigned int t)
296 sys_poll_intr(NULL, 0, t);
300 Get my own name, return in talloc'ed storage.
303 _PUBLIC_ char *get_myname(TALLOC_CTX *ctx)
306 char hostname[HOST_NAME_MAX];
308 /* get my host name */
309 if (gethostname(hostname, sizeof(hostname)) == -1) {
310 DEBUG(0,("gethostname failed\n"));
314 /* Ensure null termination. */
315 hostname[sizeof(hostname)-1] = '\0';
317 /* split off any parts after an initial . */
318 p = strchr_m(hostname, '.');
323 return talloc_strdup(ctx, hostname);
327 Check if a process exists. Does this work on all unixes?
330 _PUBLIC_ bool process_exists_by_pid(pid_t pid)
332 /* Doing kill with a non-positive pid causes messages to be
333 * sent to places we don't want. */
337 return(kill(pid,0) == 0 || errno != ESRCH);
341 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
342 is dealt with in posix.c
345 _PUBLIC_ bool fcntl_lock(int fd, int op, off_t offset, off_t count, int type)
350 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
353 lock.l_whence = SEEK_SET;
354 lock.l_start = offset;
358 ret = fcntl(fd,op,&lock);
360 if (ret == -1 && errno != 0)
361 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
366 (lock.l_type != F_UNLCK) &&
368 (lock.l_pid != getpid())) {
369 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
373 /* it must be not locked or locked by me */
377 /* a lock set or unset */
379 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
380 (double)offset,(double)count,op,type,strerror(errno)));
384 /* everything went OK */
385 DEBUG(8,("fcntl_lock: Lock call successful\n"));
390 struct debug_channel_level {
395 static void debugadd_channel_cb(const char *buf, void *private_data)
397 struct debug_channel_level *dcl =
398 (struct debug_channel_level *)private_data;
400 DEBUGADDC(dcl->channel, dcl->level,("%s", buf));
403 static void debugadd_cb(const char *buf, void *private_data)
405 int *plevel = (int *)private_data;
406 DEBUGADD(*plevel, ("%s", buf));
409 void print_asc_cb(const uint8_t *buf, int len,
410 void (*cb)(const char *buf, void *private_data),
417 for (i=0; i<len; i++) {
418 s[0] = isprint(buf[i]) ? buf[i] : '.';
423 void print_asc(int level, const uint8_t *buf,int len)
425 print_asc_cb(buf, len, debugadd_cb, &level);
429 * Write dump of binary data to a callback
431 void dump_data_cb(const uint8_t *buf, int len,
432 bool omit_zero_bytes,
433 void (*cb)(const char *buf, void *private_data),
437 static const uint8_t empty[16] = { 0, };
438 bool skipped = false;
446 if ((omit_zero_bytes == true) &&
449 (memcmp(&buf[i], &empty, 16) == 0))
456 snprintf(tmp, sizeof(tmp), "[%04X] ", i);
457 cb(tmp, private_data);
461 snprintf(tmp, sizeof(tmp), "%02X ", (int)buf[i]);
462 cb(tmp, private_data);
465 cb(" ", private_data);
469 print_asc_cb(&buf[i-16], 8, cb, private_data);
470 cb(" ", private_data);
471 print_asc_cb(&buf[i-8], 8, cb, private_data);
472 cb("\n", private_data);
474 if ((omit_zero_bytes == true) &&
476 (memcmp(&buf[i], &empty, 16) == 0)) {
478 cb("skipping zero buffer bytes\n",
489 cb(" ", private_data);
491 cb(" ", private_data);
494 cb(" ", private_data);
497 print_asc_cb(&buf[i-(i%16)], n, cb, private_data);
498 cb(" ", private_data);
501 print_asc_cb(&buf[i-n], n, cb, private_data);
503 cb("\n", private_data);
509 * Write dump of binary data to the log file.
511 * The data is only written if the log level is at least level.
513 _PUBLIC_ void dump_data(int level, const uint8_t *buf, int len)
515 if (!DEBUGLVL(level)) {
518 dump_data_cb(buf, len, false, debugadd_cb, &level);
522 * Write dump of binary data to the log file.
524 * The data is only written if the log level is at least level for
525 * debug class dbgc_class.
527 _PUBLIC_ void dump_data_dbgc(int dbgc_class, int level, const uint8_t *buf, int len)
529 struct debug_channel_level dcl = { dbgc_class, level };
531 if (!DEBUGLVLC(dbgc_class, level)) {
534 dump_data_cb(buf, len, false, debugadd_channel_cb, &dcl);
538 * Write dump of binary data to the log file.
540 * The data is only written if the log level is at least level.
541 * 16 zero bytes in a row are omitted
543 _PUBLIC_ void dump_data_skip_zeros(int level, const uint8_t *buf, int len)
545 if (!DEBUGLVL(level)) {
548 dump_data_cb(buf, len, true, debugadd_cb, &level);
551 static void fprintf_cb(const char *buf, void *private_data)
553 FILE *f = (FILE *)private_data;
554 fprintf(f, "%s", buf);
557 void dump_data_file(const uint8_t *buf, int len, bool omit_zero_bytes,
560 dump_data_cb(buf, len, omit_zero_bytes, fprintf_cb, f);
564 malloc that aborts with smb_panic on fail or zero size.
567 _PUBLIC_ void *smb_xmalloc(size_t size)
571 smb_panic("smb_xmalloc: called with zero size.\n");
572 if ((p = malloc(size)) == NULL)
573 smb_panic("smb_xmalloc: malloc fail.\n");
578 Memdup with smb_panic on fail.
581 _PUBLIC_ void *smb_xmemdup(const void *p, size_t size)
584 p2 = smb_xmalloc(size);
590 strdup that aborts on malloc fail.
593 char *smb_xstrdup(const char *s)
595 #if defined(PARANOID_MALLOC_CHECKER)
602 #define strdup rep_strdup
605 char *s1 = strdup(s);
606 #if defined(PARANOID_MALLOC_CHECKER)
610 #define strdup(s) __ERROR_DONT_USE_STRDUP_DIRECTLY
613 smb_panic("smb_xstrdup: malloc failed");
620 strndup that aborts on malloc fail.
623 char *smb_xstrndup(const char *s, size_t n)
625 #if defined(PARANOID_MALLOC_CHECKER)
631 #if (defined(BROKEN_STRNDUP) || !defined(HAVE_STRNDUP))
633 #define strndup rep_strndup
636 char *s1 = strndup(s, n);
637 #if defined(PARANOID_MALLOC_CHECKER)
641 #define strndup(s,n) __ERROR_DONT_USE_STRNDUP_DIRECTLY
644 smb_panic("smb_xstrndup: malloc failed");
652 Like strdup but for memory.
655 _PUBLIC_ void *smb_memdup(const void *p, size_t size)
668 * Write a password to the log file.
670 * @note Only actually does something if DEBUG_PASSWORD was defined during
673 _PUBLIC_ void dump_data_pw(const char *msg, const uint8_t * data, size_t len)
675 #ifdef DEBUG_PASSWORD
676 DEBUG(11, ("%s", msg));
677 if (data != NULL && len > 0)
679 dump_data(11, data, len);
686 * see if a range of memory is all zero. A NULL pointer is considered
689 _PUBLIC_ bool all_zero(const uint8_t *ptr, size_t size)
692 if (!ptr) return true;
693 for (i=0;i<size;i++) {
694 if (ptr[i]) return false;
700 realloc an array, checking for integer overflow in the array size
702 _PUBLIC_ void *realloc_array(void *ptr, size_t el_size, unsigned count, bool free_on_fail)
704 #define MAX_MALLOC_SIZE 0x7fffffff
706 count >= MAX_MALLOC_SIZE/el_size) {
712 return malloc(el_size * count);
714 return realloc(ptr, el_size * count);
717 /****************************************************************************
719 ****************************************************************************/
721 void *malloc_array(size_t el_size, unsigned int count)
723 return realloc_array(NULL, el_size, count, false);
726 /****************************************************************************
728 ****************************************************************************/
730 void *memalign_array(size_t el_size, size_t align, unsigned int count)
732 if (el_size == 0 || count >= MAX_MALLOC_SIZE/el_size) {
736 return memalign(align, el_size*count);
739 /****************************************************************************
741 ****************************************************************************/
743 void *calloc_array(size_t size, size_t nmemb)
745 if (nmemb >= MAX_MALLOC_SIZE/size) {
748 if (size == 0 || nmemb == 0) {
751 return calloc(nmemb, size);
755 Trim the specified elements off the front and back of a string.
757 _PUBLIC_ bool trim_string(char *s, const char *front, const char *back)
764 /* Ignore null or empty strings. */
765 if (!s || (s[0] == '\0')) {
770 front_len = front? strlen(front) : 0;
771 back_len = back? strlen(back) : 0;
774 size_t front_trim = 0;
776 while (strncmp(s+front_trim, front, front_len)==0) {
777 front_trim += front_len;
779 if (front_trim > 0) {
780 /* Must use memmove here as src & dest can
781 * easily overlap. Found by valgrind. JRA. */
782 memmove(s, s+front_trim, (len-front_trim)+1);
789 while ((len >= back_len) && strncmp(s+len-back_len,back,back_len)==0) {
790 s[len-back_len]='\0';
799 Find the number of 'c' chars in a string
801 _PUBLIC_ _PURE_ size_t count_chars(const char *s, char c)
806 if (*s == c) count++;
814 * Routine to get hex characters and turn them into a byte array.
815 * the array can be variable length.
816 * - "0xnn" or "0Xnn" is specially catered for.
817 * - The first non-hex-digit character (apart from possibly leading "0x"
818 * finishes the conversion and skips the rest of the input.
819 * - A single hex-digit character at the end of the string is skipped.
821 * valid examples: "0A5D15"; "0x123456"
823 _PUBLIC_ size_t strhex_to_str(char *p, size_t p_len, const char *strhex, size_t strhex_len)
826 size_t num_chars = 0;
827 uint8_t lonybble, hinybble;
828 const char *hexchars = "0123456789ABCDEF";
829 char *p1 = NULL, *p2 = NULL;
831 /* skip leading 0x prefix */
832 if (strncasecmp(strhex, "0x", 2) == 0) {
833 i += 2; /* skip two chars */
836 for (; i+1 < strhex_len && strhex[i] != 0 && strhex[i+1] != 0; i++) {
837 p1 = strchr(hexchars, toupper((unsigned char)strhex[i]));
842 i++; /* next hex digit */
844 p2 = strchr(hexchars, toupper((unsigned char)strhex[i]));
849 /* get the two nybbles */
850 hinybble = PTR_DIFF(p1, hexchars);
851 lonybble = PTR_DIFF(p2, hexchars);
853 if (num_chars >= p_len) {
857 p[num_chars] = (hinybble << 4) | lonybble;
867 * Parse a hex string and return a data blob.
869 _PUBLIC_ _PURE_ DATA_BLOB strhex_to_data_blob(TALLOC_CTX *mem_ctx, const char *strhex)
871 DATA_BLOB ret_blob = data_blob_talloc(mem_ctx, NULL, strlen(strhex)/2+1);
873 ret_blob.length = strhex_to_str((char *)ret_blob.data, ret_blob.length,
881 * Parse a hex dump and return a data blob. Hex dump is structured as
882 * is generated from dump_data_cb() elsewhere in this file
885 _PUBLIC_ _PURE_ DATA_BLOB hexdump_to_data_blob(TALLOC_CTX *mem_ctx, const char *hexdump, size_t hexdump_len)
887 DATA_BLOB ret_blob = { 0 };
889 size_t char_count = 0;
890 /* hexdump line length is 77 chars long. We then use the ASCII representation of the bytes
891 * at the end of the final line to calculate how many are in that line, minus the extra space
893 size_t hexdump_byte_count = (16 * (hexdump_len / 77));
894 if (hexdump_len % 77) {
895 hexdump_byte_count += ((hexdump_len % 77) - 59 - 2);
898 ret_blob = data_blob_talloc(mem_ctx, NULL, hexdump_byte_count+1);
899 for (; i+1 < hexdump_len && hexdump[i] != 0 && hexdump[i+1] != 0; i++) {
901 i += 7; /* Skip the offset at the start of the line */
902 if ((i%77) < 56) { /* position 56 is after both hex chunks */
903 if (hexdump[i] != ' ') {
904 char_count += strhex_to_str((char *)&ret_blob.data[char_count],
905 hexdump_byte_count - char_count,
915 ret_blob.length = char_count;
921 * Print a buf in hex. Assumes dst is at least (srclen*2)+1 large.
923 _PUBLIC_ void hex_encode_buf(char *dst, const uint8_t *src, size_t srclen)
926 for (i=0; i<srclen; i++) {
927 snprintf(dst + i*2, 3, "%02X", src[i]);
930 * Ensure 0-termination for 0-length buffers
932 dst[srclen*2] = '\0';
936 * talloc version of hex_encode_buf()
938 _PUBLIC_ char *hex_encode_talloc(TALLOC_CTX *mem_ctx, const unsigned char *buff_in, size_t len)
942 hex_buffer = talloc_array(mem_ctx, char, (len*2)+1);
946 hex_encode_buf(hex_buffer, buff_in, len);
947 talloc_set_name_const(hex_buffer, hex_buffer);
952 varient of strcmp() that handles NULL ptrs
954 _PUBLIC_ int strcmp_safe(const char *s1, const char *s2)
959 if (s1 == NULL || s2 == NULL) {
962 return strcmp(s1, s2);
967 return the number of bytes occupied by a buffer in ASCII format
968 the result includes the null termination
971 _PUBLIC_ size_t ascii_len_n(const char *src, size_t n)
975 len = strnlen(src, n);
983 struct anonymous_shared_header {
990 /* Map a shared memory buffer of at least nelem counters. */
991 void *anonymous_shared_allocate(size_t orig_bufsz)
995 size_t pagesz = getpagesize();
997 size_t bufsz = orig_bufsz;
998 struct anonymous_shared_header *hdr;
1000 bufsz += sizeof(*hdr);
1002 /* round up to full pages */
1003 pagecnt = bufsz / pagesz;
1004 if (bufsz % pagesz) {
1007 bufsz = pagesz * pagecnt;
1009 if (orig_bufsz >= bufsz) {
1017 buf = mmap(NULL, bufsz, PROT_READ|PROT_WRITE, MAP_ANON|MAP_SHARED,
1018 -1 /* fd */, 0 /* offset */);
1024 fd = open("/dev/zero", O_RDWR);
1029 buf = mmap(NULL, bufsz, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED,
1030 fd, 0 /* offset */);
1031 saved_errno = errno;
1033 errno = saved_errno;
1037 if (buf == MAP_FAILED) {
1041 hdr = (struct anonymous_shared_header *)buf;
1042 hdr->u.length = bufsz;
1044 ptr = (void *)(&hdr[1]);
1049 void *anonymous_shared_resize(void *ptr, size_t new_size, bool maymove)
1053 size_t pagesz = getpagesize();
1056 struct anonymous_shared_header *hdr;
1064 hdr = (struct anonymous_shared_header *)ptr;
1066 if (hdr->u.length > (new_size + sizeof(*hdr))) {
1071 bufsz = new_size + sizeof(*hdr);
1073 /* round up to full pages */
1074 pagecnt = bufsz / pagesz;
1075 if (bufsz % pagesz) {
1078 bufsz = pagesz * pagecnt;
1080 if (new_size >= bufsz) {
1086 if (bufsz <= hdr->u.length) {
1091 flags = MREMAP_MAYMOVE;
1094 buf = mremap(hdr, hdr->u.length, bufsz, flags);
1096 if (buf == MAP_FAILED) {
1101 hdr = (struct anonymous_shared_header *)buf;
1102 hdr->u.length = bufsz;
1104 ptr = (void *)(&hdr[1]);
1113 void anonymous_shared_free(void *ptr)
1115 struct anonymous_shared_header *hdr;
1121 hdr = (struct anonymous_shared_header *)ptr;
1125 munmap(hdr, hdr->u.length);
1129 /* used when you want a debugger started at a particular point in the
1130 code. Mostly useful in code that runs as a child process, where
1131 normal gdb attach is harder to organise.
1133 void samba_start_debugger(void)
1136 if (asprintf(&cmd, "xterm -e \"gdb --pid %u\"&", getpid()) == -1) {
1139 if (system(cmd) == -1) {